poly_int: TYPE_VECTOR_SUBPARTS
[official-gcc.git] / gcc / c-family / c-common.c
blobcebd1b871d1a1f1e6dce80b2409ae776be0201bf
1 /* Subroutines shared by all languages that are variants of C.
2 Copyright (C) 1992-2018 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"
52 cpp_reader *parse_in; /* Declared in c-pragma.h. */
54 /* Mode used to build pointers (VOIDmode means ptr_mode). */
56 machine_mode c_default_pointer_mode = VOIDmode;
58 /* The following symbols are subsumed in the c_global_trees array, and
59 listed here individually for documentation purposes.
61 INTEGER_TYPE and REAL_TYPE nodes for the standard data types.
63 tree short_integer_type_node;
64 tree long_integer_type_node;
65 tree long_long_integer_type_node;
67 tree short_unsigned_type_node;
68 tree long_unsigned_type_node;
69 tree long_long_unsigned_type_node;
71 tree truthvalue_type_node;
72 tree truthvalue_false_node;
73 tree truthvalue_true_node;
75 tree ptrdiff_type_node;
77 tree unsigned_char_type_node;
78 tree signed_char_type_node;
79 tree wchar_type_node;
81 tree char16_type_node;
82 tree char32_type_node;
84 tree float_type_node;
85 tree double_type_node;
86 tree long_double_type_node;
88 tree complex_integer_type_node;
89 tree complex_float_type_node;
90 tree complex_double_type_node;
91 tree complex_long_double_type_node;
93 tree dfloat32_type_node;
94 tree dfloat64_type_node;
95 tree_dfloat128_type_node;
97 tree intQI_type_node;
98 tree intHI_type_node;
99 tree intSI_type_node;
100 tree intDI_type_node;
101 tree intTI_type_node;
103 tree unsigned_intQI_type_node;
104 tree unsigned_intHI_type_node;
105 tree unsigned_intSI_type_node;
106 tree unsigned_intDI_type_node;
107 tree unsigned_intTI_type_node;
109 tree widest_integer_literal_type_node;
110 tree widest_unsigned_literal_type_node;
112 Nodes for types `void *' and `const void *'.
114 tree ptr_type_node, const_ptr_type_node;
116 Nodes for types `char *' and `const char *'.
118 tree string_type_node, const_string_type_node;
120 Type `char[SOMENUMBER]'.
121 Used when an array of char is needed and the size is irrelevant.
123 tree char_array_type_node;
125 Type `wchar_t[SOMENUMBER]' or something like it.
126 Used when a wide string literal is created.
128 tree wchar_array_type_node;
130 Type `char16_t[SOMENUMBER]' or something like it.
131 Used when a UTF-16 string literal is created.
133 tree char16_array_type_node;
135 Type `char32_t[SOMENUMBER]' or something like it.
136 Used when a UTF-32 string literal is created.
138 tree char32_array_type_node;
140 Type `int ()' -- used for implicit declaration of functions.
142 tree default_function_type;
144 A VOID_TYPE node, packaged in a TREE_LIST.
146 tree void_list_node;
148 The lazily created VAR_DECLs for __FUNCTION__, __PRETTY_FUNCTION__,
149 and __func__. (C doesn't generate __FUNCTION__ and__PRETTY_FUNCTION__
150 VAR_DECLS, but C++ does.)
152 tree function_name_decl_node;
153 tree pretty_function_name_decl_node;
154 tree c99_function_name_decl_node;
156 Stack of nested function name VAR_DECLs.
158 tree saved_function_name_decls;
162 tree c_global_trees[CTI_MAX];
164 /* Switches common to the C front ends. */
166 /* Nonzero means don't output line number information. */
168 char flag_no_line_commands;
170 /* Nonzero causes -E output not to be done, but directives such as
171 #define that have side effects are still obeyed. */
173 char flag_no_output;
175 /* Nonzero means dump macros in some fashion. */
177 char flag_dump_macros;
179 /* Nonzero means pass #include lines through to the output. */
181 char flag_dump_includes;
183 /* Nonzero means process PCH files while preprocessing. */
185 bool flag_pch_preprocess;
187 /* The file name to which we should write a precompiled header, or
188 NULL if no header will be written in this compile. */
190 const char *pch_file;
192 /* Nonzero if an ISO standard was selected. It rejects macros in the
193 user's namespace. */
194 int flag_iso;
196 /* C/ObjC language option variables. */
199 /* Nonzero means allow type mismatches in conditional expressions;
200 just make their values `void'. */
202 int flag_cond_mismatch;
204 /* Nonzero means enable C89 Amendment 1 features. */
206 int flag_isoc94;
208 /* Nonzero means use the ISO C99 (or C11) dialect of C. */
210 int flag_isoc99;
212 /* Nonzero means use the ISO C11 dialect of C. */
214 int flag_isoc11;
216 /* Nonzero means that we have builtin functions, and main is an int. */
218 int flag_hosted = 1;
221 /* ObjC language option variables. */
224 /* Tells the compiler that this is a special run. Do not perform any
225 compiling, instead we are to test some platform dependent features
226 and output a C header file with appropriate definitions. */
228 int print_struct_values;
230 /* Tells the compiler what is the constant string class for ObjC. */
232 const char *constant_string_class_name;
235 /* C++ language option variables. */
237 /* The reference version of the ABI for -Wabi. */
239 int warn_abi_version = -1;
241 /* Nonzero means generate separate instantiation control files and
242 juggle them at link time. */
244 int flag_use_repository;
246 /* The C++ dialect being used. Default set in c_common_post_options. */
248 enum cxx_dialect cxx_dialect = cxx_unset;
250 /* Maximum template instantiation depth. This limit exists to limit the
251 time it takes to notice excessively recursive template instantiations.
253 The default is lower than the 1024 recommended by the C++0x standard
254 because G++ runs out of stack before 1024 with highly recursive template
255 argument deduction substitution (g++.dg/cpp0x/enum11.C). */
257 int max_tinst_depth = 900;
259 /* The elements of `ridpointers' are identifier nodes for the reserved
260 type names and storage classes. It is indexed by a RID_... value. */
261 tree *ridpointers;
263 tree (*make_fname_decl) (location_t, tree, int);
265 /* Nonzero means don't warn about problems that occur when the code is
266 executed. */
267 int c_inhibit_evaluation_warnings;
269 /* Whether we are building a boolean conversion inside
270 convert_for_assignment, or some other late binary operation. If
271 build_binary_op is called for C (from code shared by C and C++) in
272 this case, then the operands have already been folded and the
273 result will not be folded again, so C_MAYBE_CONST_EXPR should not
274 be generated. */
275 bool in_late_binary_op;
277 /* Whether lexing has been completed, so subsequent preprocessor
278 errors should use the compiler's input_location. */
279 bool done_lexing = false;
281 /* Information about how a function name is generated. */
282 struct fname_var_t
284 tree *const decl; /* pointer to the VAR_DECL. */
285 const unsigned rid; /* RID number for the identifier. */
286 const int pretty; /* How pretty is it? */
289 /* The three ways of getting then name of the current function. */
291 const struct fname_var_t fname_vars[] =
293 /* C99 compliant __func__, must be first. */
294 {&c99_function_name_decl_node, RID_C99_FUNCTION_NAME, 0},
295 /* GCC __FUNCTION__ compliant. */
296 {&function_name_decl_node, RID_FUNCTION_NAME, 0},
297 /* GCC __PRETTY_FUNCTION__ compliant. */
298 {&pretty_function_name_decl_node, RID_PRETTY_FUNCTION_NAME, 1},
299 {NULL, 0, 0},
302 /* Global visibility options. */
303 struct visibility_flags visibility_options;
305 static tree check_case_value (location_t, tree);
306 static bool check_case_bounds (location_t, tree, tree, tree *, tree *,
307 bool *);
310 static void check_nonnull_arg (void *, tree, unsigned HOST_WIDE_INT);
311 static bool nonnull_check_p (tree, unsigned HOST_WIDE_INT);
313 /* Reserved words. The third field is a mask: keywords are disabled
314 if they match the mask.
316 Masks for languages:
317 C --std=c89: D_C99 | D_CXXONLY | D_OBJC | D_CXX_OBJC
318 C --std=c99: D_CXXONLY | D_OBJC
319 ObjC is like C except that D_OBJC and D_CXX_OBJC are not set
320 C++ --std=c++98: D_CONLY | D_CXX11 | D_OBJC
321 C++ --std=c++11: D_CONLY | D_OBJC
322 ObjC++ is like C++ except that D_OBJC is not set
324 If -fno-asm is used, D_ASM is added to the mask. If
325 -fno-gnu-keywords is used, D_EXT is added. If -fno-asm and C in
326 C89 mode, D_EXT89 is added for both -fno-asm and -fno-gnu-keywords.
327 In C with -Wc++-compat, we warn if D_CXXWARN is set.
329 Note the complication of the D_CXX_OBJC keywords. These are
330 reserved words such as 'class'. In C++, 'class' is a reserved
331 word. In Objective-C++ it is too. In Objective-C, it is a
332 reserved word too, but only if it follows an '@' sign.
334 const struct c_common_resword c_common_reswords[] =
336 { "_Alignas", RID_ALIGNAS, D_CONLY },
337 { "_Alignof", RID_ALIGNOF, D_CONLY },
338 { "_Atomic", RID_ATOMIC, D_CONLY },
339 { "_Bool", RID_BOOL, D_CONLY },
340 { "_Complex", RID_COMPLEX, 0 },
341 { "_Imaginary", RID_IMAGINARY, D_CONLY },
342 { "_Float16", RID_FLOAT16, D_CONLY },
343 { "_Float32", RID_FLOAT32, D_CONLY },
344 { "_Float64", RID_FLOAT64, D_CONLY },
345 { "_Float128", RID_FLOAT128, D_CONLY },
346 { "_Float32x", RID_FLOAT32X, D_CONLY },
347 { "_Float64x", RID_FLOAT64X, D_CONLY },
348 { "_Float128x", RID_FLOAT128X, D_CONLY },
349 { "_Decimal32", RID_DFLOAT32, D_CONLY | D_EXT },
350 { "_Decimal64", RID_DFLOAT64, D_CONLY | D_EXT },
351 { "_Decimal128", RID_DFLOAT128, D_CONLY | D_EXT },
352 { "_Fract", RID_FRACT, D_CONLY | D_EXT },
353 { "_Accum", RID_ACCUM, D_CONLY | D_EXT },
354 { "_Sat", RID_SAT, D_CONLY | D_EXT },
355 { "_Static_assert", RID_STATIC_ASSERT, D_CONLY },
356 { "_Noreturn", RID_NORETURN, D_CONLY },
357 { "_Generic", RID_GENERIC, D_CONLY },
358 { "_Thread_local", RID_THREAD, D_CONLY },
359 { "__FUNCTION__", RID_FUNCTION_NAME, 0 },
360 { "__PRETTY_FUNCTION__", RID_PRETTY_FUNCTION_NAME, 0 },
361 { "__alignof", RID_ALIGNOF, 0 },
362 { "__alignof__", RID_ALIGNOF, 0 },
363 { "__asm", RID_ASM, 0 },
364 { "__asm__", RID_ASM, 0 },
365 { "__attribute", RID_ATTRIBUTE, 0 },
366 { "__attribute__", RID_ATTRIBUTE, 0 },
367 { "__auto_type", RID_AUTO_TYPE, D_CONLY },
368 { "__bases", RID_BASES, D_CXXONLY },
369 { "__builtin_addressof", RID_ADDRESSOF, D_CXXONLY },
370 { "__builtin_call_with_static_chain",
371 RID_BUILTIN_CALL_WITH_STATIC_CHAIN, D_CONLY },
372 { "__builtin_choose_expr", RID_CHOOSE_EXPR, D_CONLY },
373 { "__builtin_complex", RID_BUILTIN_COMPLEX, D_CONLY },
374 { "__builtin_launder", RID_BUILTIN_LAUNDER, D_CXXONLY },
375 { "__builtin_shuffle", RID_BUILTIN_SHUFFLE, 0 },
376 { "__builtin_tgmath", RID_BUILTIN_TGMATH, D_CONLY },
377 { "__builtin_offsetof", RID_OFFSETOF, 0 },
378 { "__builtin_types_compatible_p", RID_TYPES_COMPATIBLE_P, D_CONLY },
379 { "__builtin_va_arg", RID_VA_ARG, 0 },
380 { "__complex", RID_COMPLEX, 0 },
381 { "__complex__", RID_COMPLEX, 0 },
382 { "__const", RID_CONST, 0 },
383 { "__const__", RID_CONST, 0 },
384 { "__decltype", RID_DECLTYPE, D_CXXONLY },
385 { "__direct_bases", RID_DIRECT_BASES, D_CXXONLY },
386 { "__extension__", RID_EXTENSION, 0 },
387 { "__func__", RID_C99_FUNCTION_NAME, 0 },
388 { "__has_nothrow_assign", RID_HAS_NOTHROW_ASSIGN, D_CXXONLY },
389 { "__has_nothrow_constructor", RID_HAS_NOTHROW_CONSTRUCTOR, D_CXXONLY },
390 { "__has_nothrow_copy", RID_HAS_NOTHROW_COPY, D_CXXONLY },
391 { "__has_trivial_assign", RID_HAS_TRIVIAL_ASSIGN, D_CXXONLY },
392 { "__has_trivial_constructor", RID_HAS_TRIVIAL_CONSTRUCTOR, D_CXXONLY },
393 { "__has_trivial_copy", RID_HAS_TRIVIAL_COPY, D_CXXONLY },
394 { "__has_trivial_destructor", RID_HAS_TRIVIAL_DESTRUCTOR, D_CXXONLY },
395 { "__has_unique_object_representations", RID_HAS_UNIQUE_OBJ_REPRESENTATIONS,
396 D_CXXONLY },
397 { "__has_virtual_destructor", RID_HAS_VIRTUAL_DESTRUCTOR, D_CXXONLY },
398 { "__imag", RID_IMAGPART, 0 },
399 { "__imag__", RID_IMAGPART, 0 },
400 { "__inline", RID_INLINE, 0 },
401 { "__inline__", RID_INLINE, 0 },
402 { "__is_abstract", RID_IS_ABSTRACT, D_CXXONLY },
403 { "__is_aggregate", RID_IS_AGGREGATE, D_CXXONLY },
404 { "__is_base_of", RID_IS_BASE_OF, D_CXXONLY },
405 { "__is_class", RID_IS_CLASS, D_CXXONLY },
406 { "__is_empty", RID_IS_EMPTY, D_CXXONLY },
407 { "__is_enum", RID_IS_ENUM, D_CXXONLY },
408 { "__is_final", RID_IS_FINAL, D_CXXONLY },
409 { "__is_literal_type", RID_IS_LITERAL_TYPE, D_CXXONLY },
410 { "__is_pod", RID_IS_POD, D_CXXONLY },
411 { "__is_polymorphic", RID_IS_POLYMORPHIC, D_CXXONLY },
412 { "__is_same_as", RID_IS_SAME_AS, D_CXXONLY },
413 { "__is_standard_layout", RID_IS_STD_LAYOUT, D_CXXONLY },
414 { "__is_trivial", RID_IS_TRIVIAL, D_CXXONLY },
415 { "__is_trivially_assignable", RID_IS_TRIVIALLY_ASSIGNABLE, D_CXXONLY },
416 { "__is_trivially_constructible", RID_IS_TRIVIALLY_CONSTRUCTIBLE, D_CXXONLY },
417 { "__is_trivially_copyable", RID_IS_TRIVIALLY_COPYABLE, D_CXXONLY },
418 { "__is_union", RID_IS_UNION, D_CXXONLY },
419 { "__label__", RID_LABEL, 0 },
420 { "__null", RID_NULL, 0 },
421 { "__real", RID_REALPART, 0 },
422 { "__real__", RID_REALPART, 0 },
423 { "__restrict", RID_RESTRICT, 0 },
424 { "__restrict__", RID_RESTRICT, 0 },
425 { "__signed", RID_SIGNED, 0 },
426 { "__signed__", RID_SIGNED, 0 },
427 { "__thread", RID_THREAD, 0 },
428 { "__transaction_atomic", RID_TRANSACTION_ATOMIC, 0 },
429 { "__transaction_relaxed", RID_TRANSACTION_RELAXED, 0 },
430 { "__transaction_cancel", RID_TRANSACTION_CANCEL, 0 },
431 { "__typeof", RID_TYPEOF, 0 },
432 { "__typeof__", RID_TYPEOF, 0 },
433 { "__underlying_type", RID_UNDERLYING_TYPE, D_CXXONLY },
434 { "__volatile", RID_VOLATILE, 0 },
435 { "__volatile__", RID_VOLATILE, 0 },
436 { "__GIMPLE", RID_GIMPLE, D_CONLY },
437 { "__PHI", RID_PHI, D_CONLY },
438 { "__RTL", RID_RTL, D_CONLY },
439 { "alignas", RID_ALIGNAS, D_CXXONLY | D_CXX11 | D_CXXWARN },
440 { "alignof", RID_ALIGNOF, D_CXXONLY | D_CXX11 | D_CXXWARN },
441 { "asm", RID_ASM, D_ASM },
442 { "auto", RID_AUTO, 0 },
443 { "bool", RID_BOOL, D_CXXONLY | D_CXXWARN },
444 { "break", RID_BREAK, 0 },
445 { "case", RID_CASE, 0 },
446 { "catch", RID_CATCH, D_CXX_OBJC | D_CXXWARN },
447 { "char", RID_CHAR, 0 },
448 { "char16_t", RID_CHAR16, D_CXXONLY | D_CXX11 | D_CXXWARN },
449 { "char32_t", RID_CHAR32, D_CXXONLY | D_CXX11 | D_CXXWARN },
450 { "class", RID_CLASS, D_CXX_OBJC | D_CXXWARN },
451 { "const", RID_CONST, 0 },
452 { "constexpr", RID_CONSTEXPR, D_CXXONLY | D_CXX11 | D_CXXWARN },
453 { "const_cast", RID_CONSTCAST, D_CXXONLY | D_CXXWARN },
454 { "continue", RID_CONTINUE, 0 },
455 { "decltype", RID_DECLTYPE, D_CXXONLY | D_CXX11 | D_CXXWARN },
456 { "default", RID_DEFAULT, 0 },
457 { "delete", RID_DELETE, D_CXXONLY | D_CXXWARN },
458 { "do", RID_DO, 0 },
459 { "double", RID_DOUBLE, 0 },
460 { "dynamic_cast", RID_DYNCAST, D_CXXONLY | D_CXXWARN },
461 { "else", RID_ELSE, 0 },
462 { "enum", RID_ENUM, 0 },
463 { "explicit", RID_EXPLICIT, D_CXXONLY | D_CXXWARN },
464 { "export", RID_EXPORT, D_CXXONLY | D_CXXWARN },
465 { "extern", RID_EXTERN, 0 },
466 { "false", RID_FALSE, D_CXXONLY | D_CXXWARN },
467 { "float", RID_FLOAT, 0 },
468 { "for", RID_FOR, 0 },
469 { "friend", RID_FRIEND, D_CXXONLY | D_CXXWARN },
470 { "goto", RID_GOTO, 0 },
471 { "if", RID_IF, 0 },
472 { "inline", RID_INLINE, D_EXT89 },
473 { "int", RID_INT, 0 },
474 { "long", RID_LONG, 0 },
475 { "mutable", RID_MUTABLE, D_CXXONLY | D_CXXWARN },
476 { "namespace", RID_NAMESPACE, D_CXXONLY | D_CXXWARN },
477 { "new", RID_NEW, D_CXXONLY | D_CXXWARN },
478 { "noexcept", RID_NOEXCEPT, D_CXXONLY | D_CXX11 | D_CXXWARN },
479 { "nullptr", RID_NULLPTR, D_CXXONLY | D_CXX11 | D_CXXWARN },
480 { "operator", RID_OPERATOR, D_CXXONLY | D_CXXWARN },
481 { "private", RID_PRIVATE, D_CXX_OBJC | D_CXXWARN },
482 { "protected", RID_PROTECTED, D_CXX_OBJC | D_CXXWARN },
483 { "public", RID_PUBLIC, D_CXX_OBJC | D_CXXWARN },
484 { "register", RID_REGISTER, 0 },
485 { "reinterpret_cast", RID_REINTCAST, D_CXXONLY | D_CXXWARN },
486 { "restrict", RID_RESTRICT, D_CONLY | D_C99 },
487 { "return", RID_RETURN, 0 },
488 { "short", RID_SHORT, 0 },
489 { "signed", RID_SIGNED, 0 },
490 { "sizeof", RID_SIZEOF, 0 },
491 { "static", RID_STATIC, 0 },
492 { "static_assert", RID_STATIC_ASSERT, D_CXXONLY | D_CXX11 | D_CXXWARN },
493 { "static_cast", RID_STATCAST, D_CXXONLY | D_CXXWARN },
494 { "struct", RID_STRUCT, 0 },
495 { "switch", RID_SWITCH, 0 },
496 { "template", RID_TEMPLATE, D_CXXONLY | D_CXXWARN },
497 { "this", RID_THIS, D_CXXONLY | D_CXXWARN },
498 { "thread_local", RID_THREAD, D_CXXONLY | D_CXX11 | D_CXXWARN },
499 { "throw", RID_THROW, D_CXX_OBJC | D_CXXWARN },
500 { "true", RID_TRUE, D_CXXONLY | D_CXXWARN },
501 { "try", RID_TRY, D_CXX_OBJC | D_CXXWARN },
502 { "typedef", RID_TYPEDEF, 0 },
503 { "typename", RID_TYPENAME, D_CXXONLY | D_CXXWARN },
504 { "typeid", RID_TYPEID, D_CXXONLY | D_CXXWARN },
505 { "typeof", RID_TYPEOF, D_ASM | D_EXT },
506 { "union", RID_UNION, 0 },
507 { "unsigned", RID_UNSIGNED, 0 },
508 { "using", RID_USING, D_CXXONLY | D_CXXWARN },
509 { "virtual", RID_VIRTUAL, D_CXXONLY | D_CXXWARN },
510 { "void", RID_VOID, 0 },
511 { "volatile", RID_VOLATILE, 0 },
512 { "wchar_t", RID_WCHAR, D_CXXONLY },
513 { "while", RID_WHILE, 0 },
514 { "__is_assignable", RID_IS_ASSIGNABLE, D_CXXONLY },
515 { "__is_constructible", RID_IS_CONSTRUCTIBLE, D_CXXONLY },
517 /* C++ transactional memory. */
518 { "synchronized", RID_SYNCHRONIZED, D_CXX_OBJC | D_TRANSMEM },
519 { "atomic_noexcept", RID_ATOMIC_NOEXCEPT, D_CXXONLY | D_TRANSMEM },
520 { "atomic_cancel", RID_ATOMIC_CANCEL, D_CXXONLY | D_TRANSMEM },
521 { "atomic_commit", RID_TRANSACTION_ATOMIC, D_CXXONLY | D_TRANSMEM },
523 /* Concepts-related keywords */
524 { "concept", RID_CONCEPT, D_CXX_CONCEPTS_FLAGS | D_CXXWARN },
525 { "requires", RID_REQUIRES, D_CXX_CONCEPTS_FLAGS | D_CXXWARN },
527 /* These Objective-C keywords are recognized only immediately after
528 an '@'. */
529 { "compatibility_alias", RID_AT_ALIAS, D_OBJC },
530 { "defs", RID_AT_DEFS, D_OBJC },
531 { "encode", RID_AT_ENCODE, D_OBJC },
532 { "end", RID_AT_END, D_OBJC },
533 { "implementation", RID_AT_IMPLEMENTATION, D_OBJC },
534 { "interface", RID_AT_INTERFACE, D_OBJC },
535 { "protocol", RID_AT_PROTOCOL, D_OBJC },
536 { "selector", RID_AT_SELECTOR, D_OBJC },
537 { "finally", RID_AT_FINALLY, D_OBJC },
538 { "optional", RID_AT_OPTIONAL, D_OBJC },
539 { "required", RID_AT_REQUIRED, D_OBJC },
540 { "property", RID_AT_PROPERTY, D_OBJC },
541 { "package", RID_AT_PACKAGE, D_OBJC },
542 { "synthesize", RID_AT_SYNTHESIZE, D_OBJC },
543 { "dynamic", RID_AT_DYNAMIC, D_OBJC },
544 /* These are recognized only in protocol-qualifier context
545 (see above) */
546 { "bycopy", RID_BYCOPY, D_OBJC },
547 { "byref", RID_BYREF, D_OBJC },
548 { "in", RID_IN, D_OBJC },
549 { "inout", RID_INOUT, D_OBJC },
550 { "oneway", RID_ONEWAY, D_OBJC },
551 { "out", RID_OUT, D_OBJC },
552 /* These are recognized inside a property attribute list */
553 { "assign", RID_ASSIGN, D_OBJC },
554 { "copy", RID_COPY, D_OBJC },
555 { "getter", RID_GETTER, D_OBJC },
556 { "nonatomic", RID_NONATOMIC, D_OBJC },
557 { "readonly", RID_READONLY, D_OBJC },
558 { "readwrite", RID_READWRITE, D_OBJC },
559 { "retain", RID_RETAIN, D_OBJC },
560 { "setter", RID_SETTER, D_OBJC },
563 const unsigned int num_c_common_reswords =
564 sizeof c_common_reswords / sizeof (struct c_common_resword);
566 /* Return identifier for address space AS. */
568 const char *
569 c_addr_space_name (addr_space_t as)
571 int rid = RID_FIRST_ADDR_SPACE + as;
572 gcc_assert (ridpointers [rid]);
573 return IDENTIFIER_POINTER (ridpointers [rid]);
576 /* Push current bindings for the function name VAR_DECLS. */
578 void
579 start_fname_decls (void)
581 unsigned ix;
582 tree saved = NULL_TREE;
584 for (ix = 0; fname_vars[ix].decl; ix++)
586 tree decl = *fname_vars[ix].decl;
588 if (decl)
590 saved = tree_cons (decl, build_int_cst (integer_type_node, ix),
591 saved);
592 *fname_vars[ix].decl = NULL_TREE;
595 if (saved || saved_function_name_decls)
596 /* Normally they'll have been NULL, so only push if we've got a
597 stack, or they are non-NULL. */
598 saved_function_name_decls = tree_cons (saved, NULL_TREE,
599 saved_function_name_decls);
602 /* Finish up the current bindings, adding them into the current function's
603 statement tree. This must be done _before_ finish_stmt_tree is called.
604 If there is no current function, we must be at file scope and no statements
605 are involved. Pop the previous bindings. */
607 void
608 finish_fname_decls (void)
610 unsigned ix;
611 tree stmts = NULL_TREE;
612 tree stack = saved_function_name_decls;
614 for (; stack && TREE_VALUE (stack); stack = TREE_CHAIN (stack))
615 append_to_statement_list (TREE_VALUE (stack), &stmts);
617 if (stmts)
619 tree *bodyp = &DECL_SAVED_TREE (current_function_decl);
621 if (TREE_CODE (*bodyp) == BIND_EXPR)
622 bodyp = &BIND_EXPR_BODY (*bodyp);
624 append_to_statement_list_force (*bodyp, &stmts);
625 *bodyp = stmts;
628 for (ix = 0; fname_vars[ix].decl; ix++)
629 *fname_vars[ix].decl = NULL_TREE;
631 if (stack)
633 /* We had saved values, restore them. */
634 tree saved;
636 for (saved = TREE_PURPOSE (stack); saved; saved = TREE_CHAIN (saved))
638 tree decl = TREE_PURPOSE (saved);
639 unsigned ix = TREE_INT_CST_LOW (TREE_VALUE (saved));
641 *fname_vars[ix].decl = decl;
643 stack = TREE_CHAIN (stack);
645 saved_function_name_decls = stack;
648 /* Return the text name of the current function, suitably prettified
649 by PRETTY_P. Return string must be freed by caller. */
651 const char *
652 fname_as_string (int pretty_p)
654 const char *name = "top level";
655 char *namep;
656 int vrb = 2, len;
657 cpp_string cstr = { 0, 0 }, strname;
659 if (!pretty_p)
661 name = "";
662 vrb = 0;
665 if (current_function_decl)
666 name = lang_hooks.decl_printable_name (current_function_decl, vrb);
668 len = strlen (name) + 3; /* Two for '"'s. One for NULL. */
670 namep = XNEWVEC (char, len);
671 snprintf (namep, len, "\"%s\"", name);
672 strname.text = (unsigned char *) namep;
673 strname.len = len - 1;
675 if (cpp_interpret_string (parse_in, &strname, 1, &cstr, CPP_STRING))
677 XDELETEVEC (namep);
678 return (const char *) cstr.text;
681 return namep;
684 /* Return the VAR_DECL for a const char array naming the current
685 function. If the VAR_DECL has not yet been created, create it
686 now. RID indicates how it should be formatted and IDENTIFIER_NODE
687 ID is its name (unfortunately C and C++ hold the RID values of
688 keywords in different places, so we can't derive RID from ID in
689 this language independent code. LOC is the location of the
690 function. */
692 tree
693 fname_decl (location_t loc, unsigned int rid, tree id)
695 unsigned ix;
696 tree decl = NULL_TREE;
698 for (ix = 0; fname_vars[ix].decl; ix++)
699 if (fname_vars[ix].rid == rid)
700 break;
702 decl = *fname_vars[ix].decl;
703 if (!decl)
705 /* If a tree is built here, it would normally have the lineno of
706 the current statement. Later this tree will be moved to the
707 beginning of the function and this line number will be wrong.
708 To avoid this problem set the lineno to 0 here; that prevents
709 it from appearing in the RTL. */
710 tree stmts;
711 location_t saved_location = input_location;
712 input_location = UNKNOWN_LOCATION;
714 stmts = push_stmt_list ();
715 decl = (*make_fname_decl) (loc, id, fname_vars[ix].pretty);
716 stmts = pop_stmt_list (stmts);
717 if (!IS_EMPTY_STMT (stmts))
718 saved_function_name_decls
719 = tree_cons (decl, stmts, saved_function_name_decls);
720 *fname_vars[ix].decl = decl;
721 input_location = saved_location;
723 if (!ix && !current_function_decl)
724 pedwarn (loc, 0, "%qD is not defined outside of function scope", decl);
726 return decl;
729 /* Given a STRING_CST, give it a suitable array-of-chars data type. */
731 tree
732 fix_string_type (tree value)
734 int length = TREE_STRING_LENGTH (value);
735 int nchars;
736 tree e_type, i_type, a_type;
738 /* Compute the number of elements, for the array type. */
739 if (TREE_TYPE (value) == char_array_type_node || !TREE_TYPE (value))
741 nchars = length;
742 e_type = char_type_node;
744 else if (TREE_TYPE (value) == char16_array_type_node)
746 nchars = length / (TYPE_PRECISION (char16_type_node) / BITS_PER_UNIT);
747 e_type = char16_type_node;
749 else if (TREE_TYPE (value) == char32_array_type_node)
751 nchars = length / (TYPE_PRECISION (char32_type_node) / BITS_PER_UNIT);
752 e_type = char32_type_node;
754 else
756 nchars = length / (TYPE_PRECISION (wchar_type_node) / BITS_PER_UNIT);
757 e_type = wchar_type_node;
760 /* C89 2.2.4.1, C99 5.2.4.1 (Translation limits). The analogous
761 limit in C++98 Annex B is very large (65536) and is not normative,
762 so we do not diagnose it (warn_overlength_strings is forced off
763 in c_common_post_options). */
764 if (warn_overlength_strings)
766 const int nchars_max = flag_isoc99 ? 4095 : 509;
767 const int relevant_std = flag_isoc99 ? 99 : 90;
768 if (nchars - 1 > nchars_max)
769 /* Translators: The %d after 'ISO C' will be 90 or 99. Do not
770 separate the %d from the 'C'. 'ISO' should not be
771 translated, but it may be moved after 'C%d' in languages
772 where modifiers follow nouns. */
773 pedwarn (input_location, OPT_Woverlength_strings,
774 "string length %qd is greater than the length %qd "
775 "ISO C%d compilers are required to support",
776 nchars - 1, nchars_max, relevant_std);
779 /* Create the array type for the string constant. The ISO C++
780 standard says that a string literal has type `const char[N]' or
781 `const wchar_t[N]'. We use the same logic when invoked as a C
782 front-end with -Wwrite-strings.
783 ??? We should change the type of an expression depending on the
784 state of a warning flag. We should just be warning -- see how
785 this is handled in the C++ front-end for the deprecated implicit
786 conversion from string literals to `char*' or `wchar_t*'.
788 The C++ front end relies on TYPE_MAIN_VARIANT of a cv-qualified
789 array type being the unqualified version of that type.
790 Therefore, if we are constructing an array of const char, we must
791 construct the matching unqualified array type first. The C front
792 end does not require this, but it does no harm, so we do it
793 unconditionally. */
794 i_type = build_index_type (size_int (nchars - 1));
795 a_type = build_array_type (e_type, i_type);
796 if (c_dialect_cxx() || warn_write_strings)
797 a_type = c_build_qualified_type (a_type, TYPE_QUAL_CONST);
799 TREE_TYPE (value) = a_type;
800 TREE_CONSTANT (value) = 1;
801 TREE_READONLY (value) = 1;
802 TREE_STATIC (value) = 1;
803 return value;
806 /* Given a string of type STRING_TYPE, determine what kind of string
807 token would give an equivalent execution encoding: CPP_STRING,
808 CPP_STRING16, or CPP_STRING32. Return CPP_OTHER in case of error.
809 This may not be exactly the string token type that initially created
810 the string, since CPP_WSTRING is indistinguishable from the 16/32 bit
811 string type at this point.
813 This effectively reverses part of the logic in lex_string and
814 fix_string_type. */
816 static enum cpp_ttype
817 get_cpp_ttype_from_string_type (tree string_type)
819 gcc_assert (string_type);
820 if (TREE_CODE (string_type) == POINTER_TYPE)
821 string_type = TREE_TYPE (string_type);
823 if (TREE_CODE (string_type) != ARRAY_TYPE)
824 return CPP_OTHER;
826 tree element_type = TREE_TYPE (string_type);
827 if (TREE_CODE (element_type) != INTEGER_TYPE)
828 return CPP_OTHER;
830 int bits_per_character = TYPE_PRECISION (element_type);
831 switch (bits_per_character)
833 case 8:
834 return CPP_STRING; /* It could have also been CPP_UTF8STRING. */
835 case 16:
836 return CPP_STRING16;
837 case 32:
838 return CPP_STRING32;
841 return CPP_OTHER;
844 /* The global record of string concatentations, for use in
845 extracting locations within string literals. */
847 GTY(()) string_concat_db *g_string_concat_db;
849 /* Implementation of LANG_HOOKS_GET_SUBSTRING_LOCATION. */
851 const char *
852 c_get_substring_location (const substring_loc &substr_loc,
853 location_t *out_loc)
855 enum cpp_ttype tok_type
856 = get_cpp_ttype_from_string_type (substr_loc.get_string_type ());
857 if (tok_type == CPP_OTHER)
858 return "unrecognized string type";
860 return get_source_location_for_substring (parse_in, g_string_concat_db,
861 substr_loc.get_fmt_string_loc (),
862 tok_type,
863 substr_loc.get_caret_idx (),
864 substr_loc.get_start_idx (),
865 substr_loc.get_end_idx (),
866 out_loc);
870 /* Fold X for consideration by one of the warning functions when checking
871 whether an expression has a constant value. */
873 tree
874 fold_for_warn (tree x)
876 if (c_dialect_cxx ())
877 return c_fully_fold (x, /*for_init*/false, /*maybe_constp*/NULL);
878 else
879 /* The C front-end has already folded X appropriately. */
880 return x;
883 /* Return true iff T is a boolean promoted to int. */
885 bool
886 bool_promoted_to_int_p (tree t)
888 return (CONVERT_EXPR_P (t)
889 && TREE_TYPE (t) == integer_type_node
890 && TREE_CODE (TREE_TYPE (TREE_OPERAND (t, 0))) == BOOLEAN_TYPE);
893 /* vector_targets_convertible_p is used for vector pointer types. The
894 callers perform various checks that the qualifiers are satisfactory,
895 while OTOH vector_targets_convertible_p ignores the number of elements
896 in the vectors. That's fine with vector pointers as we can consider,
897 say, a vector of 8 elements as two consecutive vectors of 4 elements,
898 and that does not require and conversion of the pointer values.
899 In contrast, vector_types_convertible_p and
900 vector_types_compatible_elements_p are used for vector value types. */
901 /* True if pointers to distinct types T1 and T2 can be converted to
902 each other without an explicit cast. Only returns true for opaque
903 vector types. */
904 bool
905 vector_targets_convertible_p (const_tree t1, const_tree t2)
907 if (VECTOR_TYPE_P (t1) && VECTOR_TYPE_P (t2)
908 && (TYPE_VECTOR_OPAQUE (t1) || TYPE_VECTOR_OPAQUE (t2))
909 && tree_int_cst_equal (TYPE_SIZE (t1), TYPE_SIZE (t2)))
910 return true;
912 return false;
915 /* vector_types_convertible_p is used for vector value types.
916 It could in principle call vector_targets_convertible_p as a subroutine,
917 but then the check for vector type would be duplicated with its callers,
918 and also the purpose of vector_targets_convertible_p would become
919 muddled.
920 Where vector_types_convertible_p returns true, a conversion might still be
921 needed to make the types match.
922 In contrast, vector_targets_convertible_p is used for vector pointer
923 values, and vector_types_compatible_elements_p is used specifically
924 in the context for binary operators, as a check if use is possible without
925 conversion. */
926 /* True if vector types T1 and T2 can be converted to each other
927 without an explicit cast. If EMIT_LAX_NOTE is true, and T1 and T2
928 can only be converted with -flax-vector-conversions yet that is not
929 in effect, emit a note telling the user about that option if such
930 a note has not previously been emitted. */
931 bool
932 vector_types_convertible_p (const_tree t1, const_tree t2, bool emit_lax_note)
934 static bool emitted_lax_note = false;
935 bool convertible_lax;
937 if ((TYPE_VECTOR_OPAQUE (t1) || TYPE_VECTOR_OPAQUE (t2))
938 && tree_int_cst_equal (TYPE_SIZE (t1), TYPE_SIZE (t2)))
939 return true;
941 convertible_lax =
942 (tree_int_cst_equal (TYPE_SIZE (t1), TYPE_SIZE (t2))
943 && (TREE_CODE (TREE_TYPE (t1)) != REAL_TYPE
944 || known_eq (TYPE_VECTOR_SUBPARTS (t1),
945 TYPE_VECTOR_SUBPARTS (t2)))
946 && (INTEGRAL_TYPE_P (TREE_TYPE (t1))
947 == INTEGRAL_TYPE_P (TREE_TYPE (t2))));
949 if (!convertible_lax || flag_lax_vector_conversions)
950 return convertible_lax;
952 if (known_eq (TYPE_VECTOR_SUBPARTS (t1), TYPE_VECTOR_SUBPARTS (t2))
953 && lang_hooks.types_compatible_p (TREE_TYPE (t1), TREE_TYPE (t2)))
954 return true;
956 if (emit_lax_note && !emitted_lax_note)
958 emitted_lax_note = true;
959 inform (input_location, "use -flax-vector-conversions to permit "
960 "conversions between vectors with differing "
961 "element types or numbers of subparts");
964 return false;
967 /* Build a VEC_PERM_EXPR if V0, V1 and MASK are not error_mark_nodes
968 and have vector types, V0 has the same type as V1, and the number of
969 elements of V0, V1, MASK is the same.
971 In case V1 is a NULL_TREE it is assumed that __builtin_shuffle was
972 called with two arguments. In this case implementation passes the
973 first argument twice in order to share the same tree code. This fact
974 could enable the mask-values being twice the vector length. This is
975 an implementation accident and this semantics is not guaranteed to
976 the user. */
977 tree
978 c_build_vec_perm_expr (location_t loc, tree v0, tree v1, tree mask,
979 bool complain)
981 tree ret;
982 bool wrap = true;
983 bool maybe_const = false;
984 bool two_arguments = false;
986 if (v1 == NULL_TREE)
988 two_arguments = true;
989 v1 = v0;
992 if (v0 == error_mark_node || v1 == error_mark_node
993 || mask == error_mark_node)
994 return error_mark_node;
996 if (!VECTOR_INTEGER_TYPE_P (TREE_TYPE (mask)))
998 if (complain)
999 error_at (loc, "__builtin_shuffle last argument must "
1000 "be an integer vector");
1001 return error_mark_node;
1004 if (!VECTOR_TYPE_P (TREE_TYPE (v0))
1005 || !VECTOR_TYPE_P (TREE_TYPE (v1)))
1007 if (complain)
1008 error_at (loc, "__builtin_shuffle arguments must be vectors");
1009 return error_mark_node;
1012 if (TYPE_MAIN_VARIANT (TREE_TYPE (v0)) != TYPE_MAIN_VARIANT (TREE_TYPE (v1)))
1014 if (complain)
1015 error_at (loc, "__builtin_shuffle argument vectors must be of "
1016 "the same type");
1017 return error_mark_node;
1020 if (maybe_ne (TYPE_VECTOR_SUBPARTS (TREE_TYPE (v0)),
1021 TYPE_VECTOR_SUBPARTS (TREE_TYPE (mask)))
1022 && maybe_ne (TYPE_VECTOR_SUBPARTS (TREE_TYPE (v1)),
1023 TYPE_VECTOR_SUBPARTS (TREE_TYPE (mask))))
1025 if (complain)
1026 error_at (loc, "__builtin_shuffle number of elements of the "
1027 "argument vector(s) and the mask vector should "
1028 "be the same");
1029 return error_mark_node;
1032 if (GET_MODE_BITSIZE (SCALAR_TYPE_MODE (TREE_TYPE (TREE_TYPE (v0))))
1033 != GET_MODE_BITSIZE (SCALAR_TYPE_MODE (TREE_TYPE (TREE_TYPE (mask)))))
1035 if (complain)
1036 error_at (loc, "__builtin_shuffle argument vector(s) inner type "
1037 "must have the same size as inner type of the mask");
1038 return error_mark_node;
1041 if (!c_dialect_cxx ())
1043 /* Avoid C_MAYBE_CONST_EXPRs inside VEC_PERM_EXPR. */
1044 v0 = c_fully_fold (v0, false, &maybe_const);
1045 wrap &= maybe_const;
1047 if (two_arguments)
1048 v1 = v0 = save_expr (v0);
1049 else
1051 v1 = c_fully_fold (v1, false, &maybe_const);
1052 wrap &= maybe_const;
1055 mask = c_fully_fold (mask, false, &maybe_const);
1056 wrap &= maybe_const;
1058 else if (two_arguments)
1059 v1 = v0 = save_expr (v0);
1061 ret = build3_loc (loc, VEC_PERM_EXPR, TREE_TYPE (v0), v0, v1, mask);
1063 if (!c_dialect_cxx () && !wrap)
1064 ret = c_wrap_maybe_const (ret, true);
1066 return ret;
1069 /* Like tree.c:get_narrower, but retain conversion from C++0x scoped enum
1070 to integral type. */
1072 tree
1073 c_common_get_narrower (tree op, int *unsignedp_ptr)
1075 op = get_narrower (op, unsignedp_ptr);
1077 if (TREE_CODE (TREE_TYPE (op)) == ENUMERAL_TYPE
1078 && ENUM_IS_SCOPED (TREE_TYPE (op)))
1080 /* C++0x scoped enumerations don't implicitly convert to integral
1081 type; if we stripped an explicit conversion to a larger type we
1082 need to replace it so common_type will still work. */
1083 tree type = c_common_type_for_size (TYPE_PRECISION (TREE_TYPE (op)),
1084 TYPE_UNSIGNED (TREE_TYPE (op)));
1085 op = fold_convert (type, op);
1087 return op;
1090 /* This is a helper function of build_binary_op.
1092 For certain operations if both args were extended from the same
1093 smaller type, do the arithmetic in that type and then extend.
1095 BITWISE indicates a bitwise operation.
1096 For them, this optimization is safe only if
1097 both args are zero-extended or both are sign-extended.
1098 Otherwise, we might change the result.
1099 Eg, (short)-1 | (unsigned short)-1 is (int)-1
1100 but calculated in (unsigned short) it would be (unsigned short)-1.
1102 tree
1103 shorten_binary_op (tree result_type, tree op0, tree op1, bool bitwise)
1105 int unsigned0, unsigned1;
1106 tree arg0, arg1;
1107 int uns;
1108 tree type;
1110 /* Cast OP0 and OP1 to RESULT_TYPE. Doing so prevents
1111 excessive narrowing when we call get_narrower below. For
1112 example, suppose that OP0 is of unsigned int extended
1113 from signed char and that RESULT_TYPE is long long int.
1114 If we explicitly cast OP0 to RESULT_TYPE, OP0 would look
1115 like
1117 (long long int) (unsigned int) signed_char
1119 which get_narrower would narrow down to
1121 (unsigned int) signed char
1123 If we do not cast OP0 first, get_narrower would return
1124 signed_char, which is inconsistent with the case of the
1125 explicit cast. */
1126 op0 = convert (result_type, op0);
1127 op1 = convert (result_type, op1);
1129 arg0 = c_common_get_narrower (op0, &unsigned0);
1130 arg1 = c_common_get_narrower (op1, &unsigned1);
1132 /* UNS is 1 if the operation to be done is an unsigned one. */
1133 uns = TYPE_UNSIGNED (result_type);
1135 /* Handle the case that OP0 (or OP1) does not *contain* a conversion
1136 but it *requires* conversion to FINAL_TYPE. */
1138 if ((TYPE_PRECISION (TREE_TYPE (op0))
1139 == TYPE_PRECISION (TREE_TYPE (arg0)))
1140 && TREE_TYPE (op0) != result_type)
1141 unsigned0 = TYPE_UNSIGNED (TREE_TYPE (op0));
1142 if ((TYPE_PRECISION (TREE_TYPE (op1))
1143 == TYPE_PRECISION (TREE_TYPE (arg1)))
1144 && TREE_TYPE (op1) != result_type)
1145 unsigned1 = TYPE_UNSIGNED (TREE_TYPE (op1));
1147 /* Now UNSIGNED0 is 1 if ARG0 zero-extends to FINAL_TYPE. */
1149 /* For bitwise operations, signedness of nominal type
1150 does not matter. Consider only how operands were extended. */
1151 if (bitwise)
1152 uns = unsigned0;
1154 /* Note that in all three cases below we refrain from optimizing
1155 an unsigned operation on sign-extended args.
1156 That would not be valid. */
1158 /* Both args variable: if both extended in same way
1159 from same width, do it in that width.
1160 Do it unsigned if args were zero-extended. */
1161 if ((TYPE_PRECISION (TREE_TYPE (arg0))
1162 < TYPE_PRECISION (result_type))
1163 && (TYPE_PRECISION (TREE_TYPE (arg1))
1164 == TYPE_PRECISION (TREE_TYPE (arg0)))
1165 && unsigned0 == unsigned1
1166 && (unsigned0 || !uns))
1167 return c_common_signed_or_unsigned_type
1168 (unsigned0, common_type (TREE_TYPE (arg0), TREE_TYPE (arg1)));
1170 else if (TREE_CODE (arg0) == INTEGER_CST
1171 && (unsigned1 || !uns)
1172 && (TYPE_PRECISION (TREE_TYPE (arg1))
1173 < TYPE_PRECISION (result_type))
1174 && (type
1175 = c_common_signed_or_unsigned_type (unsigned1,
1176 TREE_TYPE (arg1)))
1177 && !POINTER_TYPE_P (type)
1178 && int_fits_type_p (arg0, type))
1179 return type;
1181 else if (TREE_CODE (arg1) == INTEGER_CST
1182 && (unsigned0 || !uns)
1183 && (TYPE_PRECISION (TREE_TYPE (arg0))
1184 < TYPE_PRECISION (result_type))
1185 && (type
1186 = c_common_signed_or_unsigned_type (unsigned0,
1187 TREE_TYPE (arg0)))
1188 && !POINTER_TYPE_P (type)
1189 && int_fits_type_p (arg1, type))
1190 return type;
1192 return result_type;
1195 /* Returns true iff any integer value of type FROM_TYPE can be represented as
1196 real of type TO_TYPE. This is a helper function for unsafe_conversion_p. */
1198 static bool
1199 int_safely_convertible_to_real_p (const_tree from_type, const_tree to_type)
1201 tree type_low_bound = TYPE_MIN_VALUE (from_type);
1202 tree type_high_bound = TYPE_MAX_VALUE (from_type);
1203 REAL_VALUE_TYPE real_low_bound =
1204 real_value_from_int_cst (0, type_low_bound);
1205 REAL_VALUE_TYPE real_high_bound =
1206 real_value_from_int_cst (0, type_high_bound);
1208 return exact_real_truncate (TYPE_MODE (to_type), &real_low_bound)
1209 && exact_real_truncate (TYPE_MODE (to_type), &real_high_bound);
1212 /* Checks if expression EXPR of complex/real/integer type cannot be converted
1213 to the complex/real/integer type TYPE. Function returns non-zero when:
1214 * EXPR is a constant which cannot be exactly converted to TYPE.
1215 * EXPR is not a constant and size of EXPR's type > than size of TYPE,
1216 for EXPR type and TYPE being both integers or both real, or both
1217 complex.
1218 * EXPR is not a constant of complex type and TYPE is a real or
1219 an integer.
1220 * EXPR is not a constant of real type and TYPE is an integer.
1221 * EXPR is not a constant of integer type which cannot be
1222 exactly converted to real type.
1224 Function allows conversions between types of different signedness and
1225 can return SAFE_CONVERSION (zero) in that case. Function can produce
1226 signedness warnings if PRODUCE_WARNS is true.
1228 RESULT, when non-null is the result of the conversion. When constant
1229 it is included in the text of diagnostics.
1231 Function allows conversions from complex constants to non-complex types,
1232 provided that imaginary part is zero and real part can be safely converted
1233 to TYPE. */
1235 enum conversion_safety
1236 unsafe_conversion_p (location_t loc, tree type, tree expr, tree result,
1237 bool produce_warns)
1239 enum conversion_safety give_warning = SAFE_CONVERSION; /* is 0 or false */
1240 tree expr_type = TREE_TYPE (expr);
1242 bool cstresult = (result
1243 && TREE_CODE_CLASS (TREE_CODE (result)) == tcc_constant);
1245 loc = expansion_point_location_if_in_system_header (loc);
1247 if (TREE_CODE (expr) == REAL_CST || TREE_CODE (expr) == INTEGER_CST)
1249 /* If type is complex, we are interested in compatibility with
1250 underlying type. */
1251 if (TREE_CODE (type) == COMPLEX_TYPE)
1252 type = TREE_TYPE (type);
1254 /* Warn for real constant that is not an exact integer converted
1255 to integer type. */
1256 if (TREE_CODE (expr_type) == REAL_TYPE
1257 && TREE_CODE (type) == INTEGER_TYPE)
1259 if (!real_isinteger (TREE_REAL_CST_PTR (expr), TYPE_MODE (expr_type)))
1260 give_warning = UNSAFE_REAL;
1262 /* Warn for an integer constant that does not fit into integer type. */
1263 else if (TREE_CODE (expr_type) == INTEGER_TYPE
1264 && TREE_CODE (type) == INTEGER_TYPE
1265 && !int_fits_type_p (expr, type))
1267 if (TYPE_UNSIGNED (type) && !TYPE_UNSIGNED (expr_type)
1268 && tree_int_cst_sgn (expr) < 0)
1270 if (produce_warns)
1272 if (cstresult)
1273 warning_at (loc, OPT_Wsign_conversion,
1274 "unsigned conversion from %qT to %qT "
1275 "changes value from %qE to %qE",
1276 expr_type, type, expr, result);
1277 else
1278 warning_at (loc, OPT_Wsign_conversion,
1279 "unsigned conversion from %qT to %qT "
1280 "changes the value of %qE",
1281 expr_type, type, expr);
1284 else if (!TYPE_UNSIGNED (type) && TYPE_UNSIGNED (expr_type))
1286 if (cstresult)
1287 warning_at (loc, OPT_Wsign_conversion,
1288 "signed conversion from %qT to %qT changes "
1289 "value from %qE to %qE",
1290 expr_type, type, expr, result);
1291 else
1292 warning_at (loc, OPT_Wsign_conversion,
1293 "signed conversion from %qT to %qT changes "
1294 "the value of %qE",
1295 expr_type, type, expr);
1297 else
1298 give_warning = UNSAFE_OTHER;
1300 else if (TREE_CODE (type) == REAL_TYPE)
1302 /* Warn for an integer constant that does not fit into real type. */
1303 if (TREE_CODE (expr_type) == INTEGER_TYPE)
1305 REAL_VALUE_TYPE a = real_value_from_int_cst (0, expr);
1306 if (!exact_real_truncate (TYPE_MODE (type), &a))
1307 give_warning = UNSAFE_REAL;
1309 /* Warn for a real constant that does not fit into a smaller
1310 real type. */
1311 else if (TREE_CODE (expr_type) == REAL_TYPE
1312 && TYPE_PRECISION (type) < TYPE_PRECISION (expr_type))
1314 REAL_VALUE_TYPE a = TREE_REAL_CST (expr);
1315 if (!exact_real_truncate (TYPE_MODE (type), &a))
1316 give_warning = UNSAFE_REAL;
1321 else if (TREE_CODE (expr) == COMPLEX_CST)
1323 tree imag_part = TREE_IMAGPART (expr);
1324 /* Conversion from complex constant with zero imaginary part,
1325 perform check for conversion of real part. */
1326 if ((TREE_CODE (imag_part) == REAL_CST
1327 && real_zerop (imag_part))
1328 || (TREE_CODE (imag_part) == INTEGER_CST
1329 && integer_zerop (imag_part)))
1330 /* Note: in this branch we use recursive call to unsafe_conversion_p
1331 with different type of EXPR, but it is still safe, because when EXPR
1332 is a constant, it's type is not used in text of generated warnings
1333 (otherwise they could sound misleading). */
1334 return unsafe_conversion_p (loc, type, TREE_REALPART (expr), result,
1335 produce_warns);
1336 /* Conversion from complex constant with non-zero imaginary part. */
1337 else
1339 /* Conversion to complex type.
1340 Perform checks for both real and imaginary parts. */
1341 if (TREE_CODE (type) == COMPLEX_TYPE)
1343 /* Unfortunately, produce_warns must be false in two subsequent
1344 calls of unsafe_conversion_p, because otherwise we could
1345 produce strange "double" warnings, if both real and imaginary
1346 parts have conversion problems related to signedness.
1348 For example:
1349 int32_t _Complex a = 0x80000000 + 0x80000000i;
1351 Possible solution: add a separate function for checking
1352 constants and combine result of two calls appropriately. */
1353 enum conversion_safety re_safety =
1354 unsafe_conversion_p (loc, type, TREE_REALPART (expr),
1355 result, false);
1356 enum conversion_safety im_safety =
1357 unsafe_conversion_p (loc, type, imag_part, result, false);
1359 /* Merge the results into appropriate single warning. */
1361 /* Note: this case includes SAFE_CONVERSION, i.e. success. */
1362 if (re_safety == im_safety)
1363 give_warning = re_safety;
1364 else if (!re_safety && im_safety)
1365 give_warning = im_safety;
1366 else if (re_safety && !im_safety)
1367 give_warning = re_safety;
1368 else
1369 give_warning = UNSAFE_OTHER;
1371 /* Warn about conversion from complex to real or integer type. */
1372 else
1373 give_warning = UNSAFE_IMAGINARY;
1377 /* Checks for remaining case: EXPR is not constant. */
1378 else
1380 /* Warn for real types converted to integer types. */
1381 if (TREE_CODE (expr_type) == REAL_TYPE
1382 && TREE_CODE (type) == INTEGER_TYPE)
1383 give_warning = UNSAFE_REAL;
1385 else if (TREE_CODE (expr_type) == INTEGER_TYPE
1386 && TREE_CODE (type) == INTEGER_TYPE)
1388 /* Don't warn about unsigned char y = 0xff, x = (int) y; */
1389 expr = get_unwidened (expr, 0);
1390 expr_type = TREE_TYPE (expr);
1392 /* Don't warn for short y; short x = ((int)y & 0xff); */
1393 if (TREE_CODE (expr) == BIT_AND_EXPR
1394 || TREE_CODE (expr) == BIT_IOR_EXPR
1395 || TREE_CODE (expr) == BIT_XOR_EXPR)
1397 /* If both args were extended from a shortest type,
1398 use that type if that is safe. */
1399 expr_type = shorten_binary_op (expr_type,
1400 TREE_OPERAND (expr, 0),
1401 TREE_OPERAND (expr, 1),
1402 /* bitwise */1);
1404 if (TREE_CODE (expr) == BIT_AND_EXPR)
1406 tree op0 = TREE_OPERAND (expr, 0);
1407 tree op1 = TREE_OPERAND (expr, 1);
1408 bool unsigned0 = TYPE_UNSIGNED (TREE_TYPE (op0));
1409 bool unsigned1 = TYPE_UNSIGNED (TREE_TYPE (op1));
1411 /* If one of the operands is a non-negative constant
1412 that fits in the target type, then the type of the
1413 other operand does not matter. */
1414 if ((TREE_CODE (op0) == INTEGER_CST
1415 && int_fits_type_p (op0, c_common_signed_type (type))
1416 && int_fits_type_p (op0, c_common_unsigned_type (type)))
1417 || (TREE_CODE (op1) == INTEGER_CST
1418 && int_fits_type_p (op1, c_common_signed_type (type))
1419 && int_fits_type_p (op1,
1420 c_common_unsigned_type (type))))
1421 return SAFE_CONVERSION;
1422 /* If constant is unsigned and fits in the target
1423 type, then the result will also fit. */
1424 else if ((TREE_CODE (op0) == INTEGER_CST
1425 && unsigned0
1426 && int_fits_type_p (op0, type))
1427 || (TREE_CODE (op1) == INTEGER_CST
1428 && unsigned1
1429 && int_fits_type_p (op1, type)))
1430 return SAFE_CONVERSION;
1433 /* Warn for integer types converted to smaller integer types. */
1434 if (TYPE_PRECISION (type) < TYPE_PRECISION (expr_type))
1435 give_warning = UNSAFE_OTHER;
1437 /* When they are the same width but different signedness,
1438 then the value may change. */
1439 else if (((TYPE_PRECISION (type) == TYPE_PRECISION (expr_type)
1440 && TYPE_UNSIGNED (expr_type) != TYPE_UNSIGNED (type))
1441 /* Even when converted to a bigger type, if the type is
1442 unsigned but expr is signed, then negative values
1443 will be changed. */
1444 || (TYPE_UNSIGNED (type) && !TYPE_UNSIGNED (expr_type)))
1445 && produce_warns)
1446 warning_at (loc, OPT_Wsign_conversion, "conversion to %qT from %qT "
1447 "may change the sign of the result",
1448 type, expr_type);
1451 /* Warn for integer types converted to real types if and only if
1452 all the range of values of the integer type cannot be
1453 represented by the real type. */
1454 else if (TREE_CODE (expr_type) == INTEGER_TYPE
1455 && TREE_CODE (type) == REAL_TYPE)
1457 /* Don't warn about char y = 0xff; float x = (int) y; */
1458 expr = get_unwidened (expr, 0);
1459 expr_type = TREE_TYPE (expr);
1461 if (!int_safely_convertible_to_real_p (expr_type, type))
1462 give_warning = UNSAFE_OTHER;
1465 /* Warn for real types converted to smaller real types. */
1466 else if (TREE_CODE (expr_type) == REAL_TYPE
1467 && TREE_CODE (type) == REAL_TYPE
1468 && TYPE_PRECISION (type) < TYPE_PRECISION (expr_type))
1469 give_warning = UNSAFE_REAL;
1471 /* Check conversion between two complex types. */
1472 else if (TREE_CODE (expr_type) == COMPLEX_TYPE
1473 && TREE_CODE (type) == COMPLEX_TYPE)
1475 /* Extract underlying types (i.e., type of real and imaginary
1476 parts) of expr_type and type. */
1477 tree from_type = TREE_TYPE (expr_type);
1478 tree to_type = TREE_TYPE (type);
1480 /* Warn for real types converted to integer types. */
1481 if (TREE_CODE (from_type) == REAL_TYPE
1482 && TREE_CODE (to_type) == INTEGER_TYPE)
1483 give_warning = UNSAFE_REAL;
1485 /* Warn for real types converted to smaller real types. */
1486 else if (TREE_CODE (from_type) == REAL_TYPE
1487 && TREE_CODE (to_type) == REAL_TYPE
1488 && TYPE_PRECISION (to_type) < TYPE_PRECISION (from_type))
1489 give_warning = UNSAFE_REAL;
1491 /* Check conversion for complex integer types. Here implementation
1492 is simpler than for real-domain integers because it does not
1493 involve sophisticated cases, such as bitmasks, casts, etc. */
1494 else if (TREE_CODE (from_type) == INTEGER_TYPE
1495 && TREE_CODE (to_type) == INTEGER_TYPE)
1497 /* Warn for integer types converted to smaller integer types. */
1498 if (TYPE_PRECISION (to_type) < TYPE_PRECISION (from_type))
1499 give_warning = UNSAFE_OTHER;
1501 /* Check for different signedness, see case for real-domain
1502 integers (above) for a more detailed comment. */
1503 else if (((TYPE_PRECISION (to_type) == TYPE_PRECISION (from_type)
1504 && TYPE_UNSIGNED (to_type) != TYPE_UNSIGNED (from_type))
1505 || (TYPE_UNSIGNED (to_type) && !TYPE_UNSIGNED (from_type)))
1506 && produce_warns)
1507 warning_at (loc, OPT_Wsign_conversion,
1508 "conversion to %qT from %qT "
1509 "may change the sign of the result",
1510 type, expr_type);
1512 else if (TREE_CODE (from_type) == INTEGER_TYPE
1513 && TREE_CODE (to_type) == REAL_TYPE
1514 && !int_safely_convertible_to_real_p (from_type, to_type))
1515 give_warning = UNSAFE_OTHER;
1518 /* Warn for complex types converted to real or integer types. */
1519 else if (TREE_CODE (expr_type) == COMPLEX_TYPE
1520 && TREE_CODE (type) != COMPLEX_TYPE)
1521 give_warning = UNSAFE_IMAGINARY;
1524 return give_warning;
1528 /* Convert EXPR to TYPE, warning about conversion problems with constants.
1529 Invoke this function on every expression that is converted implicitly,
1530 i.e. because of language rules and not because of an explicit cast. */
1532 tree
1533 convert_and_check (location_t loc, tree type, tree expr)
1535 tree result;
1536 tree expr_for_warning;
1538 /* Convert from a value with possible excess precision rather than
1539 via the semantic type, but do not warn about values not fitting
1540 exactly in the semantic type. */
1541 if (TREE_CODE (expr) == EXCESS_PRECISION_EXPR)
1543 tree orig_type = TREE_TYPE (expr);
1544 expr = TREE_OPERAND (expr, 0);
1545 expr_for_warning = convert (orig_type, expr);
1546 if (orig_type == type)
1547 return expr_for_warning;
1549 else
1550 expr_for_warning = expr;
1552 if (TREE_TYPE (expr) == type)
1553 return expr;
1555 result = convert (type, expr);
1557 if (c_inhibit_evaluation_warnings == 0
1558 && !TREE_OVERFLOW_P (expr)
1559 && result != error_mark_node)
1560 warnings_for_convert_and_check (loc, type, expr_for_warning, result);
1562 return result;
1565 /* A node in a list that describes references to variables (EXPR), which are
1566 either read accesses if WRITER is zero, or write accesses, in which case
1567 WRITER is the parent of EXPR. */
1568 struct tlist
1570 struct tlist *next;
1571 tree expr, writer;
1574 /* Used to implement a cache the results of a call to verify_tree. We only
1575 use this for SAVE_EXPRs. */
1576 struct tlist_cache
1578 struct tlist_cache *next;
1579 struct tlist *cache_before_sp;
1580 struct tlist *cache_after_sp;
1581 tree expr;
1584 /* Obstack to use when allocating tlist structures, and corresponding
1585 firstobj. */
1586 static struct obstack tlist_obstack;
1587 static char *tlist_firstobj = 0;
1589 /* Keep track of the identifiers we've warned about, so we can avoid duplicate
1590 warnings. */
1591 static struct tlist *warned_ids;
1592 /* SAVE_EXPRs need special treatment. We process them only once and then
1593 cache the results. */
1594 static struct tlist_cache *save_expr_cache;
1596 static void add_tlist (struct tlist **, struct tlist *, tree, int);
1597 static void merge_tlist (struct tlist **, struct tlist *, int);
1598 static void verify_tree (tree, struct tlist **, struct tlist **, tree);
1599 static bool warning_candidate_p (tree);
1600 static bool candidate_equal_p (const_tree, const_tree);
1601 static void warn_for_collisions (struct tlist *);
1602 static void warn_for_collisions_1 (tree, tree, struct tlist *, int);
1603 static struct tlist *new_tlist (struct tlist *, tree, tree);
1605 /* Create a new struct tlist and fill in its fields. */
1606 static struct tlist *
1607 new_tlist (struct tlist *next, tree t, tree writer)
1609 struct tlist *l;
1610 l = XOBNEW (&tlist_obstack, struct tlist);
1611 l->next = next;
1612 l->expr = t;
1613 l->writer = writer;
1614 return l;
1617 /* Add duplicates of the nodes found in ADD to the list *TO. If EXCLUDE_WRITER
1618 is nonnull, we ignore any node we find which has a writer equal to it. */
1620 static void
1621 add_tlist (struct tlist **to, struct tlist *add, tree exclude_writer, int copy)
1623 while (add)
1625 struct tlist *next = add->next;
1626 if (!copy)
1627 add->next = *to;
1628 if (!exclude_writer || !candidate_equal_p (add->writer, exclude_writer))
1629 *to = copy ? new_tlist (*to, add->expr, add->writer) : add;
1630 add = next;
1634 /* Merge the nodes of ADD into TO. This merging process is done so that for
1635 each variable that already exists in TO, no new node is added; however if
1636 there is a write access recorded in ADD, and an occurrence on TO is only
1637 a read access, then the occurrence in TO will be modified to record the
1638 write. */
1640 static void
1641 merge_tlist (struct tlist **to, struct tlist *add, int copy)
1643 struct tlist **end = to;
1645 while (*end)
1646 end = &(*end)->next;
1648 while (add)
1650 int found = 0;
1651 struct tlist *tmp2;
1652 struct tlist *next = add->next;
1654 for (tmp2 = *to; tmp2; tmp2 = tmp2->next)
1655 if (candidate_equal_p (tmp2->expr, add->expr))
1657 found = 1;
1658 if (!tmp2->writer)
1659 tmp2->writer = add->writer;
1661 if (!found)
1663 *end = copy ? new_tlist (NULL, add->expr, add->writer) : add;
1664 end = &(*end)->next;
1665 *end = 0;
1667 add = next;
1671 /* WRITTEN is a variable, WRITER is its parent. Warn if any of the variable
1672 references in list LIST conflict with it, excluding reads if ONLY writers
1673 is nonzero. */
1675 static void
1676 warn_for_collisions_1 (tree written, tree writer, struct tlist *list,
1677 int only_writes)
1679 struct tlist *tmp;
1681 /* Avoid duplicate warnings. */
1682 for (tmp = warned_ids; tmp; tmp = tmp->next)
1683 if (candidate_equal_p (tmp->expr, written))
1684 return;
1686 while (list)
1688 if (candidate_equal_p (list->expr, written)
1689 && !candidate_equal_p (list->writer, writer)
1690 && (!only_writes || list->writer))
1692 warned_ids = new_tlist (warned_ids, written, NULL_TREE);
1693 warning_at (EXPR_LOC_OR_LOC (writer, input_location),
1694 OPT_Wsequence_point, "operation on %qE may be undefined",
1695 list->expr);
1697 list = list->next;
1701 /* Given a list LIST of references to variables, find whether any of these
1702 can cause conflicts due to missing sequence points. */
1704 static void
1705 warn_for_collisions (struct tlist *list)
1707 struct tlist *tmp;
1709 for (tmp = list; tmp; tmp = tmp->next)
1711 if (tmp->writer)
1712 warn_for_collisions_1 (tmp->expr, tmp->writer, list, 0);
1716 /* Return nonzero if X is a tree that can be verified by the sequence point
1717 warnings. */
1719 static bool
1720 warning_candidate_p (tree x)
1722 if (DECL_P (x) && DECL_ARTIFICIAL (x))
1723 return false;
1725 if (TREE_CODE (x) == BLOCK)
1726 return false;
1728 /* VOID_TYPE_P (TREE_TYPE (x)) is workaround for cp/tree.c
1729 (lvalue_p) crash on TRY/CATCH. */
1730 if (TREE_TYPE (x) == NULL_TREE || VOID_TYPE_P (TREE_TYPE (x)))
1731 return false;
1733 if (!lvalue_p (x))
1734 return false;
1736 /* No point to track non-const calls, they will never satisfy
1737 operand_equal_p. */
1738 if (TREE_CODE (x) == CALL_EXPR && (call_expr_flags (x) & ECF_CONST) == 0)
1739 return false;
1741 if (TREE_CODE (x) == STRING_CST)
1742 return false;
1744 return true;
1747 /* Return nonzero if X and Y appear to be the same candidate (or NULL) */
1748 static bool
1749 candidate_equal_p (const_tree x, const_tree y)
1751 return (x == y) || (x && y && operand_equal_p (x, y, 0));
1754 /* Walk the tree X, and record accesses to variables. If X is written by the
1755 parent tree, WRITER is the parent.
1756 We store accesses in one of the two lists: PBEFORE_SP, and PNO_SP. If this
1757 expression or its only operand forces a sequence point, then everything up
1758 to the sequence point is stored in PBEFORE_SP. Everything else gets stored
1759 in PNO_SP.
1760 Once we return, we will have emitted warnings if any subexpression before
1761 such a sequence point could be undefined. On a higher level, however, the
1762 sequence point may not be relevant, and we'll merge the two lists.
1764 Example: (b++, a) + b;
1765 The call that processes the COMPOUND_EXPR will store the increment of B
1766 in PBEFORE_SP, and the use of A in PNO_SP. The higher-level call that
1767 processes the PLUS_EXPR will need to merge the two lists so that
1768 eventually, all accesses end up on the same list (and we'll warn about the
1769 unordered subexpressions b++ and b.
1771 A note on merging. If we modify the former example so that our expression
1772 becomes
1773 (b++, b) + a
1774 care must be taken not simply to add all three expressions into the final
1775 PNO_SP list. The function merge_tlist takes care of that by merging the
1776 before-SP list of the COMPOUND_EXPR into its after-SP list in a special
1777 way, so that no more than one access to B is recorded. */
1779 static void
1780 verify_tree (tree x, struct tlist **pbefore_sp, struct tlist **pno_sp,
1781 tree writer)
1783 struct tlist *tmp_before, *tmp_nosp, *tmp_list2, *tmp_list3;
1784 enum tree_code code;
1785 enum tree_code_class cl;
1787 /* X may be NULL if it is the operand of an empty statement expression
1788 ({ }). */
1789 if (x == NULL)
1790 return;
1792 restart:
1793 code = TREE_CODE (x);
1794 cl = TREE_CODE_CLASS (code);
1796 if (warning_candidate_p (x))
1797 *pno_sp = new_tlist (*pno_sp, x, writer);
1799 switch (code)
1801 case CONSTRUCTOR:
1802 case SIZEOF_EXPR:
1803 return;
1805 case COMPOUND_EXPR:
1806 case TRUTH_ANDIF_EXPR:
1807 case TRUTH_ORIF_EXPR:
1808 tmp_before = tmp_nosp = tmp_list2 = tmp_list3 = 0;
1809 verify_tree (TREE_OPERAND (x, 0), &tmp_before, &tmp_nosp, NULL_TREE);
1810 warn_for_collisions (tmp_nosp);
1811 merge_tlist (pbefore_sp, tmp_before, 0);
1812 merge_tlist (pbefore_sp, tmp_nosp, 0);
1813 verify_tree (TREE_OPERAND (x, 1), &tmp_list3, &tmp_list2, NULL_TREE);
1814 warn_for_collisions (tmp_list2);
1815 merge_tlist (pbefore_sp, tmp_list3, 0);
1816 merge_tlist (pno_sp, tmp_list2, 0);
1817 return;
1819 case COND_EXPR:
1820 tmp_before = tmp_list2 = 0;
1821 verify_tree (TREE_OPERAND (x, 0), &tmp_before, &tmp_list2, NULL_TREE);
1822 warn_for_collisions (tmp_list2);
1823 merge_tlist (pbefore_sp, tmp_before, 0);
1824 merge_tlist (pbefore_sp, tmp_list2, 0);
1826 tmp_list3 = tmp_nosp = 0;
1827 verify_tree (TREE_OPERAND (x, 1), &tmp_list3, &tmp_nosp, NULL_TREE);
1828 warn_for_collisions (tmp_nosp);
1829 merge_tlist (pbefore_sp, tmp_list3, 0);
1831 tmp_list3 = tmp_list2 = 0;
1832 verify_tree (TREE_OPERAND (x, 2), &tmp_list3, &tmp_list2, NULL_TREE);
1833 warn_for_collisions (tmp_list2);
1834 merge_tlist (pbefore_sp, tmp_list3, 0);
1835 /* Rather than add both tmp_nosp and tmp_list2, we have to merge the
1836 two first, to avoid warning for (a ? b++ : b++). */
1837 merge_tlist (&tmp_nosp, tmp_list2, 0);
1838 add_tlist (pno_sp, tmp_nosp, NULL_TREE, 0);
1839 return;
1841 case PREDECREMENT_EXPR:
1842 case PREINCREMENT_EXPR:
1843 case POSTDECREMENT_EXPR:
1844 case POSTINCREMENT_EXPR:
1845 verify_tree (TREE_OPERAND (x, 0), pno_sp, pno_sp, x);
1846 return;
1848 case MODIFY_EXPR:
1849 tmp_before = tmp_nosp = tmp_list3 = 0;
1850 verify_tree (TREE_OPERAND (x, 1), &tmp_before, &tmp_nosp, NULL_TREE);
1851 verify_tree (TREE_OPERAND (x, 0), &tmp_list3, &tmp_list3, x);
1852 /* Expressions inside the LHS are not ordered wrt. the sequence points
1853 in the RHS. Example:
1854 *a = (a++, 2)
1855 Despite the fact that the modification of "a" is in the before_sp
1856 list (tmp_before), it conflicts with the use of "a" in the LHS.
1857 We can handle this by adding the contents of tmp_list3
1858 to those of tmp_before, and redoing the collision warnings for that
1859 list. */
1860 add_tlist (&tmp_before, tmp_list3, x, 1);
1861 warn_for_collisions (tmp_before);
1862 /* Exclude the LHS itself here; we first have to merge it into the
1863 tmp_nosp list. This is done to avoid warning for "a = a"; if we
1864 didn't exclude the LHS, we'd get it twice, once as a read and once
1865 as a write. */
1866 add_tlist (pno_sp, tmp_list3, x, 0);
1867 warn_for_collisions_1 (TREE_OPERAND (x, 0), x, tmp_nosp, 1);
1869 merge_tlist (pbefore_sp, tmp_before, 0);
1870 if (warning_candidate_p (TREE_OPERAND (x, 0)))
1871 merge_tlist (&tmp_nosp, new_tlist (NULL, TREE_OPERAND (x, 0), x), 0);
1872 add_tlist (pno_sp, tmp_nosp, NULL_TREE, 1);
1873 return;
1875 case CALL_EXPR:
1876 /* We need to warn about conflicts among arguments and conflicts between
1877 args and the function address. Side effects of the function address,
1878 however, are not ordered by the sequence point of the call. */
1880 call_expr_arg_iterator iter;
1881 tree arg;
1882 tmp_before = tmp_nosp = 0;
1883 verify_tree (CALL_EXPR_FN (x), &tmp_before, &tmp_nosp, NULL_TREE);
1884 FOR_EACH_CALL_EXPR_ARG (arg, iter, x)
1886 tmp_list2 = tmp_list3 = 0;
1887 verify_tree (arg, &tmp_list2, &tmp_list3, NULL_TREE);
1888 merge_tlist (&tmp_list3, tmp_list2, 0);
1889 add_tlist (&tmp_before, tmp_list3, NULL_TREE, 0);
1891 add_tlist (&tmp_before, tmp_nosp, NULL_TREE, 0);
1892 warn_for_collisions (tmp_before);
1893 add_tlist (pbefore_sp, tmp_before, NULL_TREE, 0);
1894 return;
1897 case TREE_LIST:
1898 /* Scan all the list, e.g. indices of multi dimensional array. */
1899 while (x)
1901 tmp_before = tmp_nosp = 0;
1902 verify_tree (TREE_VALUE (x), &tmp_before, &tmp_nosp, NULL_TREE);
1903 merge_tlist (&tmp_nosp, tmp_before, 0);
1904 add_tlist (pno_sp, tmp_nosp, NULL_TREE, 0);
1905 x = TREE_CHAIN (x);
1907 return;
1909 case SAVE_EXPR:
1911 struct tlist_cache *t;
1912 for (t = save_expr_cache; t; t = t->next)
1913 if (candidate_equal_p (t->expr, x))
1914 break;
1916 if (!t)
1918 t = XOBNEW (&tlist_obstack, struct tlist_cache);
1919 t->next = save_expr_cache;
1920 t->expr = x;
1921 save_expr_cache = t;
1923 tmp_before = tmp_nosp = 0;
1924 verify_tree (TREE_OPERAND (x, 0), &tmp_before, &tmp_nosp, NULL_TREE);
1925 warn_for_collisions (tmp_nosp);
1927 tmp_list3 = 0;
1928 merge_tlist (&tmp_list3, tmp_nosp, 0);
1929 t->cache_before_sp = tmp_before;
1930 t->cache_after_sp = tmp_list3;
1932 merge_tlist (pbefore_sp, t->cache_before_sp, 1);
1933 add_tlist (pno_sp, t->cache_after_sp, NULL_TREE, 1);
1934 return;
1937 case ADDR_EXPR:
1938 x = TREE_OPERAND (x, 0);
1939 if (DECL_P (x))
1940 return;
1941 writer = 0;
1942 goto restart;
1944 default:
1945 /* For other expressions, simply recurse on their operands.
1946 Manual tail recursion for unary expressions.
1947 Other non-expressions need not be processed. */
1948 if (cl == tcc_unary)
1950 x = TREE_OPERAND (x, 0);
1951 writer = 0;
1952 goto restart;
1954 else if (IS_EXPR_CODE_CLASS (cl))
1956 int lp;
1957 int max = TREE_OPERAND_LENGTH (x);
1958 for (lp = 0; lp < max; lp++)
1960 tmp_before = tmp_nosp = 0;
1961 verify_tree (TREE_OPERAND (x, lp), &tmp_before, &tmp_nosp, 0);
1962 merge_tlist (&tmp_nosp, tmp_before, 0);
1963 add_tlist (pno_sp, tmp_nosp, NULL_TREE, 0);
1966 return;
1970 /* Try to warn for undefined behavior in EXPR due to missing sequence
1971 points. */
1973 DEBUG_FUNCTION void
1974 verify_sequence_points (tree expr)
1976 struct tlist *before_sp = 0, *after_sp = 0;
1978 warned_ids = 0;
1979 save_expr_cache = 0;
1980 if (tlist_firstobj == 0)
1982 gcc_obstack_init (&tlist_obstack);
1983 tlist_firstobj = (char *) obstack_alloc (&tlist_obstack, 0);
1986 verify_tree (expr, &before_sp, &after_sp, 0);
1987 warn_for_collisions (after_sp);
1988 obstack_free (&tlist_obstack, tlist_firstobj);
1991 /* Validate the expression after `case' and apply default promotions. */
1993 static tree
1994 check_case_value (location_t loc, tree value)
1996 if (value == NULL_TREE)
1997 return value;
1999 if (TREE_CODE (value) == INTEGER_CST)
2000 /* Promote char or short to int. */
2001 value = perform_integral_promotions (value);
2002 else if (value != error_mark_node)
2004 error_at (loc, "case label does not reduce to an integer constant");
2005 value = error_mark_node;
2008 constant_expression_warning (value);
2010 return value;
2013 /* See if the case values LOW and HIGH are in the range of the original
2014 type (i.e. before the default conversion to int) of the switch testing
2015 expression.
2016 TYPE is the promoted type of the testing expression, and ORIG_TYPE is
2017 the type before promoting it. CASE_LOW_P is a pointer to the lower
2018 bound of the case label, and CASE_HIGH_P is the upper bound or NULL
2019 if the case is not a case range.
2020 The caller has to make sure that we are not called with NULL for
2021 CASE_LOW_P (i.e. the default case). OUTSIDE_RANGE_P says whether there
2022 was a case value that doesn't fit into the range of the ORIG_TYPE.
2023 Returns true if the case label is in range of ORIG_TYPE (saturated or
2024 untouched) or false if the label is out of range. */
2026 static bool
2027 check_case_bounds (location_t loc, tree type, tree orig_type,
2028 tree *case_low_p, tree *case_high_p,
2029 bool *outside_range_p)
2031 tree min_value, max_value;
2032 tree case_low = *case_low_p;
2033 tree case_high = case_high_p ? *case_high_p : case_low;
2035 /* If there was a problem with the original type, do nothing. */
2036 if (orig_type == error_mark_node)
2037 return true;
2039 min_value = TYPE_MIN_VALUE (orig_type);
2040 max_value = TYPE_MAX_VALUE (orig_type);
2042 /* We'll really need integer constants here. */
2043 case_low = fold (case_low);
2044 case_high = fold (case_high);
2046 /* Case label is less than minimum for type. */
2047 if (tree_int_cst_compare (case_low, min_value) < 0
2048 && tree_int_cst_compare (case_high, min_value) < 0)
2050 warning_at (loc, 0, "case label value is less than minimum value "
2051 "for type");
2052 *outside_range_p = true;
2053 return false;
2056 /* Case value is greater than maximum for type. */
2057 if (tree_int_cst_compare (case_low, max_value) > 0
2058 && tree_int_cst_compare (case_high, max_value) > 0)
2060 warning_at (loc, 0, "case label value exceeds maximum value for type");
2061 *outside_range_p = true;
2062 return false;
2065 /* Saturate lower case label value to minimum. */
2066 if (tree_int_cst_compare (case_high, min_value) >= 0
2067 && tree_int_cst_compare (case_low, min_value) < 0)
2069 warning_at (loc, 0, "lower value in case label range"
2070 " less than minimum value for type");
2071 *outside_range_p = true;
2072 case_low = min_value;
2075 /* Saturate upper case label value to maximum. */
2076 if (tree_int_cst_compare (case_low, max_value) <= 0
2077 && tree_int_cst_compare (case_high, max_value) > 0)
2079 warning_at (loc, 0, "upper value in case label range"
2080 " exceeds maximum value for type");
2081 *outside_range_p = true;
2082 case_high = max_value;
2085 if (*case_low_p != case_low)
2086 *case_low_p = convert (type, case_low);
2087 if (case_high_p && *case_high_p != case_high)
2088 *case_high_p = convert (type, case_high);
2090 return true;
2093 /* Return an integer type with BITS bits of precision,
2094 that is unsigned if UNSIGNEDP is nonzero, otherwise signed. */
2096 tree
2097 c_common_type_for_size (unsigned int bits, int unsignedp)
2099 int i;
2101 if (bits == TYPE_PRECISION (integer_type_node))
2102 return unsignedp ? unsigned_type_node : integer_type_node;
2104 if (bits == TYPE_PRECISION (signed_char_type_node))
2105 return unsignedp ? unsigned_char_type_node : signed_char_type_node;
2107 if (bits == TYPE_PRECISION (short_integer_type_node))
2108 return unsignedp ? short_unsigned_type_node : short_integer_type_node;
2110 if (bits == TYPE_PRECISION (long_integer_type_node))
2111 return unsignedp ? long_unsigned_type_node : long_integer_type_node;
2113 if (bits == TYPE_PRECISION (long_long_integer_type_node))
2114 return (unsignedp ? long_long_unsigned_type_node
2115 : long_long_integer_type_node);
2117 for (i = 0; i < NUM_INT_N_ENTS; i ++)
2118 if (int_n_enabled_p[i]
2119 && bits == int_n_data[i].bitsize)
2120 return (unsignedp ? int_n_trees[i].unsigned_type
2121 : int_n_trees[i].signed_type);
2123 if (bits == TYPE_PRECISION (widest_integer_literal_type_node))
2124 return (unsignedp ? widest_unsigned_literal_type_node
2125 : widest_integer_literal_type_node);
2127 if (bits <= TYPE_PRECISION (intQI_type_node))
2128 return unsignedp ? unsigned_intQI_type_node : intQI_type_node;
2130 if (bits <= TYPE_PRECISION (intHI_type_node))
2131 return unsignedp ? unsigned_intHI_type_node : intHI_type_node;
2133 if (bits <= TYPE_PRECISION (intSI_type_node))
2134 return unsignedp ? unsigned_intSI_type_node : intSI_type_node;
2136 if (bits <= TYPE_PRECISION (intDI_type_node))
2137 return unsignedp ? unsigned_intDI_type_node : intDI_type_node;
2139 return NULL_TREE;
2142 /* Return a fixed-point type that has at least IBIT ibits and FBIT fbits
2143 that is unsigned if UNSIGNEDP is nonzero, otherwise signed;
2144 and saturating if SATP is nonzero, otherwise not saturating. */
2146 tree
2147 c_common_fixed_point_type_for_size (unsigned int ibit, unsigned int fbit,
2148 int unsignedp, int satp)
2150 enum mode_class mclass;
2151 if (ibit == 0)
2152 mclass = unsignedp ? MODE_UFRACT : MODE_FRACT;
2153 else
2154 mclass = unsignedp ? MODE_UACCUM : MODE_ACCUM;
2156 opt_scalar_mode opt_mode;
2157 scalar_mode mode;
2158 FOR_EACH_MODE_IN_CLASS (opt_mode, mclass)
2160 mode = opt_mode.require ();
2161 if (GET_MODE_IBIT (mode) >= ibit && GET_MODE_FBIT (mode) >= fbit)
2162 break;
2165 if (!opt_mode.exists (&mode) || !targetm.scalar_mode_supported_p (mode))
2167 sorry ("GCC cannot support operators with integer types and "
2168 "fixed-point types that have too many integral and "
2169 "fractional bits together");
2170 return NULL_TREE;
2173 return c_common_type_for_mode (mode, satp);
2176 /* Used for communication between c_common_type_for_mode and
2177 c_register_builtin_type. */
2178 tree registered_builtin_types;
2180 /* Return a data type that has machine mode MODE.
2181 If the mode is an integer,
2182 then UNSIGNEDP selects between signed and unsigned types.
2183 If the mode is a fixed-point mode,
2184 then UNSIGNEDP selects between saturating and nonsaturating types. */
2186 tree
2187 c_common_type_for_mode (machine_mode mode, int unsignedp)
2189 tree t;
2190 int i;
2192 if (mode == TYPE_MODE (integer_type_node))
2193 return unsignedp ? unsigned_type_node : integer_type_node;
2195 if (mode == TYPE_MODE (signed_char_type_node))
2196 return unsignedp ? unsigned_char_type_node : signed_char_type_node;
2198 if (mode == TYPE_MODE (short_integer_type_node))
2199 return unsignedp ? short_unsigned_type_node : short_integer_type_node;
2201 if (mode == TYPE_MODE (long_integer_type_node))
2202 return unsignedp ? long_unsigned_type_node : long_integer_type_node;
2204 if (mode == TYPE_MODE (long_long_integer_type_node))
2205 return unsignedp ? long_long_unsigned_type_node : long_long_integer_type_node;
2207 for (i = 0; i < NUM_INT_N_ENTS; i ++)
2208 if (int_n_enabled_p[i]
2209 && mode == int_n_data[i].m)
2210 return (unsignedp ? int_n_trees[i].unsigned_type
2211 : int_n_trees[i].signed_type);
2213 if (mode == QImode)
2214 return unsignedp ? unsigned_intQI_type_node : intQI_type_node;
2216 if (mode == HImode)
2217 return unsignedp ? unsigned_intHI_type_node : intHI_type_node;
2219 if (mode == SImode)
2220 return unsignedp ? unsigned_intSI_type_node : intSI_type_node;
2222 if (mode == DImode)
2223 return unsignedp ? unsigned_intDI_type_node : intDI_type_node;
2225 #if HOST_BITS_PER_WIDE_INT >= 64
2226 if (mode == TYPE_MODE (intTI_type_node))
2227 return unsignedp ? unsigned_intTI_type_node : intTI_type_node;
2228 #endif
2230 if (mode == TYPE_MODE (float_type_node))
2231 return float_type_node;
2233 if (mode == TYPE_MODE (double_type_node))
2234 return double_type_node;
2236 if (mode == TYPE_MODE (long_double_type_node))
2237 return long_double_type_node;
2239 for (i = 0; i < NUM_FLOATN_NX_TYPES; i++)
2240 if (FLOATN_NX_TYPE_NODE (i) != NULL_TREE
2241 && mode == TYPE_MODE (FLOATN_NX_TYPE_NODE (i)))
2242 return FLOATN_NX_TYPE_NODE (i);
2244 if (mode == TYPE_MODE (void_type_node))
2245 return void_type_node;
2247 if (mode == TYPE_MODE (build_pointer_type (char_type_node))
2248 || mode == TYPE_MODE (build_pointer_type (integer_type_node)))
2250 unsigned int precision
2251 = GET_MODE_PRECISION (as_a <scalar_int_mode> (mode));
2252 return (unsignedp
2253 ? make_unsigned_type (precision)
2254 : make_signed_type (precision));
2257 if (COMPLEX_MODE_P (mode))
2259 machine_mode inner_mode;
2260 tree inner_type;
2262 if (mode == TYPE_MODE (complex_float_type_node))
2263 return complex_float_type_node;
2264 if (mode == TYPE_MODE (complex_double_type_node))
2265 return complex_double_type_node;
2266 if (mode == TYPE_MODE (complex_long_double_type_node))
2267 return complex_long_double_type_node;
2269 for (i = 0; i < NUM_FLOATN_NX_TYPES; i++)
2270 if (COMPLEX_FLOATN_NX_TYPE_NODE (i) != NULL_TREE
2271 && mode == TYPE_MODE (COMPLEX_FLOATN_NX_TYPE_NODE (i)))
2272 return COMPLEX_FLOATN_NX_TYPE_NODE (i);
2274 if (mode == TYPE_MODE (complex_integer_type_node) && !unsignedp)
2275 return complex_integer_type_node;
2277 inner_mode = GET_MODE_INNER (mode);
2278 inner_type = c_common_type_for_mode (inner_mode, unsignedp);
2279 if (inner_type != NULL_TREE)
2280 return build_complex_type (inner_type);
2282 else if (VECTOR_MODE_P (mode)
2283 && valid_vector_subparts_p (GET_MODE_NUNITS (mode)))
2285 machine_mode inner_mode = GET_MODE_INNER (mode);
2286 tree inner_type = c_common_type_for_mode (inner_mode, unsignedp);
2287 if (inner_type != NULL_TREE)
2288 return build_vector_type_for_mode (inner_type, mode);
2291 if (mode == TYPE_MODE (dfloat32_type_node))
2292 return dfloat32_type_node;
2293 if (mode == TYPE_MODE (dfloat64_type_node))
2294 return dfloat64_type_node;
2295 if (mode == TYPE_MODE (dfloat128_type_node))
2296 return dfloat128_type_node;
2298 if (ALL_SCALAR_FIXED_POINT_MODE_P (mode))
2300 if (mode == TYPE_MODE (short_fract_type_node))
2301 return unsignedp ? sat_short_fract_type_node : short_fract_type_node;
2302 if (mode == TYPE_MODE (fract_type_node))
2303 return unsignedp ? sat_fract_type_node : fract_type_node;
2304 if (mode == TYPE_MODE (long_fract_type_node))
2305 return unsignedp ? sat_long_fract_type_node : long_fract_type_node;
2306 if (mode == TYPE_MODE (long_long_fract_type_node))
2307 return unsignedp ? sat_long_long_fract_type_node
2308 : long_long_fract_type_node;
2310 if (mode == TYPE_MODE (unsigned_short_fract_type_node))
2311 return unsignedp ? sat_unsigned_short_fract_type_node
2312 : unsigned_short_fract_type_node;
2313 if (mode == TYPE_MODE (unsigned_fract_type_node))
2314 return unsignedp ? sat_unsigned_fract_type_node
2315 : unsigned_fract_type_node;
2316 if (mode == TYPE_MODE (unsigned_long_fract_type_node))
2317 return unsignedp ? sat_unsigned_long_fract_type_node
2318 : unsigned_long_fract_type_node;
2319 if (mode == TYPE_MODE (unsigned_long_long_fract_type_node))
2320 return unsignedp ? sat_unsigned_long_long_fract_type_node
2321 : unsigned_long_long_fract_type_node;
2323 if (mode == TYPE_MODE (short_accum_type_node))
2324 return unsignedp ? sat_short_accum_type_node : short_accum_type_node;
2325 if (mode == TYPE_MODE (accum_type_node))
2326 return unsignedp ? sat_accum_type_node : accum_type_node;
2327 if (mode == TYPE_MODE (long_accum_type_node))
2328 return unsignedp ? sat_long_accum_type_node : long_accum_type_node;
2329 if (mode == TYPE_MODE (long_long_accum_type_node))
2330 return unsignedp ? sat_long_long_accum_type_node
2331 : long_long_accum_type_node;
2333 if (mode == TYPE_MODE (unsigned_short_accum_type_node))
2334 return unsignedp ? sat_unsigned_short_accum_type_node
2335 : unsigned_short_accum_type_node;
2336 if (mode == TYPE_MODE (unsigned_accum_type_node))
2337 return unsignedp ? sat_unsigned_accum_type_node
2338 : unsigned_accum_type_node;
2339 if (mode == TYPE_MODE (unsigned_long_accum_type_node))
2340 return unsignedp ? sat_unsigned_long_accum_type_node
2341 : unsigned_long_accum_type_node;
2342 if (mode == TYPE_MODE (unsigned_long_long_accum_type_node))
2343 return unsignedp ? sat_unsigned_long_long_accum_type_node
2344 : unsigned_long_long_accum_type_node;
2346 if (mode == QQmode)
2347 return unsignedp ? sat_qq_type_node : qq_type_node;
2348 if (mode == HQmode)
2349 return unsignedp ? sat_hq_type_node : hq_type_node;
2350 if (mode == SQmode)
2351 return unsignedp ? sat_sq_type_node : sq_type_node;
2352 if (mode == DQmode)
2353 return unsignedp ? sat_dq_type_node : dq_type_node;
2354 if (mode == TQmode)
2355 return unsignedp ? sat_tq_type_node : tq_type_node;
2357 if (mode == UQQmode)
2358 return unsignedp ? sat_uqq_type_node : uqq_type_node;
2359 if (mode == UHQmode)
2360 return unsignedp ? sat_uhq_type_node : uhq_type_node;
2361 if (mode == USQmode)
2362 return unsignedp ? sat_usq_type_node : usq_type_node;
2363 if (mode == UDQmode)
2364 return unsignedp ? sat_udq_type_node : udq_type_node;
2365 if (mode == UTQmode)
2366 return unsignedp ? sat_utq_type_node : utq_type_node;
2368 if (mode == HAmode)
2369 return unsignedp ? sat_ha_type_node : ha_type_node;
2370 if (mode == SAmode)
2371 return unsignedp ? sat_sa_type_node : sa_type_node;
2372 if (mode == DAmode)
2373 return unsignedp ? sat_da_type_node : da_type_node;
2374 if (mode == TAmode)
2375 return unsignedp ? sat_ta_type_node : ta_type_node;
2377 if (mode == UHAmode)
2378 return unsignedp ? sat_uha_type_node : uha_type_node;
2379 if (mode == USAmode)
2380 return unsignedp ? sat_usa_type_node : usa_type_node;
2381 if (mode == UDAmode)
2382 return unsignedp ? sat_uda_type_node : uda_type_node;
2383 if (mode == UTAmode)
2384 return unsignedp ? sat_uta_type_node : uta_type_node;
2387 for (t = registered_builtin_types; t; t = TREE_CHAIN (t))
2388 if (TYPE_MODE (TREE_VALUE (t)) == mode
2389 && !!unsignedp == !!TYPE_UNSIGNED (TREE_VALUE (t)))
2390 return TREE_VALUE (t);
2392 return NULL_TREE;
2395 tree
2396 c_common_unsigned_type (tree type)
2398 return c_common_signed_or_unsigned_type (1, type);
2401 /* Return a signed type the same as TYPE in other respects. */
2403 tree
2404 c_common_signed_type (tree type)
2406 return c_common_signed_or_unsigned_type (0, type);
2409 /* Return a type the same as TYPE except unsigned or
2410 signed according to UNSIGNEDP. */
2412 tree
2413 c_common_signed_or_unsigned_type (int unsignedp, tree type)
2415 tree type1;
2416 int i;
2418 /* This block of code emulates the behavior of the old
2419 c_common_unsigned_type. In particular, it returns
2420 long_unsigned_type_node if passed a long, even when a int would
2421 have the same size. This is necessary for warnings to work
2422 correctly in archs where sizeof(int) == sizeof(long) */
2424 type1 = TYPE_MAIN_VARIANT (type);
2425 if (type1 == signed_char_type_node || type1 == char_type_node || type1 == unsigned_char_type_node)
2426 return unsignedp ? unsigned_char_type_node : signed_char_type_node;
2427 if (type1 == integer_type_node || type1 == unsigned_type_node)
2428 return unsignedp ? unsigned_type_node : integer_type_node;
2429 if (type1 == short_integer_type_node || type1 == short_unsigned_type_node)
2430 return unsignedp ? short_unsigned_type_node : short_integer_type_node;
2431 if (type1 == long_integer_type_node || type1 == long_unsigned_type_node)
2432 return unsignedp ? long_unsigned_type_node : long_integer_type_node;
2433 if (type1 == long_long_integer_type_node || type1 == long_long_unsigned_type_node)
2434 return unsignedp ? long_long_unsigned_type_node : long_long_integer_type_node;
2436 for (i = 0; i < NUM_INT_N_ENTS; i ++)
2437 if (int_n_enabled_p[i]
2438 && (type1 == int_n_trees[i].unsigned_type
2439 || type1 == int_n_trees[i].signed_type))
2440 return (unsignedp ? int_n_trees[i].unsigned_type
2441 : int_n_trees[i].signed_type);
2443 #if HOST_BITS_PER_WIDE_INT >= 64
2444 if (type1 == intTI_type_node || type1 == unsigned_intTI_type_node)
2445 return unsignedp ? unsigned_intTI_type_node : intTI_type_node;
2446 #endif
2447 if (type1 == intDI_type_node || type1 == unsigned_intDI_type_node)
2448 return unsignedp ? unsigned_intDI_type_node : intDI_type_node;
2449 if (type1 == intSI_type_node || type1 == unsigned_intSI_type_node)
2450 return unsignedp ? unsigned_intSI_type_node : intSI_type_node;
2451 if (type1 == intHI_type_node || type1 == unsigned_intHI_type_node)
2452 return unsignedp ? unsigned_intHI_type_node : intHI_type_node;
2453 if (type1 == intQI_type_node || type1 == unsigned_intQI_type_node)
2454 return unsignedp ? unsigned_intQI_type_node : intQI_type_node;
2456 #define C_COMMON_FIXED_TYPES(NAME) \
2457 if (type1 == short_ ## NAME ## _type_node \
2458 || type1 == unsigned_short_ ## NAME ## _type_node) \
2459 return unsignedp ? unsigned_short_ ## NAME ## _type_node \
2460 : short_ ## NAME ## _type_node; \
2461 if (type1 == NAME ## _type_node \
2462 || type1 == unsigned_ ## NAME ## _type_node) \
2463 return unsignedp ? unsigned_ ## NAME ## _type_node \
2464 : NAME ## _type_node; \
2465 if (type1 == long_ ## NAME ## _type_node \
2466 || type1 == unsigned_long_ ## NAME ## _type_node) \
2467 return unsignedp ? unsigned_long_ ## NAME ## _type_node \
2468 : long_ ## NAME ## _type_node; \
2469 if (type1 == long_long_ ## NAME ## _type_node \
2470 || type1 == unsigned_long_long_ ## NAME ## _type_node) \
2471 return unsignedp ? unsigned_long_long_ ## NAME ## _type_node \
2472 : long_long_ ## NAME ## _type_node;
2474 #define C_COMMON_FIXED_MODE_TYPES(NAME) \
2475 if (type1 == NAME ## _type_node \
2476 || type1 == u ## NAME ## _type_node) \
2477 return unsignedp ? u ## NAME ## _type_node \
2478 : NAME ## _type_node;
2480 #define C_COMMON_FIXED_TYPES_SAT(NAME) \
2481 if (type1 == sat_ ## short_ ## NAME ## _type_node \
2482 || type1 == sat_ ## unsigned_short_ ## NAME ## _type_node) \
2483 return unsignedp ? sat_ ## unsigned_short_ ## NAME ## _type_node \
2484 : sat_ ## short_ ## NAME ## _type_node; \
2485 if (type1 == sat_ ## NAME ## _type_node \
2486 || type1 == sat_ ## unsigned_ ## NAME ## _type_node) \
2487 return unsignedp ? sat_ ## unsigned_ ## NAME ## _type_node \
2488 : sat_ ## NAME ## _type_node; \
2489 if (type1 == sat_ ## long_ ## NAME ## _type_node \
2490 || type1 == sat_ ## unsigned_long_ ## NAME ## _type_node) \
2491 return unsignedp ? sat_ ## unsigned_long_ ## NAME ## _type_node \
2492 : sat_ ## long_ ## NAME ## _type_node; \
2493 if (type1 == sat_ ## long_long_ ## NAME ## _type_node \
2494 || type1 == sat_ ## unsigned_long_long_ ## NAME ## _type_node) \
2495 return unsignedp ? sat_ ## unsigned_long_long_ ## NAME ## _type_node \
2496 : sat_ ## long_long_ ## NAME ## _type_node;
2498 #define C_COMMON_FIXED_MODE_TYPES_SAT(NAME) \
2499 if (type1 == sat_ ## NAME ## _type_node \
2500 || type1 == sat_ ## u ## NAME ## _type_node) \
2501 return unsignedp ? sat_ ## u ## NAME ## _type_node \
2502 : sat_ ## NAME ## _type_node;
2504 C_COMMON_FIXED_TYPES (fract);
2505 C_COMMON_FIXED_TYPES_SAT (fract);
2506 C_COMMON_FIXED_TYPES (accum);
2507 C_COMMON_FIXED_TYPES_SAT (accum);
2509 C_COMMON_FIXED_MODE_TYPES (qq);
2510 C_COMMON_FIXED_MODE_TYPES (hq);
2511 C_COMMON_FIXED_MODE_TYPES (sq);
2512 C_COMMON_FIXED_MODE_TYPES (dq);
2513 C_COMMON_FIXED_MODE_TYPES (tq);
2514 C_COMMON_FIXED_MODE_TYPES_SAT (qq);
2515 C_COMMON_FIXED_MODE_TYPES_SAT (hq);
2516 C_COMMON_FIXED_MODE_TYPES_SAT (sq);
2517 C_COMMON_FIXED_MODE_TYPES_SAT (dq);
2518 C_COMMON_FIXED_MODE_TYPES_SAT (tq);
2519 C_COMMON_FIXED_MODE_TYPES (ha);
2520 C_COMMON_FIXED_MODE_TYPES (sa);
2521 C_COMMON_FIXED_MODE_TYPES (da);
2522 C_COMMON_FIXED_MODE_TYPES (ta);
2523 C_COMMON_FIXED_MODE_TYPES_SAT (ha);
2524 C_COMMON_FIXED_MODE_TYPES_SAT (sa);
2525 C_COMMON_FIXED_MODE_TYPES_SAT (da);
2526 C_COMMON_FIXED_MODE_TYPES_SAT (ta);
2528 /* For ENUMERAL_TYPEs in C++, must check the mode of the types, not
2529 the precision; they have precision set to match their range, but
2530 may use a wider mode to match an ABI. If we change modes, we may
2531 wind up with bad conversions. For INTEGER_TYPEs in C, must check
2532 the precision as well, so as to yield correct results for
2533 bit-field types. C++ does not have these separate bit-field
2534 types, and producing a signed or unsigned variant of an
2535 ENUMERAL_TYPE may cause other problems as well. */
2537 if (!INTEGRAL_TYPE_P (type)
2538 || TYPE_UNSIGNED (type) == unsignedp)
2539 return type;
2541 #define TYPE_OK(node) \
2542 (TYPE_MODE (type) == TYPE_MODE (node) \
2543 && TYPE_PRECISION (type) == TYPE_PRECISION (node))
2544 if (TYPE_OK (signed_char_type_node))
2545 return unsignedp ? unsigned_char_type_node : signed_char_type_node;
2546 if (TYPE_OK (integer_type_node))
2547 return unsignedp ? unsigned_type_node : integer_type_node;
2548 if (TYPE_OK (short_integer_type_node))
2549 return unsignedp ? short_unsigned_type_node : short_integer_type_node;
2550 if (TYPE_OK (long_integer_type_node))
2551 return unsignedp ? long_unsigned_type_node : long_integer_type_node;
2552 if (TYPE_OK (long_long_integer_type_node))
2553 return (unsignedp ? long_long_unsigned_type_node
2554 : long_long_integer_type_node);
2556 for (i = 0; i < NUM_INT_N_ENTS; i ++)
2557 if (int_n_enabled_p[i]
2558 && TYPE_MODE (type) == int_n_data[i].m
2559 && TYPE_PRECISION (type) == int_n_data[i].bitsize)
2560 return (unsignedp ? int_n_trees[i].unsigned_type
2561 : int_n_trees[i].signed_type);
2563 #if HOST_BITS_PER_WIDE_INT >= 64
2564 if (TYPE_OK (intTI_type_node))
2565 return unsignedp ? unsigned_intTI_type_node : intTI_type_node;
2566 #endif
2567 if (TYPE_OK (intDI_type_node))
2568 return unsignedp ? unsigned_intDI_type_node : intDI_type_node;
2569 if (TYPE_OK (intSI_type_node))
2570 return unsignedp ? unsigned_intSI_type_node : intSI_type_node;
2571 if (TYPE_OK (intHI_type_node))
2572 return unsignedp ? unsigned_intHI_type_node : intHI_type_node;
2573 if (TYPE_OK (intQI_type_node))
2574 return unsignedp ? unsigned_intQI_type_node : intQI_type_node;
2575 #undef TYPE_OK
2577 return build_nonstandard_integer_type (TYPE_PRECISION (type), unsignedp);
2580 /* Build a bit-field integer type for the given WIDTH and UNSIGNEDP. */
2582 tree
2583 c_build_bitfield_integer_type (unsigned HOST_WIDE_INT width, int unsignedp)
2585 int i;
2587 /* Extended integer types of the same width as a standard type have
2588 lesser rank, so those of the same width as int promote to int or
2589 unsigned int and are valid for printf formats expecting int or
2590 unsigned int. To avoid such special cases, avoid creating
2591 extended integer types for bit-fields if a standard integer type
2592 is available. */
2593 if (width == TYPE_PRECISION (integer_type_node))
2594 return unsignedp ? unsigned_type_node : integer_type_node;
2595 if (width == TYPE_PRECISION (signed_char_type_node))
2596 return unsignedp ? unsigned_char_type_node : signed_char_type_node;
2597 if (width == TYPE_PRECISION (short_integer_type_node))
2598 return unsignedp ? short_unsigned_type_node : short_integer_type_node;
2599 if (width == TYPE_PRECISION (long_integer_type_node))
2600 return unsignedp ? long_unsigned_type_node : long_integer_type_node;
2601 if (width == TYPE_PRECISION (long_long_integer_type_node))
2602 return (unsignedp ? long_long_unsigned_type_node
2603 : long_long_integer_type_node);
2604 for (i = 0; i < NUM_INT_N_ENTS; i ++)
2605 if (int_n_enabled_p[i]
2606 && width == int_n_data[i].bitsize)
2607 return (unsignedp ? int_n_trees[i].unsigned_type
2608 : int_n_trees[i].signed_type);
2609 return build_nonstandard_integer_type (width, unsignedp);
2612 /* The C version of the register_builtin_type langhook. */
2614 void
2615 c_register_builtin_type (tree type, const char* name)
2617 tree decl;
2619 decl = build_decl (UNKNOWN_LOCATION,
2620 TYPE_DECL, get_identifier (name), type);
2621 DECL_ARTIFICIAL (decl) = 1;
2622 if (!TYPE_NAME (type))
2623 TYPE_NAME (type) = decl;
2624 lang_hooks.decls.pushdecl (decl);
2626 registered_builtin_types = tree_cons (0, type, registered_builtin_types);
2629 /* Print an error message for invalid operands to arith operation
2630 CODE with TYPE0 for operand 0, and TYPE1 for operand 1.
2631 RICHLOC is a rich location for the message, containing either
2632 three separate locations for each of the operator and operands
2634 lhs op rhs
2635 ~~~ ^~ ~~~
2637 (C FE), or one location ranging over all over them
2639 lhs op rhs
2640 ~~~~^~~~~~
2642 (C++ FE). */
2644 void
2645 binary_op_error (rich_location *richloc, enum tree_code code,
2646 tree type0, tree type1)
2648 const char *opname;
2650 switch (code)
2652 case PLUS_EXPR:
2653 opname = "+"; break;
2654 case MINUS_EXPR:
2655 opname = "-"; break;
2656 case MULT_EXPR:
2657 opname = "*"; break;
2658 case MAX_EXPR:
2659 opname = "max"; break;
2660 case MIN_EXPR:
2661 opname = "min"; break;
2662 case EQ_EXPR:
2663 opname = "=="; break;
2664 case NE_EXPR:
2665 opname = "!="; break;
2666 case LE_EXPR:
2667 opname = "<="; break;
2668 case GE_EXPR:
2669 opname = ">="; break;
2670 case LT_EXPR:
2671 opname = "<"; break;
2672 case GT_EXPR:
2673 opname = ">"; break;
2674 case LSHIFT_EXPR:
2675 opname = "<<"; break;
2676 case RSHIFT_EXPR:
2677 opname = ">>"; break;
2678 case TRUNC_MOD_EXPR:
2679 case FLOOR_MOD_EXPR:
2680 opname = "%"; break;
2681 case TRUNC_DIV_EXPR:
2682 case FLOOR_DIV_EXPR:
2683 opname = "/"; break;
2684 case BIT_AND_EXPR:
2685 opname = "&"; break;
2686 case BIT_IOR_EXPR:
2687 opname = "|"; break;
2688 case TRUTH_ANDIF_EXPR:
2689 opname = "&&"; break;
2690 case TRUTH_ORIF_EXPR:
2691 opname = "||"; break;
2692 case BIT_XOR_EXPR:
2693 opname = "^"; break;
2694 default:
2695 gcc_unreachable ();
2697 error_at (richloc,
2698 "invalid operands to binary %s (have %qT and %qT)",
2699 opname, type0, type1);
2702 /* Given an expression as a tree, return its original type. Do this
2703 by stripping any conversion that preserves the sign and precision. */
2704 static tree
2705 expr_original_type (tree expr)
2707 STRIP_SIGN_NOPS (expr);
2708 return TREE_TYPE (expr);
2711 /* Subroutine of build_binary_op, used for comparison operations.
2712 See if the operands have both been converted from subword integer types
2713 and, if so, perhaps change them both back to their original type.
2714 This function is also responsible for converting the two operands
2715 to the proper common type for comparison.
2717 The arguments of this function are all pointers to local variables
2718 of build_binary_op: OP0_PTR is &OP0, OP1_PTR is &OP1,
2719 RESTYPE_PTR is &RESULT_TYPE and RESCODE_PTR is &RESULTCODE.
2721 LOC is the location of the comparison.
2723 If this function returns non-NULL_TREE, it means that the comparison has
2724 a constant value. What this function returns is an expression for
2725 that value. */
2727 tree
2728 shorten_compare (location_t loc, tree *op0_ptr, tree *op1_ptr,
2729 tree *restype_ptr, enum tree_code *rescode_ptr)
2731 tree type;
2732 tree op0 = *op0_ptr;
2733 tree op1 = *op1_ptr;
2734 int unsignedp0, unsignedp1;
2735 int real1, real2;
2736 tree primop0, primop1;
2737 enum tree_code code = *rescode_ptr;
2739 /* Throw away any conversions to wider types
2740 already present in the operands. */
2742 primop0 = c_common_get_narrower (op0, &unsignedp0);
2743 primop1 = c_common_get_narrower (op1, &unsignedp1);
2745 /* If primopN is first sign-extended from primopN's precision to opN's
2746 precision, then zero-extended from opN's precision to
2747 *restype_ptr precision, shortenings might be invalid. */
2748 if (TYPE_PRECISION (TREE_TYPE (primop0)) < TYPE_PRECISION (TREE_TYPE (op0))
2749 && TYPE_PRECISION (TREE_TYPE (op0)) < TYPE_PRECISION (*restype_ptr)
2750 && !unsignedp0
2751 && TYPE_UNSIGNED (TREE_TYPE (op0)))
2752 primop0 = op0;
2753 if (TYPE_PRECISION (TREE_TYPE (primop1)) < TYPE_PRECISION (TREE_TYPE (op1))
2754 && TYPE_PRECISION (TREE_TYPE (op1)) < TYPE_PRECISION (*restype_ptr)
2755 && !unsignedp1
2756 && TYPE_UNSIGNED (TREE_TYPE (op1)))
2757 primop1 = op1;
2759 /* Handle the case that OP0 does not *contain* a conversion
2760 but it *requires* conversion to FINAL_TYPE. */
2762 if (op0 == primop0 && TREE_TYPE (op0) != *restype_ptr)
2763 unsignedp0 = TYPE_UNSIGNED (TREE_TYPE (op0));
2764 if (op1 == primop1 && TREE_TYPE (op1) != *restype_ptr)
2765 unsignedp1 = TYPE_UNSIGNED (TREE_TYPE (op1));
2767 /* If one of the operands must be floated, we cannot optimize. */
2768 real1 = TREE_CODE (TREE_TYPE (primop0)) == REAL_TYPE;
2769 real2 = TREE_CODE (TREE_TYPE (primop1)) == REAL_TYPE;
2771 /* If first arg is constant, swap the args (changing operation
2772 so value is preserved), for canonicalization. Don't do this if
2773 the second arg is 0. */
2775 if (TREE_CONSTANT (primop0)
2776 && !integer_zerop (primop1) && !real_zerop (primop1)
2777 && !fixed_zerop (primop1))
2779 std::swap (primop0, primop1);
2780 std::swap (op0, op1);
2781 *op0_ptr = op0;
2782 *op1_ptr = op1;
2783 std::swap (unsignedp0, unsignedp1);
2784 std::swap (real1, real2);
2786 switch (code)
2788 case LT_EXPR:
2789 code = GT_EXPR;
2790 break;
2791 case GT_EXPR:
2792 code = LT_EXPR;
2793 break;
2794 case LE_EXPR:
2795 code = GE_EXPR;
2796 break;
2797 case GE_EXPR:
2798 code = LE_EXPR;
2799 break;
2800 default:
2801 break;
2803 *rescode_ptr = code;
2806 /* If comparing an integer against a constant more bits wide,
2807 maybe we can deduce a value of 1 or 0 independent of the data.
2808 Or else truncate the constant now
2809 rather than extend the variable at run time.
2811 This is only interesting if the constant is the wider arg.
2812 Also, it is not safe if the constant is unsigned and the
2813 variable arg is signed, since in this case the variable
2814 would be sign-extended and then regarded as unsigned.
2815 Our technique fails in this case because the lowest/highest
2816 possible unsigned results don't follow naturally from the
2817 lowest/highest possible values of the variable operand.
2818 For just EQ_EXPR and NE_EXPR there is another technique that
2819 could be used: see if the constant can be faithfully represented
2820 in the other operand's type, by truncating it and reextending it
2821 and see if that preserves the constant's value. */
2823 if (!real1 && !real2
2824 && TREE_CODE (TREE_TYPE (primop0)) != FIXED_POINT_TYPE
2825 && TREE_CODE (primop1) == INTEGER_CST
2826 && TYPE_PRECISION (TREE_TYPE (primop0)) < TYPE_PRECISION (*restype_ptr))
2828 int min_gt, max_gt, min_lt, max_lt;
2829 tree maxval, minval;
2830 /* 1 if comparison is nominally unsigned. */
2831 int unsignedp = TYPE_UNSIGNED (*restype_ptr);
2832 tree val;
2834 type = c_common_signed_or_unsigned_type (unsignedp0,
2835 TREE_TYPE (primop0));
2837 maxval = TYPE_MAX_VALUE (type);
2838 minval = TYPE_MIN_VALUE (type);
2840 if (unsignedp && !unsignedp0)
2841 *restype_ptr = c_common_signed_type (*restype_ptr);
2843 if (TREE_TYPE (primop1) != *restype_ptr)
2845 /* Convert primop1 to target type, but do not introduce
2846 additional overflow. We know primop1 is an int_cst. */
2847 primop1 = force_fit_type (*restype_ptr,
2848 wi::to_wide
2849 (primop1,
2850 TYPE_PRECISION (*restype_ptr)),
2851 0, TREE_OVERFLOW (primop1));
2853 if (type != *restype_ptr)
2855 minval = convert (*restype_ptr, minval);
2856 maxval = convert (*restype_ptr, maxval);
2859 min_gt = tree_int_cst_lt (primop1, minval);
2860 max_gt = tree_int_cst_lt (primop1, maxval);
2861 min_lt = tree_int_cst_lt (minval, primop1);
2862 max_lt = tree_int_cst_lt (maxval, primop1);
2864 val = 0;
2865 /* This used to be a switch, but Genix compiler can't handle that. */
2866 if (code == NE_EXPR)
2868 if (max_lt || min_gt)
2869 val = truthvalue_true_node;
2871 else if (code == EQ_EXPR)
2873 if (max_lt || min_gt)
2874 val = truthvalue_false_node;
2876 else if (code == LT_EXPR)
2878 if (max_lt)
2879 val = truthvalue_true_node;
2880 if (!min_lt)
2881 val = truthvalue_false_node;
2883 else if (code == GT_EXPR)
2885 if (min_gt)
2886 val = truthvalue_true_node;
2887 if (!max_gt)
2888 val = truthvalue_false_node;
2890 else if (code == LE_EXPR)
2892 if (!max_gt)
2893 val = truthvalue_true_node;
2894 if (min_gt)
2895 val = truthvalue_false_node;
2897 else if (code == GE_EXPR)
2899 if (!min_lt)
2900 val = truthvalue_true_node;
2901 if (max_lt)
2902 val = truthvalue_false_node;
2905 /* If primop0 was sign-extended and unsigned comparison specd,
2906 we did a signed comparison above using the signed type bounds.
2907 But the comparison we output must be unsigned.
2909 Also, for inequalities, VAL is no good; but if the signed
2910 comparison had *any* fixed result, it follows that the
2911 unsigned comparison just tests the sign in reverse
2912 (positive values are LE, negative ones GE).
2913 So we can generate an unsigned comparison
2914 against an extreme value of the signed type. */
2916 if (unsignedp && !unsignedp0)
2918 if (val != 0)
2919 switch (code)
2921 case LT_EXPR:
2922 case GE_EXPR:
2923 primop1 = TYPE_MIN_VALUE (type);
2924 val = 0;
2925 break;
2927 case LE_EXPR:
2928 case GT_EXPR:
2929 primop1 = TYPE_MAX_VALUE (type);
2930 val = 0;
2931 break;
2933 default:
2934 break;
2936 type = c_common_unsigned_type (type);
2939 if (TREE_CODE (primop0) != INTEGER_CST
2940 /* Don't warn if it's from a (non-system) macro. */
2941 && !(from_macro_expansion_at
2942 (expansion_point_location_if_in_system_header
2943 (EXPR_LOCATION (primop0)))))
2945 if (val == truthvalue_false_node)
2946 warning_at (loc, OPT_Wtype_limits,
2947 "comparison is always false due to limited range of data type");
2948 if (val == truthvalue_true_node)
2949 warning_at (loc, OPT_Wtype_limits,
2950 "comparison is always true due to limited range of data type");
2953 if (val != 0)
2955 /* Don't forget to evaluate PRIMOP0 if it has side effects. */
2956 if (TREE_SIDE_EFFECTS (primop0))
2957 return build2 (COMPOUND_EXPR, TREE_TYPE (val), primop0, val);
2958 return val;
2961 /* Value is not predetermined, but do the comparison
2962 in the type of the operand that is not constant.
2963 TYPE is already properly set. */
2966 /* If either arg is decimal float and the other is float, find the
2967 proper common type to use for comparison. */
2968 else if (real1 && real2
2969 && DECIMAL_FLOAT_MODE_P (TYPE_MODE (TREE_TYPE (primop0)))
2970 && DECIMAL_FLOAT_MODE_P (TYPE_MODE (TREE_TYPE (primop1))))
2971 type = common_type (TREE_TYPE (primop0), TREE_TYPE (primop1));
2973 /* If either arg is decimal float and the other is float, fail. */
2974 else if (real1 && real2
2975 && (DECIMAL_FLOAT_MODE_P (TYPE_MODE (TREE_TYPE (primop0)))
2976 || DECIMAL_FLOAT_MODE_P (TYPE_MODE (TREE_TYPE (primop1)))))
2977 return NULL_TREE;
2979 else if (real1 && real2
2980 && (TYPE_PRECISION (TREE_TYPE (primop0))
2981 == TYPE_PRECISION (TREE_TYPE (primop1))))
2982 type = TREE_TYPE (primop0);
2984 /* If args' natural types are both narrower than nominal type
2985 and both extend in the same manner, compare them
2986 in the type of the wider arg.
2987 Otherwise must actually extend both to the nominal
2988 common type lest different ways of extending
2989 alter the result.
2990 (eg, (short)-1 == (unsigned short)-1 should be 0.) */
2992 else if (unsignedp0 == unsignedp1 && real1 == real2
2993 && TYPE_PRECISION (TREE_TYPE (primop0)) < TYPE_PRECISION (*restype_ptr)
2994 && TYPE_PRECISION (TREE_TYPE (primop1)) < TYPE_PRECISION (*restype_ptr))
2996 type = common_type (TREE_TYPE (primop0), TREE_TYPE (primop1));
2997 type = c_common_signed_or_unsigned_type (unsignedp0
2998 || TYPE_UNSIGNED (*restype_ptr),
2999 type);
3000 /* Make sure shorter operand is extended the right way
3001 to match the longer operand. */
3002 primop0
3003 = convert (c_common_signed_or_unsigned_type (unsignedp0,
3004 TREE_TYPE (primop0)),
3005 primop0);
3006 primop1
3007 = convert (c_common_signed_or_unsigned_type (unsignedp1,
3008 TREE_TYPE (primop1)),
3009 primop1);
3011 else
3013 /* Here we must do the comparison on the nominal type
3014 using the args exactly as we received them. */
3015 type = *restype_ptr;
3016 primop0 = op0;
3017 primop1 = op1;
3019 if (!real1 && !real2 && integer_zerop (primop1)
3020 && TYPE_UNSIGNED (*restype_ptr))
3022 tree value = NULL_TREE;
3023 /* All unsigned values are >= 0, so we warn. However,
3024 if OP0 is a constant that is >= 0, the signedness of
3025 the comparison isn't an issue, so suppress the
3026 warning. */
3027 bool warn =
3028 warn_type_limits && !in_system_header_at (loc)
3029 && !(TREE_CODE (primop0) == INTEGER_CST
3030 && !TREE_OVERFLOW (convert (c_common_signed_type (type),
3031 primop0)))
3032 /* Do not warn for enumeration types. */
3033 && (TREE_CODE (expr_original_type (primop0)) != ENUMERAL_TYPE);
3035 switch (code)
3037 case GE_EXPR:
3038 if (warn)
3039 warning_at (loc, OPT_Wtype_limits,
3040 "comparison of unsigned expression >= 0 is always true");
3041 value = truthvalue_true_node;
3042 break;
3044 case LT_EXPR:
3045 if (warn)
3046 warning_at (loc, OPT_Wtype_limits,
3047 "comparison of unsigned expression < 0 is always false");
3048 value = truthvalue_false_node;
3049 break;
3051 default:
3052 break;
3055 if (value != NULL_TREE)
3057 /* Don't forget to evaluate PRIMOP0 if it has side effects. */
3058 if (TREE_SIDE_EFFECTS (primop0))
3059 return build2 (COMPOUND_EXPR, TREE_TYPE (value),
3060 primop0, value);
3061 return value;
3066 *op0_ptr = convert (type, primop0);
3067 *op1_ptr = convert (type, primop1);
3069 *restype_ptr = truthvalue_type_node;
3071 return NULL_TREE;
3074 /* Return a tree for the sum or difference (RESULTCODE says which)
3075 of pointer PTROP and integer INTOP. */
3077 tree
3078 pointer_int_sum (location_t loc, enum tree_code resultcode,
3079 tree ptrop, tree intop, bool complain)
3081 tree size_exp, ret;
3083 /* The result is a pointer of the same type that is being added. */
3084 tree result_type = TREE_TYPE (ptrop);
3086 if (TREE_CODE (TREE_TYPE (result_type)) == VOID_TYPE)
3088 if (complain && warn_pointer_arith)
3089 pedwarn (loc, OPT_Wpointer_arith,
3090 "pointer of type %<void *%> used in arithmetic");
3091 else if (!complain)
3092 return error_mark_node;
3093 size_exp = integer_one_node;
3095 else if (TREE_CODE (TREE_TYPE (result_type)) == FUNCTION_TYPE)
3097 if (complain && warn_pointer_arith)
3098 pedwarn (loc, OPT_Wpointer_arith,
3099 "pointer to a function used in arithmetic");
3100 else if (!complain)
3101 return error_mark_node;
3102 size_exp = integer_one_node;
3104 else
3105 size_exp = size_in_bytes_loc (loc, TREE_TYPE (result_type));
3107 /* We are manipulating pointer values, so we don't need to warn
3108 about relying on undefined signed overflow. We disable the
3109 warning here because we use integer types so fold won't know that
3110 they are really pointers. */
3111 fold_defer_overflow_warnings ();
3113 /* If what we are about to multiply by the size of the elements
3114 contains a constant term, apply distributive law
3115 and multiply that constant term separately.
3116 This helps produce common subexpressions. */
3117 if ((TREE_CODE (intop) == PLUS_EXPR || TREE_CODE (intop) == MINUS_EXPR)
3118 && !TREE_CONSTANT (intop)
3119 && TREE_CONSTANT (TREE_OPERAND (intop, 1))
3120 && TREE_CONSTANT (size_exp)
3121 /* If the constant comes from pointer subtraction,
3122 skip this optimization--it would cause an error. */
3123 && TREE_CODE (TREE_TYPE (TREE_OPERAND (intop, 0))) == INTEGER_TYPE
3124 /* If the constant is unsigned, and smaller than the pointer size,
3125 then we must skip this optimization. This is because it could cause
3126 an overflow error if the constant is negative but INTOP is not. */
3127 && (!TYPE_UNSIGNED (TREE_TYPE (intop))
3128 || (TYPE_PRECISION (TREE_TYPE (intop))
3129 == TYPE_PRECISION (TREE_TYPE (ptrop)))))
3131 enum tree_code subcode = resultcode;
3132 tree int_type = TREE_TYPE (intop);
3133 if (TREE_CODE (intop) == MINUS_EXPR)
3134 subcode = (subcode == PLUS_EXPR ? MINUS_EXPR : PLUS_EXPR);
3135 /* Convert both subexpression types to the type of intop,
3136 because weird cases involving pointer arithmetic
3137 can result in a sum or difference with different type args. */
3138 ptrop = build_binary_op (EXPR_LOCATION (TREE_OPERAND (intop, 1)),
3139 subcode, ptrop,
3140 convert (int_type, TREE_OPERAND (intop, 1)),
3141 true);
3142 intop = convert (int_type, TREE_OPERAND (intop, 0));
3145 /* Convert the integer argument to a type the same size as sizetype
3146 so the multiply won't overflow spuriously. */
3147 if (TYPE_PRECISION (TREE_TYPE (intop)) != TYPE_PRECISION (sizetype)
3148 || TYPE_UNSIGNED (TREE_TYPE (intop)) != TYPE_UNSIGNED (sizetype))
3149 intop = convert (c_common_type_for_size (TYPE_PRECISION (sizetype),
3150 TYPE_UNSIGNED (sizetype)), intop);
3152 /* Replace the integer argument with a suitable product by the object size.
3153 Do this multiplication as signed, then convert to the appropriate type
3154 for the pointer operation and disregard an overflow that occurred only
3155 because of the sign-extension change in the latter conversion. */
3157 tree t = fold_build2_loc (loc, MULT_EXPR, TREE_TYPE (intop), intop,
3158 convert (TREE_TYPE (intop), size_exp));
3159 intop = convert (sizetype, t);
3160 if (TREE_OVERFLOW_P (intop) && !TREE_OVERFLOW (t))
3161 intop = wide_int_to_tree (TREE_TYPE (intop), wi::to_wide (intop));
3164 /* Create the sum or difference. */
3165 if (resultcode == MINUS_EXPR)
3166 intop = fold_build1_loc (loc, NEGATE_EXPR, sizetype, intop);
3168 ret = fold_build_pointer_plus_loc (loc, ptrop, intop);
3170 fold_undefer_and_ignore_overflow_warnings ();
3172 return ret;
3175 /* Wrap a C_MAYBE_CONST_EXPR around an expression that is fully folded
3176 and if NON_CONST is known not to be permitted in an evaluated part
3177 of a constant expression. */
3179 tree
3180 c_wrap_maybe_const (tree expr, bool non_const)
3182 bool nowarning = TREE_NO_WARNING (expr);
3183 location_t loc = EXPR_LOCATION (expr);
3185 /* This should never be called for C++. */
3186 if (c_dialect_cxx ())
3187 gcc_unreachable ();
3189 /* The result of folding may have a NOP_EXPR to set TREE_NO_WARNING. */
3190 STRIP_TYPE_NOPS (expr);
3191 expr = build2 (C_MAYBE_CONST_EXPR, TREE_TYPE (expr), NULL, expr);
3192 C_MAYBE_CONST_EXPR_NON_CONST (expr) = non_const;
3193 if (nowarning)
3194 TREE_NO_WARNING (expr) = 1;
3195 protected_set_expr_location (expr, loc);
3197 return expr;
3200 /* Return whether EXPR is a declaration whose address can never be
3201 NULL. */
3203 bool
3204 decl_with_nonnull_addr_p (const_tree expr)
3206 return (DECL_P (expr)
3207 && (TREE_CODE (expr) == PARM_DECL
3208 || TREE_CODE (expr) == LABEL_DECL
3209 || !DECL_WEAK (expr)));
3212 /* Prepare expr to be an argument of a TRUTH_NOT_EXPR,
3213 or for an `if' or `while' statement or ?..: exp. It should already
3214 have been validated to be of suitable type; otherwise, a bad
3215 diagnostic may result.
3217 The EXPR is located at LOCATION.
3219 This preparation consists of taking the ordinary
3220 representation of an expression expr and producing a valid tree
3221 boolean expression describing whether expr is nonzero. We could
3222 simply always do build_binary_op (NE_EXPR, expr, truthvalue_false_node, 1),
3223 but we optimize comparisons, &&, ||, and !.
3225 The resulting type should always be `truthvalue_type_node'. */
3227 tree
3228 c_common_truthvalue_conversion (location_t location, tree expr)
3230 switch (TREE_CODE (expr))
3232 case EQ_EXPR: case NE_EXPR: case UNEQ_EXPR: case LTGT_EXPR:
3233 case LE_EXPR: case GE_EXPR: case LT_EXPR: case GT_EXPR:
3234 case UNLE_EXPR: case UNGE_EXPR: case UNLT_EXPR: case UNGT_EXPR:
3235 case ORDERED_EXPR: case UNORDERED_EXPR:
3236 if (TREE_TYPE (expr) == truthvalue_type_node)
3237 return expr;
3238 expr = build2 (TREE_CODE (expr), truthvalue_type_node,
3239 TREE_OPERAND (expr, 0), TREE_OPERAND (expr, 1));
3240 goto ret;
3242 case TRUTH_ANDIF_EXPR:
3243 case TRUTH_ORIF_EXPR:
3244 case TRUTH_AND_EXPR:
3245 case TRUTH_OR_EXPR:
3246 case TRUTH_XOR_EXPR:
3247 if (TREE_TYPE (expr) == truthvalue_type_node)
3248 return expr;
3249 expr = build2 (TREE_CODE (expr), truthvalue_type_node,
3250 c_common_truthvalue_conversion (location,
3251 TREE_OPERAND (expr, 0)),
3252 c_common_truthvalue_conversion (location,
3253 TREE_OPERAND (expr, 1)));
3254 goto ret;
3256 case TRUTH_NOT_EXPR:
3257 if (TREE_TYPE (expr) == truthvalue_type_node)
3258 return expr;
3259 expr = build1 (TREE_CODE (expr), truthvalue_type_node,
3260 c_common_truthvalue_conversion (location,
3261 TREE_OPERAND (expr, 0)));
3262 goto ret;
3264 case ERROR_MARK:
3265 return expr;
3267 case INTEGER_CST:
3268 if (TREE_CODE (TREE_TYPE (expr)) == ENUMERAL_TYPE
3269 && !integer_zerop (expr)
3270 && !integer_onep (expr))
3271 warning_at (location, OPT_Wint_in_bool_context,
3272 "enum constant in boolean context");
3273 return integer_zerop (expr) ? truthvalue_false_node
3274 : truthvalue_true_node;
3276 case REAL_CST:
3277 return real_compare (NE_EXPR, &TREE_REAL_CST (expr), &dconst0)
3278 ? truthvalue_true_node
3279 : truthvalue_false_node;
3281 case FIXED_CST:
3282 return fixed_compare (NE_EXPR, &TREE_FIXED_CST (expr),
3283 &FCONST0 (TYPE_MODE (TREE_TYPE (expr))))
3284 ? truthvalue_true_node
3285 : truthvalue_false_node;
3287 case FUNCTION_DECL:
3288 expr = build_unary_op (location, ADDR_EXPR, expr, false);
3289 /* Fall through. */
3291 case ADDR_EXPR:
3293 tree inner = TREE_OPERAND (expr, 0);
3294 if (decl_with_nonnull_addr_p (inner))
3296 /* Common Ada/Pascal programmer's mistake. */
3297 warning_at (location,
3298 OPT_Waddress,
3299 "the address of %qD will always evaluate as %<true%>",
3300 inner);
3301 return truthvalue_true_node;
3303 break;
3306 case COMPLEX_EXPR:
3307 expr = build_binary_op (EXPR_LOCATION (expr),
3308 (TREE_SIDE_EFFECTS (TREE_OPERAND (expr, 1))
3309 ? TRUTH_OR_EXPR : TRUTH_ORIF_EXPR),
3310 c_common_truthvalue_conversion (location,
3311 TREE_OPERAND (expr, 0)),
3312 c_common_truthvalue_conversion (location,
3313 TREE_OPERAND (expr, 1)),
3314 false);
3315 goto ret;
3317 case NEGATE_EXPR:
3318 case ABS_EXPR:
3319 case FLOAT_EXPR:
3320 case EXCESS_PRECISION_EXPR:
3321 /* These don't change whether an object is nonzero or zero. */
3322 return c_common_truthvalue_conversion (location, TREE_OPERAND (expr, 0));
3324 case LROTATE_EXPR:
3325 case RROTATE_EXPR:
3326 /* These don't change whether an object is zero or nonzero, but
3327 we can't ignore them if their second arg has side-effects. */
3328 if (TREE_SIDE_EFFECTS (TREE_OPERAND (expr, 1)))
3330 expr = build2 (COMPOUND_EXPR, truthvalue_type_node,
3331 TREE_OPERAND (expr, 1),
3332 c_common_truthvalue_conversion
3333 (location, TREE_OPERAND (expr, 0)));
3334 goto ret;
3336 else
3337 return c_common_truthvalue_conversion (location,
3338 TREE_OPERAND (expr, 0));
3340 case MULT_EXPR:
3341 warning_at (EXPR_LOCATION (expr), OPT_Wint_in_bool_context,
3342 "%<*%> in boolean context, suggest %<&&%> instead");
3343 break;
3345 case LSHIFT_EXPR:
3346 /* We will only warn on signed shifts here, because the majority of
3347 false positive warnings happen in code where unsigned arithmetic
3348 was used in anticipation of a possible overflow.
3349 Furthermore, if we see an unsigned type here we know that the
3350 result of the shift is not subject to integer promotion rules. */
3351 if (TREE_CODE (TREE_TYPE (expr)) == INTEGER_TYPE
3352 && !TYPE_UNSIGNED (TREE_TYPE (expr)))
3353 warning_at (EXPR_LOCATION (expr), OPT_Wint_in_bool_context,
3354 "%<<<%> in boolean context, did you mean %<<%> ?");
3355 break;
3357 case COND_EXPR:
3358 if (warn_int_in_bool_context
3359 && !from_macro_definition_at (EXPR_LOCATION (expr)))
3361 tree val1 = fold_for_warn (TREE_OPERAND (expr, 1));
3362 tree val2 = fold_for_warn (TREE_OPERAND (expr, 2));
3363 if (TREE_CODE (val1) == INTEGER_CST
3364 && TREE_CODE (val2) == INTEGER_CST
3365 && !integer_zerop (val1)
3366 && !integer_zerop (val2)
3367 && (!integer_onep (val1)
3368 || !integer_onep (val2)))
3369 warning_at (EXPR_LOCATION (expr), OPT_Wint_in_bool_context,
3370 "?: using integer constants in boolean context, "
3371 "the expression will always evaluate to %<true%>");
3372 else if ((TREE_CODE (val1) == INTEGER_CST
3373 && !integer_zerop (val1)
3374 && !integer_onep (val1))
3375 || (TREE_CODE (val2) == INTEGER_CST
3376 && !integer_zerop (val2)
3377 && !integer_onep (val2)))
3378 warning_at (EXPR_LOCATION (expr), OPT_Wint_in_bool_context,
3379 "?: using integer constants in boolean context");
3381 /* Distribute the conversion into the arms of a COND_EXPR. */
3382 if (c_dialect_cxx ())
3383 /* Avoid premature folding. */
3384 break;
3385 else
3387 int w = warn_int_in_bool_context;
3388 warn_int_in_bool_context = 0;
3389 /* Folding will happen later for C. */
3390 expr = build3 (COND_EXPR, truthvalue_type_node,
3391 TREE_OPERAND (expr, 0),
3392 c_common_truthvalue_conversion (location,
3393 TREE_OPERAND (expr, 1)),
3394 c_common_truthvalue_conversion (location,
3395 TREE_OPERAND (expr, 2)));
3396 warn_int_in_bool_context = w;
3397 goto ret;
3400 CASE_CONVERT:
3402 tree totype = TREE_TYPE (expr);
3403 tree fromtype = TREE_TYPE (TREE_OPERAND (expr, 0));
3405 if (POINTER_TYPE_P (totype)
3406 && !c_inhibit_evaluation_warnings
3407 && TREE_CODE (fromtype) == REFERENCE_TYPE)
3409 tree inner = expr;
3410 STRIP_NOPS (inner);
3412 if (DECL_P (inner))
3413 warning_at (location,
3414 OPT_Waddress,
3415 "the compiler can assume that the address of "
3416 "%qD will always evaluate to %<true%>",
3417 inner);
3420 /* Don't cancel the effect of a CONVERT_EXPR from a REFERENCE_TYPE,
3421 since that affects how `default_conversion' will behave. */
3422 if (TREE_CODE (totype) == REFERENCE_TYPE
3423 || TREE_CODE (fromtype) == REFERENCE_TYPE)
3424 break;
3425 /* Don't strip a conversion from C++0x scoped enum, since they
3426 don't implicitly convert to other types. */
3427 if (TREE_CODE (fromtype) == ENUMERAL_TYPE
3428 && ENUM_IS_SCOPED (fromtype))
3429 break;
3430 /* If this isn't narrowing the argument, we can ignore it. */
3431 if (TYPE_PRECISION (totype) >= TYPE_PRECISION (fromtype))
3432 return c_common_truthvalue_conversion (location,
3433 TREE_OPERAND (expr, 0));
3435 break;
3437 case MODIFY_EXPR:
3438 if (!TREE_NO_WARNING (expr)
3439 && warn_parentheses)
3441 warning_at (location, OPT_Wparentheses,
3442 "suggest parentheses around assignment used as "
3443 "truth value");
3444 TREE_NO_WARNING (expr) = 1;
3446 break;
3448 default:
3449 break;
3452 if (TREE_CODE (TREE_TYPE (expr)) == COMPLEX_TYPE)
3454 tree t = save_expr (expr);
3455 expr = (build_binary_op
3456 (EXPR_LOCATION (expr),
3457 (TREE_SIDE_EFFECTS (expr)
3458 ? TRUTH_OR_EXPR : TRUTH_ORIF_EXPR),
3459 c_common_truthvalue_conversion
3460 (location,
3461 build_unary_op (location, REALPART_EXPR, t, false)),
3462 c_common_truthvalue_conversion
3463 (location,
3464 build_unary_op (location, IMAGPART_EXPR, t, false)),
3465 false));
3466 goto ret;
3469 if (TREE_CODE (TREE_TYPE (expr)) == FIXED_POINT_TYPE)
3471 tree fixed_zero_node = build_fixed (TREE_TYPE (expr),
3472 FCONST0 (TYPE_MODE
3473 (TREE_TYPE (expr))));
3474 return build_binary_op (location, NE_EXPR, expr, fixed_zero_node, true);
3476 else
3477 return build_binary_op (location, NE_EXPR, expr, integer_zero_node, true);
3479 ret:
3480 protected_set_expr_location (expr, location);
3481 return expr;
3484 static void def_builtin_1 (enum built_in_function fncode,
3485 const char *name,
3486 enum built_in_class fnclass,
3487 tree fntype, tree libtype,
3488 bool both_p, bool fallback_p, bool nonansi_p,
3489 tree fnattrs, bool implicit_p);
3492 /* Apply the TYPE_QUALS to the new DECL. */
3494 void
3495 c_apply_type_quals_to_decl (int type_quals, tree decl)
3497 tree type = TREE_TYPE (decl);
3499 if (type == error_mark_node)
3500 return;
3502 if ((type_quals & TYPE_QUAL_CONST)
3503 || (type && TREE_CODE (type) == REFERENCE_TYPE))
3504 /* We used to check TYPE_NEEDS_CONSTRUCTING here, but now a constexpr
3505 constructor can produce constant init, so rely on cp_finish_decl to
3506 clear TREE_READONLY if the variable has non-constant init. */
3507 TREE_READONLY (decl) = 1;
3508 if (type_quals & TYPE_QUAL_VOLATILE)
3510 TREE_SIDE_EFFECTS (decl) = 1;
3511 TREE_THIS_VOLATILE (decl) = 1;
3513 if (type_quals & TYPE_QUAL_RESTRICT)
3515 while (type && TREE_CODE (type) == ARRAY_TYPE)
3516 /* Allow 'restrict' on arrays of pointers.
3517 FIXME currently we just ignore it. */
3518 type = TREE_TYPE (type);
3519 if (!type
3520 || !POINTER_TYPE_P (type)
3521 || !C_TYPE_OBJECT_OR_INCOMPLETE_P (TREE_TYPE (type)))
3522 error ("invalid use of %<restrict%>");
3526 /* Return the typed-based alias set for T, which may be an expression
3527 or a type. Return -1 if we don't do anything special. */
3529 alias_set_type
3530 c_common_get_alias_set (tree t)
3532 /* For VLAs, use the alias set of the element type rather than the
3533 default of alias set 0 for types compared structurally. */
3534 if (TYPE_P (t) && TYPE_STRUCTURAL_EQUALITY_P (t))
3536 if (TREE_CODE (t) == ARRAY_TYPE)
3537 return get_alias_set (TREE_TYPE (t));
3538 return -1;
3541 /* That's all the expressions we handle specially. */
3542 if (!TYPE_P (t))
3543 return -1;
3545 /* The C standard guarantees that any object may be accessed via an
3546 lvalue that has character type. */
3547 if (t == char_type_node
3548 || t == signed_char_type_node
3549 || t == unsigned_char_type_node)
3550 return 0;
3552 /* The C standard specifically allows aliasing between signed and
3553 unsigned variants of the same type. We treat the signed
3554 variant as canonical. */
3555 if (TREE_CODE (t) == INTEGER_TYPE && TYPE_UNSIGNED (t))
3557 tree t1 = c_common_signed_type (t);
3559 /* t1 == t can happen for boolean nodes which are always unsigned. */
3560 if (t1 != t)
3561 return get_alias_set (t1);
3564 return -1;
3567 /* Compute the value of 'sizeof (TYPE)' or '__alignof__ (TYPE)', where
3568 the IS_SIZEOF parameter indicates which operator is being applied.
3569 The COMPLAIN flag controls whether we should diagnose possibly
3570 ill-formed constructs or not. LOC is the location of the SIZEOF or
3571 TYPEOF operator. If MIN_ALIGNOF, the least alignment required for
3572 a type in any context should be returned, rather than the normal
3573 alignment for that type. */
3575 tree
3576 c_sizeof_or_alignof_type (location_t loc,
3577 tree type, bool is_sizeof, bool min_alignof,
3578 int complain)
3580 const char *op_name;
3581 tree value = NULL;
3582 enum tree_code type_code = TREE_CODE (type);
3584 op_name = is_sizeof ? "sizeof" : "__alignof__";
3586 if (type_code == FUNCTION_TYPE)
3588 if (is_sizeof)
3590 if (complain && warn_pointer_arith)
3591 pedwarn (loc, OPT_Wpointer_arith,
3592 "invalid application of %<sizeof%> to a function type");
3593 else if (!complain)
3594 return error_mark_node;
3595 value = size_one_node;
3597 else
3599 if (complain)
3601 if (c_dialect_cxx ())
3602 pedwarn (loc, OPT_Wpedantic, "ISO C++ does not permit "
3603 "%<alignof%> applied to a function type");
3604 else
3605 pedwarn (loc, OPT_Wpedantic, "ISO C does not permit "
3606 "%<_Alignof%> applied to a function type");
3608 value = size_int (FUNCTION_BOUNDARY / BITS_PER_UNIT);
3611 else if (type_code == VOID_TYPE || type_code == ERROR_MARK)
3613 if (type_code == VOID_TYPE
3614 && complain && warn_pointer_arith)
3615 pedwarn (loc, OPT_Wpointer_arith,
3616 "invalid application of %qs to a void type", op_name);
3617 else if (!complain)
3618 return error_mark_node;
3619 value = size_one_node;
3621 else if (!COMPLETE_TYPE_P (type)
3622 && (!c_dialect_cxx () || is_sizeof || type_code != ARRAY_TYPE))
3624 if (complain)
3625 error_at (loc, "invalid application of %qs to incomplete type %qT",
3626 op_name, type);
3627 return error_mark_node;
3629 else if (c_dialect_cxx () && type_code == ARRAY_TYPE
3630 && !COMPLETE_TYPE_P (TREE_TYPE (type)))
3632 if (complain)
3633 error_at (loc, "invalid application of %qs to array type %qT of "
3634 "incomplete element type", op_name, type);
3635 return error_mark_node;
3637 else
3639 if (is_sizeof)
3640 /* Convert in case a char is more than one unit. */
3641 value = size_binop_loc (loc, CEIL_DIV_EXPR, TYPE_SIZE_UNIT (type),
3642 size_int (TYPE_PRECISION (char_type_node)
3643 / BITS_PER_UNIT));
3644 else if (min_alignof)
3645 value = size_int (min_align_of_type (type));
3646 else
3647 value = size_int (TYPE_ALIGN_UNIT (type));
3650 /* VALUE will have the middle-end integer type sizetype.
3651 However, we should really return a value of type `size_t',
3652 which is just a typedef for an ordinary integer type. */
3653 value = fold_convert_loc (loc, size_type_node, value);
3655 return value;
3658 /* Implement the __alignof keyword: Return the minimum required
3659 alignment of EXPR, measured in bytes. For VAR_DECLs,
3660 FUNCTION_DECLs and FIELD_DECLs return DECL_ALIGN (which can be set
3661 from an "aligned" __attribute__ specification). LOC is the
3662 location of the ALIGNOF operator. */
3664 tree
3665 c_alignof_expr (location_t loc, tree expr)
3667 tree t;
3669 if (VAR_OR_FUNCTION_DECL_P (expr))
3670 t = size_int (DECL_ALIGN_UNIT (expr));
3672 else if (TREE_CODE (expr) == COMPONENT_REF
3673 && DECL_C_BIT_FIELD (TREE_OPERAND (expr, 1)))
3675 error_at (loc, "%<__alignof%> applied to a bit-field");
3676 t = size_one_node;
3678 else if (TREE_CODE (expr) == COMPONENT_REF
3679 && TREE_CODE (TREE_OPERAND (expr, 1)) == FIELD_DECL)
3680 t = size_int (DECL_ALIGN_UNIT (TREE_OPERAND (expr, 1)));
3682 else if (INDIRECT_REF_P (expr))
3684 tree t = TREE_OPERAND (expr, 0);
3685 tree best = t;
3686 int bestalign = TYPE_ALIGN (TREE_TYPE (TREE_TYPE (t)));
3688 while (CONVERT_EXPR_P (t)
3689 && TREE_CODE (TREE_TYPE (TREE_OPERAND (t, 0))) == POINTER_TYPE)
3691 int thisalign;
3693 t = TREE_OPERAND (t, 0);
3694 thisalign = TYPE_ALIGN (TREE_TYPE (TREE_TYPE (t)));
3695 if (thisalign > bestalign)
3696 best = t, bestalign = thisalign;
3698 return c_alignof (loc, TREE_TYPE (TREE_TYPE (best)));
3700 else
3701 return c_alignof (loc, TREE_TYPE (expr));
3703 return fold_convert_loc (loc, size_type_node, t);
3706 /* Handle C and C++ default attributes. */
3708 enum built_in_attribute
3710 #define DEF_ATTR_NULL_TREE(ENUM) ENUM,
3711 #define DEF_ATTR_INT(ENUM, VALUE) ENUM,
3712 #define DEF_ATTR_STRING(ENUM, VALUE) ENUM,
3713 #define DEF_ATTR_IDENT(ENUM, STRING) ENUM,
3714 #define DEF_ATTR_TREE_LIST(ENUM, PURPOSE, VALUE, CHAIN) ENUM,
3715 #include "builtin-attrs.def"
3716 #undef DEF_ATTR_NULL_TREE
3717 #undef DEF_ATTR_INT
3718 #undef DEF_ATTR_STRING
3719 #undef DEF_ATTR_IDENT
3720 #undef DEF_ATTR_TREE_LIST
3721 ATTR_LAST
3724 static GTY(()) tree built_in_attributes[(int) ATTR_LAST];
3726 static void c_init_attributes (void);
3728 enum c_builtin_type
3730 #define DEF_PRIMITIVE_TYPE(NAME, VALUE) NAME,
3731 #define DEF_FUNCTION_TYPE_0(NAME, RETURN) NAME,
3732 #define DEF_FUNCTION_TYPE_1(NAME, RETURN, ARG1) NAME,
3733 #define DEF_FUNCTION_TYPE_2(NAME, RETURN, ARG1, ARG2) NAME,
3734 #define DEF_FUNCTION_TYPE_3(NAME, RETURN, ARG1, ARG2, ARG3) NAME,
3735 #define DEF_FUNCTION_TYPE_4(NAME, RETURN, ARG1, ARG2, ARG3, ARG4) NAME,
3736 #define DEF_FUNCTION_TYPE_5(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5) NAME,
3737 #define DEF_FUNCTION_TYPE_6(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3738 ARG6) NAME,
3739 #define DEF_FUNCTION_TYPE_7(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3740 ARG6, ARG7) NAME,
3741 #define DEF_FUNCTION_TYPE_8(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3742 ARG6, ARG7, ARG8) NAME,
3743 #define DEF_FUNCTION_TYPE_9(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3744 ARG6, ARG7, ARG8, ARG9) NAME,
3745 #define DEF_FUNCTION_TYPE_10(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3746 ARG6, ARG7, ARG8, ARG9, ARG10) NAME,
3747 #define DEF_FUNCTION_TYPE_11(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3748 ARG6, ARG7, ARG8, ARG9, ARG10, ARG11) NAME,
3749 #define DEF_FUNCTION_TYPE_VAR_0(NAME, RETURN) NAME,
3750 #define DEF_FUNCTION_TYPE_VAR_1(NAME, RETURN, ARG1) NAME,
3751 #define DEF_FUNCTION_TYPE_VAR_2(NAME, RETURN, ARG1, ARG2) NAME,
3752 #define DEF_FUNCTION_TYPE_VAR_3(NAME, RETURN, ARG1, ARG2, ARG3) NAME,
3753 #define DEF_FUNCTION_TYPE_VAR_4(NAME, RETURN, ARG1, ARG2, ARG3, ARG4) NAME,
3754 #define DEF_FUNCTION_TYPE_VAR_5(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5) \
3755 NAME,
3756 #define DEF_FUNCTION_TYPE_VAR_6(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3757 ARG6) NAME,
3758 #define DEF_FUNCTION_TYPE_VAR_7(NAME, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3759 ARG6, ARG7) NAME,
3760 #define DEF_POINTER_TYPE(NAME, TYPE) NAME,
3761 #include "builtin-types.def"
3762 #undef DEF_PRIMITIVE_TYPE
3763 #undef DEF_FUNCTION_TYPE_0
3764 #undef DEF_FUNCTION_TYPE_1
3765 #undef DEF_FUNCTION_TYPE_2
3766 #undef DEF_FUNCTION_TYPE_3
3767 #undef DEF_FUNCTION_TYPE_4
3768 #undef DEF_FUNCTION_TYPE_5
3769 #undef DEF_FUNCTION_TYPE_6
3770 #undef DEF_FUNCTION_TYPE_7
3771 #undef DEF_FUNCTION_TYPE_8
3772 #undef DEF_FUNCTION_TYPE_9
3773 #undef DEF_FUNCTION_TYPE_10
3774 #undef DEF_FUNCTION_TYPE_11
3775 #undef DEF_FUNCTION_TYPE_VAR_0
3776 #undef DEF_FUNCTION_TYPE_VAR_1
3777 #undef DEF_FUNCTION_TYPE_VAR_2
3778 #undef DEF_FUNCTION_TYPE_VAR_3
3779 #undef DEF_FUNCTION_TYPE_VAR_4
3780 #undef DEF_FUNCTION_TYPE_VAR_5
3781 #undef DEF_FUNCTION_TYPE_VAR_6
3782 #undef DEF_FUNCTION_TYPE_VAR_7
3783 #undef DEF_POINTER_TYPE
3784 BT_LAST
3787 typedef enum c_builtin_type builtin_type;
3789 /* A temporary array for c_common_nodes_and_builtins. Used in
3790 communication with def_fn_type. */
3791 static tree builtin_types[(int) BT_LAST + 1];
3793 /* A helper function for c_common_nodes_and_builtins. Build function type
3794 for DEF with return type RET and N arguments. If VAR is true, then the
3795 function should be variadic after those N arguments.
3797 Takes special care not to ICE if any of the types involved are
3798 error_mark_node, which indicates that said type is not in fact available
3799 (see builtin_type_for_size). In which case the function type as a whole
3800 should be error_mark_node. */
3802 static void
3803 def_fn_type (builtin_type def, builtin_type ret, bool var, int n, ...)
3805 tree t;
3806 tree *args = XALLOCAVEC (tree, n);
3807 va_list list;
3808 int i;
3810 va_start (list, n);
3811 for (i = 0; i < n; ++i)
3813 builtin_type a = (builtin_type) va_arg (list, int);
3814 t = builtin_types[a];
3815 if (t == error_mark_node)
3816 goto egress;
3817 args[i] = t;
3820 t = builtin_types[ret];
3821 if (t == error_mark_node)
3822 goto egress;
3823 if (var)
3824 t = build_varargs_function_type_array (t, n, args);
3825 else
3826 t = build_function_type_array (t, n, args);
3828 egress:
3829 builtin_types[def] = t;
3830 va_end (list);
3833 /* Build builtin functions common to both C and C++ language
3834 frontends. */
3836 static void
3837 c_define_builtins (tree va_list_ref_type_node, tree va_list_arg_type_node)
3839 #define DEF_PRIMITIVE_TYPE(ENUM, VALUE) \
3840 builtin_types[ENUM] = VALUE;
3841 #define DEF_FUNCTION_TYPE_0(ENUM, RETURN) \
3842 def_fn_type (ENUM, RETURN, 0, 0);
3843 #define DEF_FUNCTION_TYPE_1(ENUM, RETURN, ARG1) \
3844 def_fn_type (ENUM, RETURN, 0, 1, ARG1);
3845 #define DEF_FUNCTION_TYPE_2(ENUM, RETURN, ARG1, ARG2) \
3846 def_fn_type (ENUM, RETURN, 0, 2, ARG1, ARG2);
3847 #define DEF_FUNCTION_TYPE_3(ENUM, RETURN, ARG1, ARG2, ARG3) \
3848 def_fn_type (ENUM, RETURN, 0, 3, ARG1, ARG2, ARG3);
3849 #define DEF_FUNCTION_TYPE_4(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4) \
3850 def_fn_type (ENUM, RETURN, 0, 4, ARG1, ARG2, ARG3, ARG4);
3851 #define DEF_FUNCTION_TYPE_5(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5) \
3852 def_fn_type (ENUM, RETURN, 0, 5, ARG1, ARG2, ARG3, ARG4, ARG5);
3853 #define DEF_FUNCTION_TYPE_6(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3854 ARG6) \
3855 def_fn_type (ENUM, RETURN, 0, 6, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6);
3856 #define DEF_FUNCTION_TYPE_7(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3857 ARG6, ARG7) \
3858 def_fn_type (ENUM, RETURN, 0, 7, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, ARG7);
3859 #define DEF_FUNCTION_TYPE_8(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3860 ARG6, ARG7, ARG8) \
3861 def_fn_type (ENUM, RETURN, 0, 8, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, \
3862 ARG7, ARG8);
3863 #define DEF_FUNCTION_TYPE_9(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3864 ARG6, ARG7, ARG8, ARG9) \
3865 def_fn_type (ENUM, RETURN, 0, 9, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, \
3866 ARG7, ARG8, ARG9);
3867 #define DEF_FUNCTION_TYPE_10(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3868 ARG6, ARG7, ARG8, ARG9, ARG10) \
3869 def_fn_type (ENUM, RETURN, 0, 10, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, \
3870 ARG7, ARG8, ARG9, ARG10);
3871 #define DEF_FUNCTION_TYPE_11(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3872 ARG6, ARG7, ARG8, ARG9, ARG10, ARG11) \
3873 def_fn_type (ENUM, RETURN, 0, 11, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, \
3874 ARG7, ARG8, ARG9, ARG10, ARG11);
3875 #define DEF_FUNCTION_TYPE_VAR_0(ENUM, RETURN) \
3876 def_fn_type (ENUM, RETURN, 1, 0);
3877 #define DEF_FUNCTION_TYPE_VAR_1(ENUM, RETURN, ARG1) \
3878 def_fn_type (ENUM, RETURN, 1, 1, ARG1);
3879 #define DEF_FUNCTION_TYPE_VAR_2(ENUM, RETURN, ARG1, ARG2) \
3880 def_fn_type (ENUM, RETURN, 1, 2, ARG1, ARG2);
3881 #define DEF_FUNCTION_TYPE_VAR_3(ENUM, RETURN, ARG1, ARG2, ARG3) \
3882 def_fn_type (ENUM, RETURN, 1, 3, ARG1, ARG2, ARG3);
3883 #define DEF_FUNCTION_TYPE_VAR_4(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4) \
3884 def_fn_type (ENUM, RETURN, 1, 4, ARG1, ARG2, ARG3, ARG4);
3885 #define DEF_FUNCTION_TYPE_VAR_5(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5) \
3886 def_fn_type (ENUM, RETURN, 1, 5, ARG1, ARG2, ARG3, ARG4, ARG5);
3887 #define DEF_FUNCTION_TYPE_VAR_6(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3888 ARG6) \
3889 def_fn_type (ENUM, RETURN, 1, 6, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6);
3890 #define DEF_FUNCTION_TYPE_VAR_7(ENUM, RETURN, ARG1, ARG2, ARG3, ARG4, ARG5, \
3891 ARG6, ARG7) \
3892 def_fn_type (ENUM, RETURN, 1, 7, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6, ARG7);
3893 #define DEF_POINTER_TYPE(ENUM, TYPE) \
3894 builtin_types[(int) ENUM] = build_pointer_type (builtin_types[(int) TYPE]);
3896 #include "builtin-types.def"
3898 #undef DEF_PRIMITIVE_TYPE
3899 #undef DEF_FUNCTION_TYPE_0
3900 #undef DEF_FUNCTION_TYPE_1
3901 #undef DEF_FUNCTION_TYPE_2
3902 #undef DEF_FUNCTION_TYPE_3
3903 #undef DEF_FUNCTION_TYPE_4
3904 #undef DEF_FUNCTION_TYPE_5
3905 #undef DEF_FUNCTION_TYPE_6
3906 #undef DEF_FUNCTION_TYPE_7
3907 #undef DEF_FUNCTION_TYPE_8
3908 #undef DEF_FUNCTION_TYPE_9
3909 #undef DEF_FUNCTION_TYPE_10
3910 #undef DEF_FUNCTION_TYPE_11
3911 #undef DEF_FUNCTION_TYPE_VAR_0
3912 #undef DEF_FUNCTION_TYPE_VAR_1
3913 #undef DEF_FUNCTION_TYPE_VAR_2
3914 #undef DEF_FUNCTION_TYPE_VAR_3
3915 #undef DEF_FUNCTION_TYPE_VAR_4
3916 #undef DEF_FUNCTION_TYPE_VAR_5
3917 #undef DEF_FUNCTION_TYPE_VAR_6
3918 #undef DEF_FUNCTION_TYPE_VAR_7
3919 #undef DEF_POINTER_TYPE
3920 builtin_types[(int) BT_LAST] = NULL_TREE;
3922 c_init_attributes ();
3924 #define DEF_BUILTIN(ENUM, NAME, CLASS, TYPE, LIBTYPE, BOTH_P, FALLBACK_P, \
3925 NONANSI_P, ATTRS, IMPLICIT, COND) \
3926 if (NAME && COND) \
3927 def_builtin_1 (ENUM, NAME, CLASS, \
3928 builtin_types[(int) TYPE], \
3929 builtin_types[(int) LIBTYPE], \
3930 BOTH_P, FALLBACK_P, NONANSI_P, \
3931 built_in_attributes[(int) ATTRS], IMPLICIT);
3932 #include "builtins.def"
3934 targetm.init_builtins ();
3936 build_common_builtin_nodes ();
3939 /* Like get_identifier, but avoid warnings about null arguments when
3940 the argument may be NULL for targets where GCC lacks stdint.h type
3941 information. */
3943 static inline tree
3944 c_get_ident (const char *id)
3946 return get_identifier (id);
3949 /* Build tree nodes and builtin functions common to both C and C++ language
3950 frontends. */
3952 void
3953 c_common_nodes_and_builtins (void)
3955 int char16_type_size;
3956 int char32_type_size;
3957 int wchar_type_size;
3958 tree array_domain_type;
3959 tree va_list_ref_type_node;
3960 tree va_list_arg_type_node;
3961 int i;
3963 build_common_tree_nodes (flag_signed_char);
3965 /* Define `int' and `char' first so that dbx will output them first. */
3966 record_builtin_type (RID_INT, NULL, integer_type_node);
3967 record_builtin_type (RID_CHAR, "char", char_type_node);
3969 /* `signed' is the same as `int'. FIXME: the declarations of "signed",
3970 "unsigned long", "long long unsigned" and "unsigned short" were in C++
3971 but not C. Are the conditionals here needed? */
3972 if (c_dialect_cxx ())
3973 record_builtin_type (RID_SIGNED, NULL, integer_type_node);
3974 record_builtin_type (RID_LONG, "long int", long_integer_type_node);
3975 record_builtin_type (RID_UNSIGNED, "unsigned int", unsigned_type_node);
3976 record_builtin_type (RID_MAX, "long unsigned int",
3977 long_unsigned_type_node);
3979 for (i = 0; i < NUM_INT_N_ENTS; i ++)
3981 char name[25];
3983 sprintf (name, "__int%d", int_n_data[i].bitsize);
3984 record_builtin_type ((enum rid)(RID_FIRST_INT_N + i), name,
3985 int_n_trees[i].signed_type);
3986 sprintf (name, "__int%d unsigned", int_n_data[i].bitsize);
3987 record_builtin_type (RID_MAX, name, int_n_trees[i].unsigned_type);
3990 if (c_dialect_cxx ())
3991 record_builtin_type (RID_MAX, "unsigned long", long_unsigned_type_node);
3992 record_builtin_type (RID_MAX, "long long int",
3993 long_long_integer_type_node);
3994 record_builtin_type (RID_MAX, "long long unsigned int",
3995 long_long_unsigned_type_node);
3996 if (c_dialect_cxx ())
3997 record_builtin_type (RID_MAX, "long long unsigned",
3998 long_long_unsigned_type_node);
3999 record_builtin_type (RID_SHORT, "short int", short_integer_type_node);
4000 record_builtin_type (RID_MAX, "short unsigned int",
4001 short_unsigned_type_node);
4002 if (c_dialect_cxx ())
4003 record_builtin_type (RID_MAX, "unsigned short",
4004 short_unsigned_type_node);
4006 /* Define both `signed char' and `unsigned char'. */
4007 record_builtin_type (RID_MAX, "signed char", signed_char_type_node);
4008 record_builtin_type (RID_MAX, "unsigned char", unsigned_char_type_node);
4010 /* These are types that c_common_type_for_size and
4011 c_common_type_for_mode use. */
4012 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4013 TYPE_DECL, NULL_TREE,
4014 intQI_type_node));
4015 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4016 TYPE_DECL, NULL_TREE,
4017 intHI_type_node));
4018 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4019 TYPE_DECL, NULL_TREE,
4020 intSI_type_node));
4021 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4022 TYPE_DECL, NULL_TREE,
4023 intDI_type_node));
4024 #if HOST_BITS_PER_WIDE_INT >= 64
4025 /* Note that this is different than the __int128 type that's part of
4026 the generic __intN support. */
4027 if (targetm.scalar_mode_supported_p (TImode))
4028 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4029 TYPE_DECL,
4030 get_identifier ("__int128_t"),
4031 intTI_type_node));
4032 #endif
4033 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4034 TYPE_DECL, NULL_TREE,
4035 unsigned_intQI_type_node));
4036 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4037 TYPE_DECL, NULL_TREE,
4038 unsigned_intHI_type_node));
4039 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4040 TYPE_DECL, NULL_TREE,
4041 unsigned_intSI_type_node));
4042 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4043 TYPE_DECL, NULL_TREE,
4044 unsigned_intDI_type_node));
4045 #if HOST_BITS_PER_WIDE_INT >= 64
4046 if (targetm.scalar_mode_supported_p (TImode))
4047 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4048 TYPE_DECL,
4049 get_identifier ("__uint128_t"),
4050 unsigned_intTI_type_node));
4051 #endif
4053 /* Create the widest literal types. */
4054 if (targetm.scalar_mode_supported_p (TImode))
4056 widest_integer_literal_type_node = intTI_type_node;
4057 widest_unsigned_literal_type_node = unsigned_intTI_type_node;
4059 else
4061 widest_integer_literal_type_node = intDI_type_node;
4062 widest_unsigned_literal_type_node = unsigned_intDI_type_node;
4065 signed_size_type_node = c_common_signed_type (size_type_node);
4067 pid_type_node =
4068 TREE_TYPE (identifier_global_value (get_identifier (PID_TYPE)));
4070 record_builtin_type (RID_FLOAT, NULL, float_type_node);
4071 record_builtin_type (RID_DOUBLE, NULL, double_type_node);
4072 record_builtin_type (RID_MAX, "long double", long_double_type_node);
4074 if (!c_dialect_cxx ())
4075 for (i = 0; i < NUM_FLOATN_NX_TYPES; i++)
4076 if (FLOATN_NX_TYPE_NODE (i) != NULL_TREE)
4077 record_builtin_type ((enum rid) (RID_FLOATN_NX_FIRST + i), NULL,
4078 FLOATN_NX_TYPE_NODE (i));
4080 /* Only supported decimal floating point extension if the target
4081 actually supports underlying modes. */
4082 if (targetm.scalar_mode_supported_p (SDmode)
4083 && targetm.scalar_mode_supported_p (DDmode)
4084 && targetm.scalar_mode_supported_p (TDmode))
4086 record_builtin_type (RID_DFLOAT32, NULL, dfloat32_type_node);
4087 record_builtin_type (RID_DFLOAT64, NULL, dfloat64_type_node);
4088 record_builtin_type (RID_DFLOAT128, NULL, dfloat128_type_node);
4091 if (targetm.fixed_point_supported_p ())
4093 record_builtin_type (RID_MAX, "short _Fract", short_fract_type_node);
4094 record_builtin_type (RID_FRACT, NULL, fract_type_node);
4095 record_builtin_type (RID_MAX, "long _Fract", long_fract_type_node);
4096 record_builtin_type (RID_MAX, "long long _Fract",
4097 long_long_fract_type_node);
4098 record_builtin_type (RID_MAX, "unsigned short _Fract",
4099 unsigned_short_fract_type_node);
4100 record_builtin_type (RID_MAX, "unsigned _Fract",
4101 unsigned_fract_type_node);
4102 record_builtin_type (RID_MAX, "unsigned long _Fract",
4103 unsigned_long_fract_type_node);
4104 record_builtin_type (RID_MAX, "unsigned long long _Fract",
4105 unsigned_long_long_fract_type_node);
4106 record_builtin_type (RID_MAX, "_Sat short _Fract",
4107 sat_short_fract_type_node);
4108 record_builtin_type (RID_MAX, "_Sat _Fract", sat_fract_type_node);
4109 record_builtin_type (RID_MAX, "_Sat long _Fract",
4110 sat_long_fract_type_node);
4111 record_builtin_type (RID_MAX, "_Sat long long _Fract",
4112 sat_long_long_fract_type_node);
4113 record_builtin_type (RID_MAX, "_Sat unsigned short _Fract",
4114 sat_unsigned_short_fract_type_node);
4115 record_builtin_type (RID_MAX, "_Sat unsigned _Fract",
4116 sat_unsigned_fract_type_node);
4117 record_builtin_type (RID_MAX, "_Sat unsigned long _Fract",
4118 sat_unsigned_long_fract_type_node);
4119 record_builtin_type (RID_MAX, "_Sat unsigned long long _Fract",
4120 sat_unsigned_long_long_fract_type_node);
4121 record_builtin_type (RID_MAX, "short _Accum", short_accum_type_node);
4122 record_builtin_type (RID_ACCUM, NULL, accum_type_node);
4123 record_builtin_type (RID_MAX, "long _Accum", long_accum_type_node);
4124 record_builtin_type (RID_MAX, "long long _Accum",
4125 long_long_accum_type_node);
4126 record_builtin_type (RID_MAX, "unsigned short _Accum",
4127 unsigned_short_accum_type_node);
4128 record_builtin_type (RID_MAX, "unsigned _Accum",
4129 unsigned_accum_type_node);
4130 record_builtin_type (RID_MAX, "unsigned long _Accum",
4131 unsigned_long_accum_type_node);
4132 record_builtin_type (RID_MAX, "unsigned long long _Accum",
4133 unsigned_long_long_accum_type_node);
4134 record_builtin_type (RID_MAX, "_Sat short _Accum",
4135 sat_short_accum_type_node);
4136 record_builtin_type (RID_MAX, "_Sat _Accum", sat_accum_type_node);
4137 record_builtin_type (RID_MAX, "_Sat long _Accum",
4138 sat_long_accum_type_node);
4139 record_builtin_type (RID_MAX, "_Sat long long _Accum",
4140 sat_long_long_accum_type_node);
4141 record_builtin_type (RID_MAX, "_Sat unsigned short _Accum",
4142 sat_unsigned_short_accum_type_node);
4143 record_builtin_type (RID_MAX, "_Sat unsigned _Accum",
4144 sat_unsigned_accum_type_node);
4145 record_builtin_type (RID_MAX, "_Sat unsigned long _Accum",
4146 sat_unsigned_long_accum_type_node);
4147 record_builtin_type (RID_MAX, "_Sat unsigned long long _Accum",
4148 sat_unsigned_long_long_accum_type_node);
4152 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4153 TYPE_DECL,
4154 get_identifier ("complex int"),
4155 complex_integer_type_node));
4156 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4157 TYPE_DECL,
4158 get_identifier ("complex float"),
4159 complex_float_type_node));
4160 lang_hooks.decls.pushdecl (build_decl (UNKNOWN_LOCATION,
4161 TYPE_DECL,
4162 get_identifier ("complex double"),
4163 complex_double_type_node));
4164 lang_hooks.decls.pushdecl
4165 (build_decl (UNKNOWN_LOCATION,
4166 TYPE_DECL, get_identifier ("complex long double"),
4167 complex_long_double_type_node));
4169 if (!c_dialect_cxx ())
4170 for (i = 0; i < NUM_FLOATN_NX_TYPES; i++)
4171 if (COMPLEX_FLOATN_NX_TYPE_NODE (i) != NULL_TREE)
4173 char buf[30];
4174 sprintf (buf, "complex _Float%d%s", floatn_nx_types[i].n,
4175 floatn_nx_types[i].extended ? "x" : "");
4176 lang_hooks.decls.pushdecl
4177 (build_decl (UNKNOWN_LOCATION,
4178 TYPE_DECL,
4179 get_identifier (buf),
4180 COMPLEX_FLOATN_NX_TYPE_NODE (i)));
4183 if (c_dialect_cxx ())
4185 /* For C++, make fileptr_type_node a distinct void * type until
4186 FILE type is defined. Likewise for const struct tm*. */
4187 for (unsigned i = 0;
4188 i < sizeof (builtin_structptr_types)
4189 / sizeof (builtin_structptr_type);
4190 ++i)
4191 builtin_structptr_types[i].node =
4192 build_variant_type_copy (builtin_structptr_types[i].base);
4196 record_builtin_type (RID_VOID, NULL, void_type_node);
4198 /* Set the TYPE_NAME for any variants that were built before
4199 record_builtin_type gave names to the built-in types. */
4201 tree void_name = TYPE_NAME (void_type_node);
4202 TYPE_NAME (void_type_node) = NULL_TREE;
4203 TYPE_NAME (build_qualified_type (void_type_node, TYPE_QUAL_CONST))
4204 = void_name;
4205 TYPE_NAME (void_type_node) = void_name;
4208 void_list_node = build_void_list_node ();
4210 /* Make a type to be the domain of a few array types
4211 whose domains don't really matter.
4212 200 is small enough that it always fits in size_t
4213 and large enough that it can hold most function names for the
4214 initializations of __FUNCTION__ and __PRETTY_FUNCTION__. */
4215 array_domain_type = build_index_type (size_int (200));
4217 /* Make a type for arrays of characters.
4218 With luck nothing will ever really depend on the length of this
4219 array type. */
4220 char_array_type_node
4221 = build_array_type (char_type_node, array_domain_type);
4223 string_type_node = build_pointer_type (char_type_node);
4224 const_string_type_node
4225 = build_pointer_type (build_qualified_type
4226 (char_type_node, TYPE_QUAL_CONST));
4228 /* This is special for C++ so functions can be overloaded. */
4229 wchar_type_node = get_identifier (MODIFIED_WCHAR_TYPE);
4230 wchar_type_node = TREE_TYPE (identifier_global_value (wchar_type_node));
4231 wchar_type_size = TYPE_PRECISION (wchar_type_node);
4232 underlying_wchar_type_node = wchar_type_node;
4233 if (c_dialect_cxx ())
4235 if (TYPE_UNSIGNED (wchar_type_node))
4236 wchar_type_node = make_unsigned_type (wchar_type_size);
4237 else
4238 wchar_type_node = make_signed_type (wchar_type_size);
4239 record_builtin_type (RID_WCHAR, "wchar_t", wchar_type_node);
4242 /* This is for wide string constants. */
4243 wchar_array_type_node
4244 = build_array_type (wchar_type_node, array_domain_type);
4246 /* Define 'char16_t'. */
4247 char16_type_node = get_identifier (CHAR16_TYPE);
4248 char16_type_node = TREE_TYPE (identifier_global_value (char16_type_node));
4249 char16_type_size = TYPE_PRECISION (char16_type_node);
4250 if (c_dialect_cxx ())
4252 char16_type_node = make_unsigned_type (char16_type_size);
4254 if (cxx_dialect >= cxx11)
4255 record_builtin_type (RID_CHAR16, "char16_t", char16_type_node);
4258 /* This is for UTF-16 string constants. */
4259 char16_array_type_node
4260 = build_array_type (char16_type_node, array_domain_type);
4262 /* Define 'char32_t'. */
4263 char32_type_node = get_identifier (CHAR32_TYPE);
4264 char32_type_node = TREE_TYPE (identifier_global_value (char32_type_node));
4265 char32_type_size = TYPE_PRECISION (char32_type_node);
4266 if (c_dialect_cxx ())
4268 char32_type_node = make_unsigned_type (char32_type_size);
4270 if (cxx_dialect >= cxx11)
4271 record_builtin_type (RID_CHAR32, "char32_t", char32_type_node);
4274 /* This is for UTF-32 string constants. */
4275 char32_array_type_node
4276 = build_array_type (char32_type_node, array_domain_type);
4278 wint_type_node =
4279 TREE_TYPE (identifier_global_value (get_identifier (WINT_TYPE)));
4281 intmax_type_node =
4282 TREE_TYPE (identifier_global_value (get_identifier (INTMAX_TYPE)));
4283 uintmax_type_node =
4284 TREE_TYPE (identifier_global_value (get_identifier (UINTMAX_TYPE)));
4286 if (SIG_ATOMIC_TYPE)
4287 sig_atomic_type_node =
4288 TREE_TYPE (identifier_global_value (c_get_ident (SIG_ATOMIC_TYPE)));
4289 if (INT8_TYPE)
4290 int8_type_node =
4291 TREE_TYPE (identifier_global_value (c_get_ident (INT8_TYPE)));
4292 if (INT16_TYPE)
4293 int16_type_node =
4294 TREE_TYPE (identifier_global_value (c_get_ident (INT16_TYPE)));
4295 if (INT32_TYPE)
4296 int32_type_node =
4297 TREE_TYPE (identifier_global_value (c_get_ident (INT32_TYPE)));
4298 if (INT64_TYPE)
4299 int64_type_node =
4300 TREE_TYPE (identifier_global_value (c_get_ident (INT64_TYPE)));
4301 if (UINT8_TYPE)
4302 uint8_type_node =
4303 TREE_TYPE (identifier_global_value (c_get_ident (UINT8_TYPE)));
4304 if (UINT16_TYPE)
4305 c_uint16_type_node = uint16_type_node =
4306 TREE_TYPE (identifier_global_value (c_get_ident (UINT16_TYPE)));
4307 if (UINT32_TYPE)
4308 c_uint32_type_node = uint32_type_node =
4309 TREE_TYPE (identifier_global_value (c_get_ident (UINT32_TYPE)));
4310 if (UINT64_TYPE)
4311 c_uint64_type_node = uint64_type_node =
4312 TREE_TYPE (identifier_global_value (c_get_ident (UINT64_TYPE)));
4313 if (INT_LEAST8_TYPE)
4314 int_least8_type_node =
4315 TREE_TYPE (identifier_global_value (c_get_ident (INT_LEAST8_TYPE)));
4316 if (INT_LEAST16_TYPE)
4317 int_least16_type_node =
4318 TREE_TYPE (identifier_global_value (c_get_ident (INT_LEAST16_TYPE)));
4319 if (INT_LEAST32_TYPE)
4320 int_least32_type_node =
4321 TREE_TYPE (identifier_global_value (c_get_ident (INT_LEAST32_TYPE)));
4322 if (INT_LEAST64_TYPE)
4323 int_least64_type_node =
4324 TREE_TYPE (identifier_global_value (c_get_ident (INT_LEAST64_TYPE)));
4325 if (UINT_LEAST8_TYPE)
4326 uint_least8_type_node =
4327 TREE_TYPE (identifier_global_value (c_get_ident (UINT_LEAST8_TYPE)));
4328 if (UINT_LEAST16_TYPE)
4329 uint_least16_type_node =
4330 TREE_TYPE (identifier_global_value (c_get_ident (UINT_LEAST16_TYPE)));
4331 if (UINT_LEAST32_TYPE)
4332 uint_least32_type_node =
4333 TREE_TYPE (identifier_global_value (c_get_ident (UINT_LEAST32_TYPE)));
4334 if (UINT_LEAST64_TYPE)
4335 uint_least64_type_node =
4336 TREE_TYPE (identifier_global_value (c_get_ident (UINT_LEAST64_TYPE)));
4337 if (INT_FAST8_TYPE)
4338 int_fast8_type_node =
4339 TREE_TYPE (identifier_global_value (c_get_ident (INT_FAST8_TYPE)));
4340 if (INT_FAST16_TYPE)
4341 int_fast16_type_node =
4342 TREE_TYPE (identifier_global_value (c_get_ident (INT_FAST16_TYPE)));
4343 if (INT_FAST32_TYPE)
4344 int_fast32_type_node =
4345 TREE_TYPE (identifier_global_value (c_get_ident (INT_FAST32_TYPE)));
4346 if (INT_FAST64_TYPE)
4347 int_fast64_type_node =
4348 TREE_TYPE (identifier_global_value (c_get_ident (INT_FAST64_TYPE)));
4349 if (UINT_FAST8_TYPE)
4350 uint_fast8_type_node =
4351 TREE_TYPE (identifier_global_value (c_get_ident (UINT_FAST8_TYPE)));
4352 if (UINT_FAST16_TYPE)
4353 uint_fast16_type_node =
4354 TREE_TYPE (identifier_global_value (c_get_ident (UINT_FAST16_TYPE)));
4355 if (UINT_FAST32_TYPE)
4356 uint_fast32_type_node =
4357 TREE_TYPE (identifier_global_value (c_get_ident (UINT_FAST32_TYPE)));
4358 if (UINT_FAST64_TYPE)
4359 uint_fast64_type_node =
4360 TREE_TYPE (identifier_global_value (c_get_ident (UINT_FAST64_TYPE)));
4361 if (INTPTR_TYPE)
4362 intptr_type_node =
4363 TREE_TYPE (identifier_global_value (c_get_ident (INTPTR_TYPE)));
4364 if (UINTPTR_TYPE)
4365 uintptr_type_node =
4366 TREE_TYPE (identifier_global_value (c_get_ident (UINTPTR_TYPE)));
4368 default_function_type
4369 = build_varargs_function_type_list (integer_type_node, NULL_TREE);
4370 unsigned_ptrdiff_type_node = c_common_unsigned_type (ptrdiff_type_node);
4372 lang_hooks.decls.pushdecl
4373 (build_decl (UNKNOWN_LOCATION,
4374 TYPE_DECL, get_identifier ("__builtin_va_list"),
4375 va_list_type_node));
4376 if (targetm.enum_va_list_p)
4378 int l;
4379 const char *pname;
4380 tree ptype;
4382 for (l = 0; targetm.enum_va_list_p (l, &pname, &ptype); ++l)
4384 lang_hooks.decls.pushdecl
4385 (build_decl (UNKNOWN_LOCATION,
4386 TYPE_DECL, get_identifier (pname),
4387 ptype));
4392 if (TREE_CODE (va_list_type_node) == ARRAY_TYPE)
4394 va_list_arg_type_node = va_list_ref_type_node =
4395 build_pointer_type (TREE_TYPE (va_list_type_node));
4397 else
4399 va_list_arg_type_node = va_list_type_node;
4400 va_list_ref_type_node = build_reference_type (va_list_type_node);
4403 if (!flag_preprocess_only)
4404 c_define_builtins (va_list_ref_type_node, va_list_arg_type_node);
4406 main_identifier_node = get_identifier ("main");
4408 /* Create the built-in __null node. It is important that this is
4409 not shared. */
4410 null_node = make_int_cst (1, 1);
4411 TREE_TYPE (null_node) = c_common_type_for_size (POINTER_SIZE, 0);
4413 /* Since builtin_types isn't gc'ed, don't export these nodes. */
4414 memset (builtin_types, 0, sizeof (builtin_types));
4417 /* The number of named compound-literals generated thus far. */
4418 static GTY(()) int compound_literal_number;
4420 /* Set DECL_NAME for DECL, a VAR_DECL for a compound-literal. */
4422 void
4423 set_compound_literal_name (tree decl)
4425 char *name;
4426 ASM_FORMAT_PRIVATE_NAME (name, "__compound_literal",
4427 compound_literal_number);
4428 compound_literal_number++;
4429 DECL_NAME (decl) = get_identifier (name);
4432 /* build_va_arg helper function. Return a VA_ARG_EXPR with location LOC, type
4433 TYPE and operand OP. */
4435 static tree
4436 build_va_arg_1 (location_t loc, tree type, tree op)
4438 tree expr = build1 (VA_ARG_EXPR, type, op);
4439 SET_EXPR_LOCATION (expr, loc);
4440 return expr;
4443 /* Return a VA_ARG_EXPR corresponding to a source-level expression
4444 va_arg (EXPR, TYPE) at source location LOC. */
4446 tree
4447 build_va_arg (location_t loc, tree expr, tree type)
4449 tree va_type = TREE_TYPE (expr);
4450 tree canon_va_type = (va_type == error_mark_node
4451 ? error_mark_node
4452 : targetm.canonical_va_list_type (va_type));
4454 if (va_type == error_mark_node
4455 || canon_va_type == NULL_TREE)
4457 if (canon_va_type == NULL_TREE)
4458 error_at (loc, "first argument to %<va_arg%> not of type %<va_list%>");
4460 /* Let's handle things neutrallly, if expr:
4461 - has undeclared type, or
4462 - is not an va_list type. */
4463 return build_va_arg_1 (loc, type, error_mark_node);
4466 if (TREE_CODE (canon_va_type) != ARRAY_TYPE)
4468 /* Case 1: Not an array type. */
4470 /* Take the address, to get '&ap'. Note that &ap is not a va_list
4471 type. */
4472 mark_addressable (expr);
4473 expr = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (expr)), expr);
4475 return build_va_arg_1 (loc, type, expr);
4478 /* Case 2: Array type.
4480 Background:
4482 For contrast, let's start with the simple case (case 1). If
4483 canon_va_type is not an array type, but say a char *, then when
4484 passing-by-value a va_list, the type of the va_list param decl is
4485 the same as for another va_list decl (all ap's are char *):
4487 f2_1 (char * ap)
4488 D.1815 = VA_ARG (&ap, 0B, 1);
4489 return D.1815;
4491 f2 (int i)
4492 char * ap.0;
4493 char * ap;
4494 __builtin_va_start (&ap, 0);
4495 ap.0 = ap;
4496 res = f2_1 (ap.0);
4497 __builtin_va_end (&ap);
4498 D.1812 = res;
4499 return D.1812;
4501 However, if canon_va_type is ARRAY_TYPE, then when passing-by-value a
4502 va_list the type of the va_list param decl (case 2b, struct * ap) is not
4503 the same as for another va_list decl (case 2a, struct ap[1]).
4505 f2_1 (struct * ap)
4506 D.1844 = VA_ARG (ap, 0B, 0);
4507 return D.1844;
4509 f2 (int i)
4510 struct ap[1];
4511 __builtin_va_start (&ap, 0);
4512 res = f2_1 (&ap);
4513 __builtin_va_end (&ap);
4514 D.1841 = res;
4515 return D.1841;
4517 Case 2b is different because:
4518 - on the callee side, the parm decl has declared type va_list, but
4519 grokdeclarator changes the type of the parm decl to a pointer to the
4520 array elem type.
4521 - on the caller side, the pass-by-value uses &ap.
4523 We unify these two cases (case 2a: va_list is array type,
4524 case 2b: va_list is pointer to array elem type), by adding '&' for the
4525 array type case, such that we have a pointer to array elem in both
4526 cases. */
4528 if (TREE_CODE (va_type) == ARRAY_TYPE)
4530 /* Case 2a: va_list is array type. */
4532 /* Take the address, to get '&ap'. Make sure it's a pointer to array
4533 elem type. */
4534 mark_addressable (expr);
4535 expr = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (canon_va_type)),
4536 expr);
4538 /* Verify that &ap is still recognized as having va_list type. */
4539 tree canon_expr_type
4540 = targetm.canonical_va_list_type (TREE_TYPE (expr));
4541 gcc_assert (canon_expr_type != NULL_TREE);
4543 else
4545 /* Case 2b: va_list is pointer to array elem type. */
4546 gcc_assert (POINTER_TYPE_P (va_type));
4548 /* Comparison as in std_canonical_va_list_type. */
4549 gcc_assert (TYPE_MAIN_VARIANT (TREE_TYPE (va_type))
4550 == TYPE_MAIN_VARIANT (TREE_TYPE (canon_va_type)));
4552 /* Don't take the address. We've already got '&ap'. */
4556 return build_va_arg_1 (loc, type, expr);
4560 /* Linked list of disabled built-in functions. */
4562 struct disabled_builtin
4564 const char *name;
4565 struct disabled_builtin *next;
4567 static disabled_builtin *disabled_builtins = NULL;
4569 static bool builtin_function_disabled_p (const char *);
4571 /* Disable a built-in function specified by -fno-builtin-NAME. If NAME
4572 begins with "__builtin_", give an error. */
4574 void
4575 disable_builtin_function (const char *name)
4577 if (strncmp (name, "__builtin_", strlen ("__builtin_")) == 0)
4578 error ("cannot disable built-in function %qs", name);
4579 else
4581 disabled_builtin *new_disabled_builtin = XNEW (disabled_builtin);
4582 new_disabled_builtin->name = name;
4583 new_disabled_builtin->next = disabled_builtins;
4584 disabled_builtins = new_disabled_builtin;
4589 /* Return true if the built-in function NAME has been disabled, false
4590 otherwise. */
4592 static bool
4593 builtin_function_disabled_p (const char *name)
4595 disabled_builtin *p;
4596 for (p = disabled_builtins; p != NULL; p = p->next)
4598 if (strcmp (name, p->name) == 0)
4599 return true;
4601 return false;
4605 /* Worker for DEF_BUILTIN.
4606 Possibly define a builtin function with one or two names.
4607 Does not declare a non-__builtin_ function if flag_no_builtin, or if
4608 nonansi_p and flag_no_nonansi_builtin. */
4610 static void
4611 def_builtin_1 (enum built_in_function fncode,
4612 const char *name,
4613 enum built_in_class fnclass,
4614 tree fntype, tree libtype,
4615 bool both_p, bool fallback_p, bool nonansi_p,
4616 tree fnattrs, bool implicit_p)
4618 tree decl;
4619 const char *libname;
4621 if (fntype == error_mark_node)
4622 return;
4624 gcc_assert ((!both_p && !fallback_p)
4625 || !strncmp (name, "__builtin_",
4626 strlen ("__builtin_")));
4628 libname = name + strlen ("__builtin_");
4629 decl = add_builtin_function (name, fntype, fncode, fnclass,
4630 (fallback_p ? libname : NULL),
4631 fnattrs);
4633 set_builtin_decl (fncode, decl, implicit_p);
4635 if (both_p
4636 && !flag_no_builtin && !builtin_function_disabled_p (libname)
4637 && !(nonansi_p && flag_no_nonansi_builtin))
4638 add_builtin_function (libname, libtype, fncode, fnclass,
4639 NULL, fnattrs);
4642 /* Nonzero if the type T promotes to int. This is (nearly) the
4643 integral promotions defined in ISO C99 6.3.1.1/2. */
4645 bool
4646 c_promoting_integer_type_p (const_tree t)
4648 switch (TREE_CODE (t))
4650 case INTEGER_TYPE:
4651 return (TYPE_MAIN_VARIANT (t) == char_type_node
4652 || TYPE_MAIN_VARIANT (t) == signed_char_type_node
4653 || TYPE_MAIN_VARIANT (t) == unsigned_char_type_node
4654 || TYPE_MAIN_VARIANT (t) == short_integer_type_node
4655 || TYPE_MAIN_VARIANT (t) == short_unsigned_type_node
4656 || TYPE_PRECISION (t) < TYPE_PRECISION (integer_type_node));
4658 case ENUMERAL_TYPE:
4659 /* ??? Technically all enumerations not larger than an int
4660 promote to an int. But this is used along code paths
4661 that only want to notice a size change. */
4662 return TYPE_PRECISION (t) < TYPE_PRECISION (integer_type_node);
4664 case BOOLEAN_TYPE:
4665 return true;
4667 default:
4668 return false;
4672 /* Return 1 if PARMS specifies a fixed number of parameters
4673 and none of their types is affected by default promotions. */
4675 bool
4676 self_promoting_args_p (const_tree parms)
4678 const_tree t;
4679 for (t = parms; t; t = TREE_CHAIN (t))
4681 tree type = TREE_VALUE (t);
4683 if (type == error_mark_node)
4684 continue;
4686 if (TREE_CHAIN (t) == NULL_TREE && type != void_type_node)
4687 return false;
4689 if (type == NULL_TREE)
4690 return false;
4692 if (TYPE_MAIN_VARIANT (type) == float_type_node)
4693 return false;
4695 if (c_promoting_integer_type_p (type))
4696 return false;
4698 return true;
4701 /* Recursively remove any '*' or '&' operator from TYPE. */
4702 tree
4703 strip_pointer_operator (tree t)
4705 while (POINTER_TYPE_P (t))
4706 t = TREE_TYPE (t);
4707 return t;
4710 /* Recursively remove pointer or array type from TYPE. */
4711 tree
4712 strip_pointer_or_array_types (tree t)
4714 while (TREE_CODE (t) == ARRAY_TYPE || POINTER_TYPE_P (t))
4715 t = TREE_TYPE (t);
4716 return t;
4719 /* Used to compare case labels. K1 and K2 are actually tree nodes
4720 representing case labels, or NULL_TREE for a `default' label.
4721 Returns -1 if K1 is ordered before K2, -1 if K1 is ordered after
4722 K2, and 0 if K1 and K2 are equal. */
4725 case_compare (splay_tree_key k1, splay_tree_key k2)
4727 /* Consider a NULL key (such as arises with a `default' label) to be
4728 smaller than anything else. */
4729 if (!k1)
4730 return k2 ? -1 : 0;
4731 else if (!k2)
4732 return k1 ? 1 : 0;
4734 return tree_int_cst_compare ((tree) k1, (tree) k2);
4737 /* Process a case label, located at LOC, for the range LOW_VALUE
4738 ... HIGH_VALUE. If LOW_VALUE and HIGH_VALUE are both NULL_TREE
4739 then this case label is actually a `default' label. If only
4740 HIGH_VALUE is NULL_TREE, then case label was declared using the
4741 usual C/C++ syntax, rather than the GNU case range extension.
4742 CASES is a tree containing all the case ranges processed so far;
4743 COND is the condition for the switch-statement itself.
4744 OUTSIDE_RANGE_P says whether there was a case value that doesn't
4745 fit into the range of the ORIG_TYPE. Returns the CASE_LABEL_EXPR
4746 created, or ERROR_MARK_NODE if no CASE_LABEL_EXPR is created. */
4748 tree
4749 c_add_case_label (location_t loc, splay_tree cases, tree cond, tree orig_type,
4750 tree low_value, tree high_value, bool *outside_range_p)
4752 tree type;
4753 tree label;
4754 tree case_label;
4755 splay_tree_node node;
4757 /* Create the LABEL_DECL itself. */
4758 label = create_artificial_label (loc);
4760 /* If there was an error processing the switch condition, bail now
4761 before we get more confused. */
4762 if (!cond || cond == error_mark_node)
4763 goto error_out;
4765 if ((low_value && TREE_TYPE (low_value)
4766 && POINTER_TYPE_P (TREE_TYPE (low_value)))
4767 || (high_value && TREE_TYPE (high_value)
4768 && POINTER_TYPE_P (TREE_TYPE (high_value))))
4770 error_at (loc, "pointers are not permitted as case values");
4771 goto error_out;
4774 /* Case ranges are a GNU extension. */
4775 if (high_value)
4776 pedwarn (loc, OPT_Wpedantic,
4777 "range expressions in switch statements are non-standard");
4779 type = TREE_TYPE (cond);
4780 if (low_value)
4782 low_value = check_case_value (loc, low_value);
4783 low_value = convert_and_check (loc, type, low_value);
4784 if (low_value == error_mark_node)
4785 goto error_out;
4787 if (high_value)
4789 high_value = check_case_value (loc, high_value);
4790 high_value = convert_and_check (loc, type, high_value);
4791 if (high_value == error_mark_node)
4792 goto error_out;
4795 if (low_value && high_value)
4797 /* If the LOW_VALUE and HIGH_VALUE are the same, then this isn't
4798 really a case range, even though it was written that way.
4799 Remove the HIGH_VALUE to simplify later processing. */
4800 if (tree_int_cst_equal (low_value, high_value))
4801 high_value = NULL_TREE;
4802 else if (!tree_int_cst_lt (low_value, high_value))
4803 warning_at (loc, 0, "empty range specified");
4806 /* See if the case is in range of the type of the original testing
4807 expression. If both low_value and high_value are out of range,
4808 don't insert the case label and return NULL_TREE. */
4809 if (low_value
4810 && !check_case_bounds (loc, type, orig_type,
4811 &low_value, high_value ? &high_value : NULL,
4812 outside_range_p))
4813 return NULL_TREE;
4815 /* Look up the LOW_VALUE in the table of case labels we already
4816 have. */
4817 node = splay_tree_lookup (cases, (splay_tree_key) low_value);
4818 /* If there was not an exact match, check for overlapping ranges.
4819 There's no need to do this if there's no LOW_VALUE or HIGH_VALUE;
4820 that's a `default' label and the only overlap is an exact match. */
4821 if (!node && (low_value || high_value))
4823 splay_tree_node low_bound;
4824 splay_tree_node high_bound;
4826 /* Even though there wasn't an exact match, there might be an
4827 overlap between this case range and another case range.
4828 Since we've (inductively) not allowed any overlapping case
4829 ranges, we simply need to find the greatest low case label
4830 that is smaller that LOW_VALUE, and the smallest low case
4831 label that is greater than LOW_VALUE. If there is an overlap
4832 it will occur in one of these two ranges. */
4833 low_bound = splay_tree_predecessor (cases,
4834 (splay_tree_key) low_value);
4835 high_bound = splay_tree_successor (cases,
4836 (splay_tree_key) low_value);
4838 /* Check to see if the LOW_BOUND overlaps. It is smaller than
4839 the LOW_VALUE, so there is no need to check unless the
4840 LOW_BOUND is in fact itself a case range. */
4841 if (low_bound
4842 && CASE_HIGH ((tree) low_bound->value)
4843 && tree_int_cst_compare (CASE_HIGH ((tree) low_bound->value),
4844 low_value) >= 0)
4845 node = low_bound;
4846 /* Check to see if the HIGH_BOUND overlaps. The low end of that
4847 range is bigger than the low end of the current range, so we
4848 are only interested if the current range is a real range, and
4849 not an ordinary case label. */
4850 else if (high_bound
4851 && high_value
4852 && (tree_int_cst_compare ((tree) high_bound->key,
4853 high_value)
4854 <= 0))
4855 node = high_bound;
4857 /* If there was an overlap, issue an error. */
4858 if (node)
4860 tree duplicate = CASE_LABEL ((tree) node->value);
4862 if (high_value)
4864 error_at (loc, "duplicate (or overlapping) case value");
4865 inform (DECL_SOURCE_LOCATION (duplicate),
4866 "this is the first entry overlapping that value");
4868 else if (low_value)
4870 error_at (loc, "duplicate case value") ;
4871 inform (DECL_SOURCE_LOCATION (duplicate), "previously used here");
4873 else
4875 error_at (loc, "multiple default labels in one switch");
4876 inform (DECL_SOURCE_LOCATION (duplicate),
4877 "this is the first default label");
4879 goto error_out;
4882 /* Add a CASE_LABEL to the statement-tree. */
4883 case_label = add_stmt (build_case_label (low_value, high_value, label));
4884 /* Register this case label in the splay tree. */
4885 splay_tree_insert (cases,
4886 (splay_tree_key) low_value,
4887 (splay_tree_value) case_label);
4889 return case_label;
4891 error_out:
4892 /* Add a label so that the back-end doesn't think that the beginning of
4893 the switch is unreachable. Note that we do not add a case label, as
4894 that just leads to duplicates and thence to failure later on. */
4895 if (!cases->root)
4897 tree t = create_artificial_label (loc);
4898 add_stmt (build_stmt (loc, LABEL_EXPR, t));
4900 return error_mark_node;
4903 /* Subroutine of c_switch_covers_all_cases_p, called via
4904 splay_tree_foreach. Return 1 if it doesn't cover all the cases.
4905 ARGS[0] is initially NULL and after the first iteration is the
4906 so far highest case label. ARGS[1] is the minimum of SWITCH_COND's
4907 type. */
4909 static int
4910 c_switch_covers_all_cases_p_1 (splay_tree_node node, void *data)
4912 tree label = (tree) node->value;
4913 tree *args = (tree *) data;
4915 /* If there is a default case, we shouldn't have called this. */
4916 gcc_assert (CASE_LOW (label));
4918 if (args[0] == NULL_TREE)
4920 if (wi::to_widest (args[1]) < wi::to_widest (CASE_LOW (label)))
4921 return 1;
4923 else if (wi::add (wi::to_widest (args[0]), 1)
4924 != wi::to_widest (CASE_LOW (label)))
4925 return 1;
4926 if (CASE_HIGH (label))
4927 args[0] = CASE_HIGH (label);
4928 else
4929 args[0] = CASE_LOW (label);
4930 return 0;
4933 /* Return true if switch with CASES and switch condition with type
4934 covers all possible values in the case labels. */
4936 bool
4937 c_switch_covers_all_cases_p (splay_tree cases, tree type)
4939 /* If there is default:, this is always the case. */
4940 splay_tree_node default_node
4941 = splay_tree_lookup (cases, (splay_tree_key) NULL);
4942 if (default_node)
4943 return true;
4945 if (!INTEGRAL_TYPE_P (type))
4946 return false;
4948 tree args[2] = { NULL_TREE, TYPE_MIN_VALUE (type) };
4949 if (splay_tree_foreach (cases, c_switch_covers_all_cases_p_1, args))
4950 return false;
4952 /* If there are no cases at all, or if the highest case label
4953 is smaller than TYPE_MAX_VALUE, return false. */
4954 if (args[0] == NULL_TREE
4955 || wi::to_widest (args[0]) < wi::to_widest (TYPE_MAX_VALUE (type)))
4956 return false;
4958 return true;
4961 /* Finish an expression taking the address of LABEL (an
4962 IDENTIFIER_NODE). Returns an expression for the address.
4964 LOC is the location for the expression returned. */
4966 tree
4967 finish_label_address_expr (tree label, location_t loc)
4969 tree result;
4971 pedwarn (input_location, OPT_Wpedantic, "taking the address of a label is non-standard");
4973 if (label == error_mark_node)
4974 return error_mark_node;
4976 label = lookup_label (label);
4977 if (label == NULL_TREE)
4978 result = null_pointer_node;
4979 else
4981 TREE_USED (label) = 1;
4982 result = build1 (ADDR_EXPR, ptr_type_node, label);
4983 /* The current function is not necessarily uninlinable.
4984 Computed gotos are incompatible with inlining, but the value
4985 here could be used only in a diagnostic, for example. */
4986 protected_set_expr_location (result, loc);
4989 return result;
4993 /* Given a boolean expression ARG, return a tree representing an increment
4994 or decrement (as indicated by CODE) of ARG. The front end must check for
4995 invalid cases (e.g., decrement in C++). */
4996 tree
4997 boolean_increment (enum tree_code code, tree arg)
4999 tree val;
5000 tree true_res = build_int_cst (TREE_TYPE (arg), 1);
5002 arg = stabilize_reference (arg);
5003 switch (code)
5005 case PREINCREMENT_EXPR:
5006 val = build2 (MODIFY_EXPR, TREE_TYPE (arg), arg, true_res);
5007 break;
5008 case POSTINCREMENT_EXPR:
5009 val = build2 (MODIFY_EXPR, TREE_TYPE (arg), arg, true_res);
5010 arg = save_expr (arg);
5011 val = build2 (COMPOUND_EXPR, TREE_TYPE (arg), val, arg);
5012 val = build2 (COMPOUND_EXPR, TREE_TYPE (arg), arg, val);
5013 break;
5014 case PREDECREMENT_EXPR:
5015 val = build2 (MODIFY_EXPR, TREE_TYPE (arg), arg,
5016 invert_truthvalue_loc (input_location, arg));
5017 break;
5018 case POSTDECREMENT_EXPR:
5019 val = build2 (MODIFY_EXPR, TREE_TYPE (arg), arg,
5020 invert_truthvalue_loc (input_location, arg));
5021 arg = save_expr (arg);
5022 val = build2 (COMPOUND_EXPR, TREE_TYPE (arg), val, arg);
5023 val = build2 (COMPOUND_EXPR, TREE_TYPE (arg), arg, val);
5024 break;
5025 default:
5026 gcc_unreachable ();
5028 TREE_SIDE_EFFECTS (val) = 1;
5029 return val;
5032 /* Built-in macros for stddef.h and stdint.h, that require macros
5033 defined in this file. */
5034 void
5035 c_stddef_cpp_builtins(void)
5037 builtin_define_with_value ("__SIZE_TYPE__", SIZE_TYPE, 0);
5038 builtin_define_with_value ("__PTRDIFF_TYPE__", PTRDIFF_TYPE, 0);
5039 builtin_define_with_value ("__WCHAR_TYPE__", MODIFIED_WCHAR_TYPE, 0);
5040 builtin_define_with_value ("__WINT_TYPE__", WINT_TYPE, 0);
5041 builtin_define_with_value ("__INTMAX_TYPE__", INTMAX_TYPE, 0);
5042 builtin_define_with_value ("__UINTMAX_TYPE__", UINTMAX_TYPE, 0);
5043 builtin_define_with_value ("__CHAR16_TYPE__", CHAR16_TYPE, 0);
5044 builtin_define_with_value ("__CHAR32_TYPE__", CHAR32_TYPE, 0);
5045 if (SIG_ATOMIC_TYPE)
5046 builtin_define_with_value ("__SIG_ATOMIC_TYPE__", SIG_ATOMIC_TYPE, 0);
5047 if (INT8_TYPE)
5048 builtin_define_with_value ("__INT8_TYPE__", INT8_TYPE, 0);
5049 if (INT16_TYPE)
5050 builtin_define_with_value ("__INT16_TYPE__", INT16_TYPE, 0);
5051 if (INT32_TYPE)
5052 builtin_define_with_value ("__INT32_TYPE__", INT32_TYPE, 0);
5053 if (INT64_TYPE)
5054 builtin_define_with_value ("__INT64_TYPE__", INT64_TYPE, 0);
5055 if (UINT8_TYPE)
5056 builtin_define_with_value ("__UINT8_TYPE__", UINT8_TYPE, 0);
5057 if (UINT16_TYPE)
5058 builtin_define_with_value ("__UINT16_TYPE__", UINT16_TYPE, 0);
5059 if (UINT32_TYPE)
5060 builtin_define_with_value ("__UINT32_TYPE__", UINT32_TYPE, 0);
5061 if (UINT64_TYPE)
5062 builtin_define_with_value ("__UINT64_TYPE__", UINT64_TYPE, 0);
5063 if (INT_LEAST8_TYPE)
5064 builtin_define_with_value ("__INT_LEAST8_TYPE__", INT_LEAST8_TYPE, 0);
5065 if (INT_LEAST16_TYPE)
5066 builtin_define_with_value ("__INT_LEAST16_TYPE__", INT_LEAST16_TYPE, 0);
5067 if (INT_LEAST32_TYPE)
5068 builtin_define_with_value ("__INT_LEAST32_TYPE__", INT_LEAST32_TYPE, 0);
5069 if (INT_LEAST64_TYPE)
5070 builtin_define_with_value ("__INT_LEAST64_TYPE__", INT_LEAST64_TYPE, 0);
5071 if (UINT_LEAST8_TYPE)
5072 builtin_define_with_value ("__UINT_LEAST8_TYPE__", UINT_LEAST8_TYPE, 0);
5073 if (UINT_LEAST16_TYPE)
5074 builtin_define_with_value ("__UINT_LEAST16_TYPE__", UINT_LEAST16_TYPE, 0);
5075 if (UINT_LEAST32_TYPE)
5076 builtin_define_with_value ("__UINT_LEAST32_TYPE__", UINT_LEAST32_TYPE, 0);
5077 if (UINT_LEAST64_TYPE)
5078 builtin_define_with_value ("__UINT_LEAST64_TYPE__", UINT_LEAST64_TYPE, 0);
5079 if (INT_FAST8_TYPE)
5080 builtin_define_with_value ("__INT_FAST8_TYPE__", INT_FAST8_TYPE, 0);
5081 if (INT_FAST16_TYPE)
5082 builtin_define_with_value ("__INT_FAST16_TYPE__", INT_FAST16_TYPE, 0);
5083 if (INT_FAST32_TYPE)
5084 builtin_define_with_value ("__INT_FAST32_TYPE__", INT_FAST32_TYPE, 0);
5085 if (INT_FAST64_TYPE)
5086 builtin_define_with_value ("__INT_FAST64_TYPE__", INT_FAST64_TYPE, 0);
5087 if (UINT_FAST8_TYPE)
5088 builtin_define_with_value ("__UINT_FAST8_TYPE__", UINT_FAST8_TYPE, 0);
5089 if (UINT_FAST16_TYPE)
5090 builtin_define_with_value ("__UINT_FAST16_TYPE__", UINT_FAST16_TYPE, 0);
5091 if (UINT_FAST32_TYPE)
5092 builtin_define_with_value ("__UINT_FAST32_TYPE__", UINT_FAST32_TYPE, 0);
5093 if (UINT_FAST64_TYPE)
5094 builtin_define_with_value ("__UINT_FAST64_TYPE__", UINT_FAST64_TYPE, 0);
5095 if (INTPTR_TYPE)
5096 builtin_define_with_value ("__INTPTR_TYPE__", INTPTR_TYPE, 0);
5097 if (UINTPTR_TYPE)
5098 builtin_define_with_value ("__UINTPTR_TYPE__", UINTPTR_TYPE, 0);
5101 static void
5102 c_init_attributes (void)
5104 /* Fill in the built_in_attributes array. */
5105 #define DEF_ATTR_NULL_TREE(ENUM) \
5106 built_in_attributes[(int) ENUM] = NULL_TREE;
5107 #define DEF_ATTR_INT(ENUM, VALUE) \
5108 built_in_attributes[(int) ENUM] = build_int_cst (integer_type_node, VALUE);
5109 #define DEF_ATTR_STRING(ENUM, VALUE) \
5110 built_in_attributes[(int) ENUM] = build_string (strlen (VALUE), VALUE);
5111 #define DEF_ATTR_IDENT(ENUM, STRING) \
5112 built_in_attributes[(int) ENUM] = get_identifier (STRING);
5113 #define DEF_ATTR_TREE_LIST(ENUM, PURPOSE, VALUE, CHAIN) \
5114 built_in_attributes[(int) ENUM] \
5115 = tree_cons (built_in_attributes[(int) PURPOSE], \
5116 built_in_attributes[(int) VALUE], \
5117 built_in_attributes[(int) CHAIN]);
5118 #include "builtin-attrs.def"
5119 #undef DEF_ATTR_NULL_TREE
5120 #undef DEF_ATTR_INT
5121 #undef DEF_ATTR_IDENT
5122 #undef DEF_ATTR_TREE_LIST
5125 /* Check whether ALIGN is a valid user-specified alignment. If so,
5126 return its base-2 log; if not, output an error and return -1. If
5127 ALLOW_ZERO then 0 is valid and should result in a return of -1 with
5128 no error. */
5130 check_user_alignment (const_tree align, bool allow_zero)
5132 int i;
5134 if (error_operand_p (align))
5135 return -1;
5136 if (TREE_CODE (align) != INTEGER_CST
5137 || !INTEGRAL_TYPE_P (TREE_TYPE (align)))
5139 error ("requested alignment is not an integer constant");
5140 return -1;
5142 else if (allow_zero && integer_zerop (align))
5143 return -1;
5144 else if (tree_int_cst_sgn (align) == -1
5145 || (i = tree_log2 (align)) == -1)
5147 error ("requested alignment is not a positive power of 2");
5148 return -1;
5150 else if (i >= HOST_BITS_PER_INT - LOG2_BITS_PER_UNIT)
5152 error ("requested alignment is too large");
5153 return -1;
5155 return i;
5158 /* Determine the ELF symbol visibility for DECL, which is either a
5159 variable or a function. It is an error to use this function if a
5160 definition of DECL is not available in this translation unit.
5161 Returns true if the final visibility has been determined by this
5162 function; false if the caller is free to make additional
5163 modifications. */
5165 bool
5166 c_determine_visibility (tree decl)
5168 gcc_assert (VAR_OR_FUNCTION_DECL_P (decl));
5170 /* If the user explicitly specified the visibility with an
5171 attribute, honor that. DECL_VISIBILITY will have been set during
5172 the processing of the attribute. We check for an explicit
5173 attribute, rather than just checking DECL_VISIBILITY_SPECIFIED,
5174 to distinguish the use of an attribute from the use of a "#pragma
5175 GCC visibility push(...)"; in the latter case we still want other
5176 considerations to be able to overrule the #pragma. */
5177 if (lookup_attribute ("visibility", DECL_ATTRIBUTES (decl))
5178 || (TARGET_DLLIMPORT_DECL_ATTRIBUTES
5179 && (lookup_attribute ("dllimport", DECL_ATTRIBUTES (decl))
5180 || lookup_attribute ("dllexport", DECL_ATTRIBUTES (decl)))))
5181 return true;
5183 /* Set default visibility to whatever the user supplied with
5184 visibility_specified depending on #pragma GCC visibility. */
5185 if (!DECL_VISIBILITY_SPECIFIED (decl))
5187 if (visibility_options.inpragma
5188 || DECL_VISIBILITY (decl) != default_visibility)
5190 DECL_VISIBILITY (decl) = default_visibility;
5191 DECL_VISIBILITY_SPECIFIED (decl) = visibility_options.inpragma;
5192 /* If visibility changed and DECL already has DECL_RTL, ensure
5193 symbol flags are updated. */
5194 if (((VAR_P (decl) && TREE_STATIC (decl))
5195 || TREE_CODE (decl) == FUNCTION_DECL)
5196 && DECL_RTL_SET_P (decl))
5197 make_decl_rtl (decl);
5200 return false;
5203 /* Data to communicate through check_function_arguments_recurse between
5204 check_function_nonnull and check_nonnull_arg. */
5206 struct nonnull_arg_ctx
5208 location_t loc;
5209 bool warned_p;
5212 /* Check the argument list of a function call for null in argument slots
5213 that are marked as requiring a non-null pointer argument. The NARGS
5214 arguments are passed in the array ARGARRAY. Return true if we have
5215 warned. */
5217 static bool
5218 check_function_nonnull (location_t loc, tree attrs, int nargs, tree *argarray)
5220 tree a;
5221 int i;
5223 attrs = lookup_attribute ("nonnull", attrs);
5224 if (attrs == NULL_TREE)
5225 return false;
5227 a = attrs;
5228 /* See if any of the nonnull attributes has no arguments. If so,
5229 then every pointer argument is checked (in which case the check
5230 for pointer type is done in check_nonnull_arg). */
5231 if (TREE_VALUE (a) != NULL_TREE)
5233 a = lookup_attribute ("nonnull", TREE_CHAIN (a));
5234 while (a != NULL_TREE && TREE_VALUE (a) != NULL_TREE);
5236 struct nonnull_arg_ctx ctx = { loc, false };
5237 if (a != NULL_TREE)
5238 for (i = 0; i < nargs; i++)
5239 check_function_arguments_recurse (check_nonnull_arg, &ctx, argarray[i],
5240 i + 1);
5241 else
5243 /* Walk the argument list. If we encounter an argument number we
5244 should check for non-null, do it. */
5245 for (i = 0; i < nargs; i++)
5247 for (a = attrs; ; a = TREE_CHAIN (a))
5249 a = lookup_attribute ("nonnull", a);
5250 if (a == NULL_TREE || nonnull_check_p (TREE_VALUE (a), i + 1))
5251 break;
5254 if (a != NULL_TREE)
5255 check_function_arguments_recurse (check_nonnull_arg, &ctx,
5256 argarray[i], i + 1);
5259 return ctx.warned_p;
5262 /* Check that the Nth argument of a function call (counting backwards
5263 from the end) is a (pointer)0. The NARGS arguments are passed in the
5264 array ARGARRAY. */
5266 static void
5267 check_function_sentinel (const_tree fntype, int nargs, tree *argarray)
5269 tree attr = lookup_attribute ("sentinel", TYPE_ATTRIBUTES (fntype));
5271 if (attr)
5273 int len = 0;
5274 int pos = 0;
5275 tree sentinel;
5276 function_args_iterator iter;
5277 tree t;
5279 /* Skip over the named arguments. */
5280 FOREACH_FUNCTION_ARGS (fntype, t, iter)
5282 if (len == nargs)
5283 break;
5284 len++;
5287 if (TREE_VALUE (attr))
5289 tree p = TREE_VALUE (TREE_VALUE (attr));
5290 pos = TREE_INT_CST_LOW (p);
5293 /* The sentinel must be one of the varargs, i.e.
5294 in position >= the number of fixed arguments. */
5295 if ((nargs - 1 - pos) < len)
5297 warning (OPT_Wformat_,
5298 "not enough variable arguments to fit a sentinel");
5299 return;
5302 /* Validate the sentinel. */
5303 sentinel = argarray[nargs - 1 - pos];
5304 if ((!POINTER_TYPE_P (TREE_TYPE (sentinel))
5305 || !integer_zerop (sentinel))
5306 /* Although __null (in C++) is only an integer we allow it
5307 nevertheless, as we are guaranteed that it's exactly
5308 as wide as a pointer, and we don't want to force
5309 users to cast the NULL they have written there.
5310 We warn with -Wstrict-null-sentinel, though. */
5311 && (warn_strict_null_sentinel || null_node != sentinel))
5312 warning (OPT_Wformat_, "missing sentinel in function call");
5316 /* Check that the same argument isn't passed to restrict arguments
5317 and other arguments. */
5319 static void
5320 check_function_restrict (const_tree fndecl, const_tree fntype,
5321 int nargs, tree *argarray)
5323 int i;
5324 tree parms = TYPE_ARG_TYPES (fntype);
5326 if (fndecl
5327 && TREE_CODE (fndecl) == FUNCTION_DECL)
5329 /* Skip checking built-ins here. They are checked in more
5330 detail elsewhere. */
5331 if (DECL_BUILT_IN (fndecl)
5332 && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
5333 return;
5335 if (DECL_ARGUMENTS (fndecl))
5336 parms = DECL_ARGUMENTS (fndecl);
5339 for (i = 0; i < nargs; i++)
5340 TREE_VISITED (argarray[i]) = 0;
5342 for (i = 0; i < nargs && parms && parms != void_list_node; i++)
5344 tree type;
5345 if (TREE_CODE (parms) == PARM_DECL)
5347 type = TREE_TYPE (parms);
5348 parms = DECL_CHAIN (parms);
5350 else
5352 type = TREE_VALUE (parms);
5353 parms = TREE_CHAIN (parms);
5355 if (POINTER_TYPE_P (type)
5356 && TYPE_RESTRICT (type)
5357 && !TYPE_READONLY (TREE_TYPE (type)))
5358 warn_for_restrict (i, argarray, nargs);
5361 for (i = 0; i < nargs; i++)
5362 TREE_VISITED (argarray[i]) = 0;
5365 /* Helper for check_function_nonnull; given a list of operands which
5366 must be non-null in ARGS, determine if operand PARAM_NUM should be
5367 checked. */
5369 static bool
5370 nonnull_check_p (tree args, unsigned HOST_WIDE_INT param_num)
5372 unsigned HOST_WIDE_INT arg_num = 0;
5374 for (; args; args = TREE_CHAIN (args))
5376 bool found = get_nonnull_operand (TREE_VALUE (args), &arg_num);
5378 gcc_assert (found);
5380 if (arg_num == param_num)
5381 return true;
5383 return false;
5386 /* Check that the function argument PARAM (which is operand number
5387 PARAM_NUM) is non-null. This is called by check_function_nonnull
5388 via check_function_arguments_recurse. */
5390 static void
5391 check_nonnull_arg (void *ctx, tree param, unsigned HOST_WIDE_INT param_num)
5393 struct nonnull_arg_ctx *pctx = (struct nonnull_arg_ctx *) ctx;
5395 /* Just skip checking the argument if it's not a pointer. This can
5396 happen if the "nonnull" attribute was given without an operand
5397 list (which means to check every pointer argument). */
5399 if (TREE_CODE (TREE_TYPE (param)) != POINTER_TYPE)
5400 return;
5402 /* When not optimizing diagnose the simple cases of null arguments.
5403 When optimization is enabled defer the checking until expansion
5404 when more cases can be detected. */
5405 if (integer_zerop (param))
5407 warning_at (pctx->loc, OPT_Wnonnull, "null argument where non-null "
5408 "required (argument %lu)", (unsigned long) param_num);
5409 pctx->warned_p = true;
5413 /* Helper for nonnull attribute handling; fetch the operand number
5414 from the attribute argument list. */
5416 bool
5417 get_nonnull_operand (tree arg_num_expr, unsigned HOST_WIDE_INT *valp)
5419 /* Verify the arg number is a small constant. */
5420 if (tree_fits_uhwi_p (arg_num_expr))
5422 *valp = tree_to_uhwi (arg_num_expr);
5423 return true;
5425 else
5426 return false;
5429 /* Arguments being collected for optimization. */
5430 typedef const char *const_char_p; /* For DEF_VEC_P. */
5431 static GTY(()) vec<const_char_p, va_gc> *optimize_args;
5434 /* Inner function to convert a TREE_LIST to argv string to parse the optimize
5435 options in ARGS. ATTR_P is true if this is for attribute(optimize), and
5436 false for #pragma GCC optimize. */
5438 bool
5439 parse_optimize_options (tree args, bool attr_p)
5441 bool ret = true;
5442 unsigned opt_argc;
5443 unsigned i;
5444 const char **opt_argv;
5445 struct cl_decoded_option *decoded_options;
5446 unsigned int decoded_options_count;
5447 tree ap;
5449 /* Build up argv vector. Just in case the string is stored away, use garbage
5450 collected strings. */
5451 vec_safe_truncate (optimize_args, 0);
5452 vec_safe_push (optimize_args, (const char *) NULL);
5454 for (ap = args; ap != NULL_TREE; ap = TREE_CHAIN (ap))
5456 tree value = TREE_VALUE (ap);
5458 if (TREE_CODE (value) == INTEGER_CST)
5460 char buffer[20];
5461 sprintf (buffer, "-O%ld", (long) TREE_INT_CST_LOW (value));
5462 vec_safe_push (optimize_args, ggc_strdup (buffer));
5465 else if (TREE_CODE (value) == STRING_CST)
5467 /* Split string into multiple substrings. */
5468 size_t len = TREE_STRING_LENGTH (value);
5469 char *p = ASTRDUP (TREE_STRING_POINTER (value));
5470 char *end = p + len;
5471 char *comma;
5472 char *next_p = p;
5474 while (next_p != NULL)
5476 size_t len2;
5477 char *q, *r;
5479 p = next_p;
5480 comma = strchr (p, ',');
5481 if (comma)
5483 len2 = comma - p;
5484 *comma = '\0';
5485 next_p = comma+1;
5487 else
5489 len2 = end - p;
5490 next_p = NULL;
5493 r = q = (char *) ggc_alloc_atomic (len2 + 3);
5495 /* If the user supplied -Oxxx or -fxxx, only allow -Oxxx or -fxxx
5496 options. */
5497 if (*p == '-' && p[1] != 'O' && p[1] != 'f')
5499 ret = false;
5500 if (attr_p)
5501 warning (OPT_Wattributes,
5502 "bad option %qs to attribute %<optimize%>", p);
5503 else
5504 warning (OPT_Wpragmas,
5505 "bad option %qs to pragma %<optimize%>", p);
5506 continue;
5509 if (*p != '-')
5511 *r++ = '-';
5513 /* Assume that Ox is -Ox, a numeric value is -Ox, a s by
5514 itself is -Os, and any other switch begins with a -f. */
5515 if ((*p >= '0' && *p <= '9')
5516 || (p[0] == 's' && p[1] == '\0'))
5517 *r++ = 'O';
5518 else if (*p != 'O')
5519 *r++ = 'f';
5522 memcpy (r, p, len2);
5523 r[len2] = '\0';
5524 vec_safe_push (optimize_args, (const char *) q);
5530 opt_argc = optimize_args->length ();
5531 opt_argv = (const char **) alloca (sizeof (char *) * (opt_argc + 1));
5533 for (i = 1; i < opt_argc; i++)
5534 opt_argv[i] = (*optimize_args)[i];
5536 /* Now parse the options. */
5537 decode_cmdline_options_to_array_default_mask (opt_argc, opt_argv,
5538 &decoded_options,
5539 &decoded_options_count);
5540 /* Drop non-Optimization options. */
5541 unsigned j = 1;
5542 for (i = 1; i < decoded_options_count; ++i)
5544 if (! (cl_options[decoded_options[i].opt_index].flags & CL_OPTIMIZATION))
5546 ret = false;
5547 if (attr_p)
5548 warning (OPT_Wattributes,
5549 "bad option %qs to attribute %<optimize%>",
5550 decoded_options[i].orig_option_with_args_text);
5551 else
5552 warning (OPT_Wpragmas,
5553 "bad option %qs to pragma %<optimize%>",
5554 decoded_options[i].orig_option_with_args_text);
5555 continue;
5557 if (i != j)
5558 decoded_options[j] = decoded_options[i];
5559 j++;
5561 decoded_options_count = j;
5562 /* And apply them. */
5563 decode_options (&global_options, &global_options_set,
5564 decoded_options, decoded_options_count,
5565 input_location, global_dc, NULL);
5567 targetm.override_options_after_change();
5569 optimize_args->truncate (0);
5570 return ret;
5573 /* Check whether ATTR is a valid attribute fallthrough. */
5575 bool
5576 attribute_fallthrough_p (tree attr)
5578 if (attr == error_mark_node)
5579 return false;
5580 tree t = lookup_attribute ("fallthrough", attr);
5581 if (t == NULL_TREE)
5582 return false;
5583 /* This attribute shall appear at most once in each attribute-list. */
5584 if (lookup_attribute ("fallthrough", TREE_CHAIN (t)))
5585 warning (OPT_Wattributes, "%<fallthrough%> attribute specified multiple "
5586 "times");
5587 /* No attribute-argument-clause shall be present. */
5588 else if (TREE_VALUE (t) != NULL_TREE)
5589 warning (OPT_Wattributes, "%<fallthrough%> attribute specified with "
5590 "a parameter");
5591 /* Warn if other attributes are found. */
5592 for (t = attr; t != NULL_TREE; t = TREE_CHAIN (t))
5594 tree name = get_attribute_name (t);
5595 if (!is_attribute_p ("fallthrough", name))
5596 warning (OPT_Wattributes, "%qE attribute ignored", name);
5598 return true;
5602 /* Check for valid arguments being passed to a function with FNTYPE.
5603 There are NARGS arguments in the array ARGARRAY. LOC should be used for
5604 diagnostics. Return true if -Wnonnull warning has been diagnosed. */
5605 bool
5606 check_function_arguments (location_t loc, const_tree fndecl, const_tree fntype,
5607 int nargs, tree *argarray, vec<location_t> *arglocs)
5609 bool warned_p = false;
5611 /* Check for null being passed in a pointer argument that must be
5612 non-null. We also need to do this if format checking is enabled. */
5614 if (warn_nonnull)
5615 warned_p = check_function_nonnull (loc, TYPE_ATTRIBUTES (fntype),
5616 nargs, argarray);
5618 /* Check for errors in format strings. */
5620 if (warn_format || warn_suggest_attribute_format)
5621 check_function_format (TYPE_ATTRIBUTES (fntype), nargs, argarray, arglocs);
5623 if (warn_format)
5624 check_function_sentinel (fntype, nargs, argarray);
5626 if (warn_restrict)
5627 check_function_restrict (fndecl, fntype, nargs, argarray);
5628 return warned_p;
5631 /* Generic argument checking recursion routine. PARAM is the argument to
5632 be checked. PARAM_NUM is the number of the argument. CALLBACK is invoked
5633 once the argument is resolved. CTX is context for the callback. */
5634 void
5635 check_function_arguments_recurse (void (*callback)
5636 (void *, tree, unsigned HOST_WIDE_INT),
5637 void *ctx, tree param,
5638 unsigned HOST_WIDE_INT param_num)
5640 if (CONVERT_EXPR_P (param)
5641 && (TYPE_PRECISION (TREE_TYPE (param))
5642 == TYPE_PRECISION (TREE_TYPE (TREE_OPERAND (param, 0)))))
5644 /* Strip coercion. */
5645 check_function_arguments_recurse (callback, ctx,
5646 TREE_OPERAND (param, 0), param_num);
5647 return;
5650 if (TREE_CODE (param) == CALL_EXPR)
5652 tree type = TREE_TYPE (TREE_TYPE (CALL_EXPR_FN (param)));
5653 tree attrs;
5654 bool found_format_arg = false;
5656 /* See if this is a call to a known internationalization function
5657 that modifies a format arg. Such a function may have multiple
5658 format_arg attributes (for example, ngettext). */
5660 for (attrs = TYPE_ATTRIBUTES (type);
5661 attrs;
5662 attrs = TREE_CHAIN (attrs))
5663 if (is_attribute_p ("format_arg", TREE_PURPOSE (attrs)))
5665 tree inner_arg;
5666 tree format_num_expr;
5667 int format_num;
5668 int i;
5669 call_expr_arg_iterator iter;
5671 /* Extract the argument number, which was previously checked
5672 to be valid. */
5673 format_num_expr = TREE_VALUE (TREE_VALUE (attrs));
5675 format_num = tree_to_uhwi (format_num_expr);
5677 for (inner_arg = first_call_expr_arg (param, &iter), i = 1;
5678 inner_arg != NULL_TREE;
5679 inner_arg = next_call_expr_arg (&iter), i++)
5680 if (i == format_num)
5682 check_function_arguments_recurse (callback, ctx,
5683 inner_arg, param_num);
5684 found_format_arg = true;
5685 break;
5689 /* If we found a format_arg attribute and did a recursive check,
5690 we are done with checking this argument. Otherwise, we continue
5691 and this will be considered a non-literal. */
5692 if (found_format_arg)
5693 return;
5696 if (TREE_CODE (param) == COND_EXPR)
5698 /* Simplify to avoid warning for an impossible case. */
5699 param = fold_for_warn (param);
5700 if (TREE_CODE (param) == COND_EXPR)
5702 /* Check both halves of the conditional expression. */
5703 check_function_arguments_recurse (callback, ctx,
5704 TREE_OPERAND (param, 1),
5705 param_num);
5706 check_function_arguments_recurse (callback, ctx,
5707 TREE_OPERAND (param, 2),
5708 param_num);
5709 return;
5713 (*callback) (ctx, param, param_num);
5716 /* Checks for a builtin function FNDECL that the number of arguments
5717 NARGS against the required number REQUIRED and issues an error if
5718 there is a mismatch. Returns true if the number of arguments is
5719 correct, otherwise false. LOC is the location of FNDECL. */
5721 static bool
5722 builtin_function_validate_nargs (location_t loc, tree fndecl, int nargs,
5723 int required)
5725 if (nargs < required)
5727 error_at (loc, "too few arguments to function %qE", fndecl);
5728 return false;
5730 else if (nargs > required)
5732 error_at (loc, "too many arguments to function %qE", fndecl);
5733 return false;
5735 return true;
5738 /* Helper macro for check_builtin_function_arguments. */
5739 #define ARG_LOCATION(N) \
5740 (arg_loc.is_empty () \
5741 ? EXPR_LOC_OR_LOC (args[(N)], input_location) \
5742 : expansion_point_location (arg_loc[(N)]))
5744 /* Verifies the NARGS arguments ARGS to the builtin function FNDECL.
5745 Returns false if there was an error, otherwise true. LOC is the
5746 location of the function; ARG_LOC is a vector of locations of the
5747 arguments. */
5749 bool
5750 check_builtin_function_arguments (location_t loc, vec<location_t> arg_loc,
5751 tree fndecl, int nargs, tree *args)
5753 if (!DECL_BUILT_IN (fndecl)
5754 || DECL_BUILT_IN_CLASS (fndecl) != BUILT_IN_NORMAL)
5755 return true;
5757 switch (DECL_FUNCTION_CODE (fndecl))
5759 case BUILT_IN_ALLOCA_WITH_ALIGN_AND_MAX:
5760 if (!tree_fits_uhwi_p (args[2]))
5762 error_at (ARG_LOCATION (2),
5763 "third argument to function %qE must be a constant integer",
5764 fndecl);
5765 return false;
5767 /* fall through */
5769 case BUILT_IN_ALLOCA_WITH_ALIGN:
5771 /* Get the requested alignment (in bits) if it's a constant
5772 integer expression. */
5773 unsigned HOST_WIDE_INT align
5774 = tree_fits_uhwi_p (args[1]) ? tree_to_uhwi (args[1]) : 0;
5776 /* Determine if the requested alignment is a power of 2. */
5777 if ((align & (align - 1)))
5778 align = 0;
5780 /* The maximum alignment in bits corresponding to the same
5781 maximum in bytes enforced in check_user_alignment(). */
5782 unsigned maxalign = (UINT_MAX >> 1) + 1;
5784 /* Reject invalid alignments. */
5785 if (align < BITS_PER_UNIT || maxalign < align)
5787 error_at (ARG_LOCATION (1),
5788 "second argument to function %qE must be a constant "
5789 "integer power of 2 between %qi and %qu bits",
5790 fndecl, BITS_PER_UNIT, maxalign);
5791 return false;
5793 return true;
5796 case BUILT_IN_CONSTANT_P:
5797 return builtin_function_validate_nargs (loc, fndecl, nargs, 1);
5799 case BUILT_IN_ISFINITE:
5800 case BUILT_IN_ISINF:
5801 case BUILT_IN_ISINF_SIGN:
5802 case BUILT_IN_ISNAN:
5803 case BUILT_IN_ISNORMAL:
5804 case BUILT_IN_SIGNBIT:
5805 if (builtin_function_validate_nargs (loc, fndecl, nargs, 1))
5807 if (TREE_CODE (TREE_TYPE (args[0])) != REAL_TYPE)
5809 error_at (ARG_LOCATION (0), "non-floating-point argument in "
5810 "call to function %qE", fndecl);
5811 return false;
5813 return true;
5815 return false;
5817 case BUILT_IN_ISGREATER:
5818 case BUILT_IN_ISGREATEREQUAL:
5819 case BUILT_IN_ISLESS:
5820 case BUILT_IN_ISLESSEQUAL:
5821 case BUILT_IN_ISLESSGREATER:
5822 case BUILT_IN_ISUNORDERED:
5823 if (builtin_function_validate_nargs (loc, fndecl, nargs, 2))
5825 enum tree_code code0, code1;
5826 code0 = TREE_CODE (TREE_TYPE (args[0]));
5827 code1 = TREE_CODE (TREE_TYPE (args[1]));
5828 if (!((code0 == REAL_TYPE && code1 == REAL_TYPE)
5829 || (code0 == REAL_TYPE && code1 == INTEGER_TYPE)
5830 || (code0 == INTEGER_TYPE && code1 == REAL_TYPE)))
5832 error_at (loc, "non-floating-point arguments in call to "
5833 "function %qE", fndecl);
5834 return false;
5836 return true;
5838 return false;
5840 case BUILT_IN_FPCLASSIFY:
5841 if (builtin_function_validate_nargs (loc, fndecl, nargs, 6))
5843 for (unsigned int i = 0; i < 5; i++)
5844 if (TREE_CODE (args[i]) != INTEGER_CST)
5846 error_at (ARG_LOCATION (i), "non-const integer argument %u in "
5847 "call to function %qE", i + 1, fndecl);
5848 return false;
5851 if (TREE_CODE (TREE_TYPE (args[5])) != REAL_TYPE)
5853 error_at (ARG_LOCATION (5), "non-floating-point argument in "
5854 "call to function %qE", fndecl);
5855 return false;
5857 return true;
5859 return false;
5861 case BUILT_IN_ASSUME_ALIGNED:
5862 if (builtin_function_validate_nargs (loc, fndecl, nargs, 2 + (nargs > 2)))
5864 if (nargs >= 3 && TREE_CODE (TREE_TYPE (args[2])) != INTEGER_TYPE)
5866 error_at (ARG_LOCATION (2), "non-integer argument 3 in call to "
5867 "function %qE", fndecl);
5868 return false;
5870 return true;
5872 return false;
5874 case BUILT_IN_ADD_OVERFLOW:
5875 case BUILT_IN_SUB_OVERFLOW:
5876 case BUILT_IN_MUL_OVERFLOW:
5877 if (builtin_function_validate_nargs (loc, fndecl, nargs, 3))
5879 unsigned i;
5880 for (i = 0; i < 2; i++)
5881 if (!INTEGRAL_TYPE_P (TREE_TYPE (args[i])))
5883 error_at (ARG_LOCATION (i), "argument %u in call to function "
5884 "%qE does not have integral type", i + 1, fndecl);
5885 return false;
5887 if (TREE_CODE (TREE_TYPE (args[2])) != POINTER_TYPE
5888 || !INTEGRAL_TYPE_P (TREE_TYPE (TREE_TYPE (args[2]))))
5890 error_at (ARG_LOCATION (2), "argument 3 in call to function %qE "
5891 "does not have pointer to integral type", fndecl);
5892 return false;
5894 else if (TREE_CODE (TREE_TYPE (TREE_TYPE (args[2]))) == ENUMERAL_TYPE)
5896 error_at (ARG_LOCATION (2), "argument 3 in call to function %qE "
5897 "has pointer to enumerated type", fndecl);
5898 return false;
5900 else if (TREE_CODE (TREE_TYPE (TREE_TYPE (args[2]))) == BOOLEAN_TYPE)
5902 error_at (ARG_LOCATION (2), "argument 3 in call to function %qE "
5903 "has pointer to boolean type", fndecl);
5904 return false;
5906 return true;
5908 return false;
5910 case BUILT_IN_ADD_OVERFLOW_P:
5911 case BUILT_IN_SUB_OVERFLOW_P:
5912 case BUILT_IN_MUL_OVERFLOW_P:
5913 if (builtin_function_validate_nargs (loc, fndecl, nargs, 3))
5915 unsigned i;
5916 for (i = 0; i < 3; i++)
5917 if (!INTEGRAL_TYPE_P (TREE_TYPE (args[i])))
5919 error_at (ARG_LOCATION (i), "argument %u in call to function "
5920 "%qE does not have integral type", i + 1, fndecl);
5921 return false;
5923 if (TREE_CODE (TREE_TYPE (args[2])) == ENUMERAL_TYPE)
5925 error_at (ARG_LOCATION (2), "argument 3 in call to function "
5926 "%qE has enumerated type", fndecl);
5927 return false;
5929 else if (TREE_CODE (TREE_TYPE (args[2])) == BOOLEAN_TYPE)
5931 error_at (ARG_LOCATION (2), "argument 3 in call to function "
5932 "%qE has boolean type", fndecl);
5933 return false;
5935 return true;
5937 return false;
5939 default:
5940 return true;
5944 /* Subroutine of c_parse_error.
5945 Return the result of concatenating LHS and RHS. RHS is really
5946 a string literal, its first character is indicated by RHS_START and
5947 RHS_SIZE is its length (including the terminating NUL character).
5949 The caller is responsible for deleting the returned pointer. */
5951 static char *
5952 catenate_strings (const char *lhs, const char *rhs_start, int rhs_size)
5954 const size_t lhs_size = strlen (lhs);
5955 char *result = XNEWVEC (char, lhs_size + rhs_size);
5956 memcpy (result, lhs, lhs_size);
5957 memcpy (result + lhs_size, rhs_start, rhs_size);
5958 return result;
5961 /* Issue the error given by GMSGID at RICHLOC, indicating that it occurred
5962 before TOKEN, which had the associated VALUE. */
5964 void
5965 c_parse_error (const char *gmsgid, enum cpp_ttype token_type,
5966 tree value, unsigned char token_flags,
5967 rich_location *richloc)
5969 #define catenate_messages(M1, M2) catenate_strings ((M1), (M2), sizeof (M2))
5971 char *message = NULL;
5973 if (token_type == CPP_EOF)
5974 message = catenate_messages (gmsgid, " at end of input");
5975 else if (token_type == CPP_CHAR
5976 || token_type == CPP_WCHAR
5977 || token_type == CPP_CHAR16
5978 || token_type == CPP_CHAR32
5979 || token_type == CPP_UTF8CHAR)
5981 unsigned int val = TREE_INT_CST_LOW (value);
5982 const char *prefix;
5984 switch (token_type)
5986 default:
5987 prefix = "";
5988 break;
5989 case CPP_WCHAR:
5990 prefix = "L";
5991 break;
5992 case CPP_CHAR16:
5993 prefix = "u";
5994 break;
5995 case CPP_CHAR32:
5996 prefix = "U";
5997 break;
5998 case CPP_UTF8CHAR:
5999 prefix = "u8";
6000 break;
6003 if (val <= UCHAR_MAX && ISGRAPH (val))
6004 message = catenate_messages (gmsgid, " before %s'%c'");
6005 else
6006 message = catenate_messages (gmsgid, " before %s'\\x%x'");
6008 error_at (richloc, message, prefix, val);
6009 free (message);
6010 message = NULL;
6012 else if (token_type == CPP_CHAR_USERDEF
6013 || token_type == CPP_WCHAR_USERDEF
6014 || token_type == CPP_CHAR16_USERDEF
6015 || token_type == CPP_CHAR32_USERDEF
6016 || token_type == CPP_UTF8CHAR_USERDEF)
6017 message = catenate_messages (gmsgid,
6018 " before user-defined character literal");
6019 else if (token_type == CPP_STRING_USERDEF
6020 || token_type == CPP_WSTRING_USERDEF
6021 || token_type == CPP_STRING16_USERDEF
6022 || token_type == CPP_STRING32_USERDEF
6023 || token_type == CPP_UTF8STRING_USERDEF)
6024 message = catenate_messages (gmsgid, " before user-defined string literal");
6025 else if (token_type == CPP_STRING
6026 || token_type == CPP_WSTRING
6027 || token_type == CPP_STRING16
6028 || token_type == CPP_STRING32
6029 || token_type == CPP_UTF8STRING)
6030 message = catenate_messages (gmsgid, " before string constant");
6031 else if (token_type == CPP_NUMBER)
6032 message = catenate_messages (gmsgid, " before numeric constant");
6033 else if (token_type == CPP_NAME)
6035 message = catenate_messages (gmsgid, " before %qE");
6036 error_at (richloc, message, value);
6037 free (message);
6038 message = NULL;
6040 else if (token_type == CPP_PRAGMA)
6041 message = catenate_messages (gmsgid, " before %<#pragma%>");
6042 else if (token_type == CPP_PRAGMA_EOL)
6043 message = catenate_messages (gmsgid, " before end of line");
6044 else if (token_type == CPP_DECLTYPE)
6045 message = catenate_messages (gmsgid, " before %<decltype%>");
6046 else if (token_type < N_TTYPES)
6048 message = catenate_messages (gmsgid, " before %qs token");
6049 error_at (richloc, message, cpp_type2name (token_type, token_flags));
6050 free (message);
6051 message = NULL;
6053 else
6054 error_at (richloc, gmsgid);
6056 if (message)
6058 error_at (richloc, message);
6059 free (message);
6061 #undef catenate_messages
6064 /* Return the gcc option code associated with the reason for a cpp
6065 message, or 0 if none. */
6067 static int
6068 c_option_controlling_cpp_error (int reason)
6070 const struct cpp_reason_option_codes_t *entry;
6072 for (entry = cpp_reason_option_codes; entry->reason != CPP_W_NONE; entry++)
6074 if (entry->reason == reason)
6075 return entry->option_code;
6077 return 0;
6080 /* Callback from cpp_error for PFILE to print diagnostics from the
6081 preprocessor. The diagnostic is of type LEVEL, with REASON set
6082 to the reason code if LEVEL is represents a warning, at location
6083 RICHLOC unless this is after lexing and the compiler's location
6084 should be used instead; MSG is the translated message and AP
6085 the arguments. Returns true if a diagnostic was emitted, false
6086 otherwise. */
6088 bool
6089 c_cpp_error (cpp_reader *pfile ATTRIBUTE_UNUSED, int level, int reason,
6090 rich_location *richloc,
6091 const char *msg, va_list *ap)
6093 diagnostic_info diagnostic;
6094 diagnostic_t dlevel;
6095 bool save_warn_system_headers = global_dc->dc_warn_system_headers;
6096 bool ret;
6098 switch (level)
6100 case CPP_DL_WARNING_SYSHDR:
6101 if (flag_no_output)
6102 return false;
6103 global_dc->dc_warn_system_headers = 1;
6104 /* Fall through. */
6105 case CPP_DL_WARNING:
6106 if (flag_no_output)
6107 return false;
6108 dlevel = DK_WARNING;
6109 break;
6110 case CPP_DL_PEDWARN:
6111 if (flag_no_output && !flag_pedantic_errors)
6112 return false;
6113 dlevel = DK_PEDWARN;
6114 break;
6115 case CPP_DL_ERROR:
6116 dlevel = DK_ERROR;
6117 break;
6118 case CPP_DL_ICE:
6119 dlevel = DK_ICE;
6120 break;
6121 case CPP_DL_NOTE:
6122 dlevel = DK_NOTE;
6123 break;
6124 case CPP_DL_FATAL:
6125 dlevel = DK_FATAL;
6126 break;
6127 default:
6128 gcc_unreachable ();
6130 if (done_lexing)
6131 richloc->set_range (line_table, 0, input_location, true);
6132 diagnostic_set_info_translated (&diagnostic, msg, ap,
6133 richloc, dlevel);
6134 diagnostic_override_option_index (&diagnostic,
6135 c_option_controlling_cpp_error (reason));
6136 ret = diagnostic_report_diagnostic (global_dc, &diagnostic);
6137 if (level == CPP_DL_WARNING_SYSHDR)
6138 global_dc->dc_warn_system_headers = save_warn_system_headers;
6139 return ret;
6142 /* Convert a character from the host to the target execution character
6143 set. cpplib handles this, mostly. */
6145 HOST_WIDE_INT
6146 c_common_to_target_charset (HOST_WIDE_INT c)
6148 /* Character constants in GCC proper are sign-extended under -fsigned-char,
6149 zero-extended under -fno-signed-char. cpplib insists that characters
6150 and character constants are always unsigned. Hence we must convert
6151 back and forth. */
6152 cppchar_t uc = ((cppchar_t)c) & ((((cppchar_t)1) << CHAR_BIT)-1);
6154 uc = cpp_host_to_exec_charset (parse_in, uc);
6156 if (flag_signed_char)
6157 return ((HOST_WIDE_INT)uc) << (HOST_BITS_PER_WIDE_INT - CHAR_TYPE_SIZE)
6158 >> (HOST_BITS_PER_WIDE_INT - CHAR_TYPE_SIZE);
6159 else
6160 return uc;
6163 /* Fold an offsetof-like expression. EXPR is a nested sequence of component
6164 references with an INDIRECT_REF of a constant at the bottom; much like the
6165 traditional rendering of offsetof as a macro. Return the folded result. */
6167 tree
6168 fold_offsetof_1 (tree expr, enum tree_code ctx)
6170 tree base, off, t;
6171 tree_code code = TREE_CODE (expr);
6172 switch (code)
6174 case ERROR_MARK:
6175 return expr;
6177 case VAR_DECL:
6178 error ("cannot apply %<offsetof%> to static data member %qD", expr);
6179 return error_mark_node;
6181 case CALL_EXPR:
6182 case TARGET_EXPR:
6183 error ("cannot apply %<offsetof%> when %<operator[]%> is overloaded");
6184 return error_mark_node;
6186 case NOP_EXPR:
6187 case INDIRECT_REF:
6188 if (!TREE_CONSTANT (TREE_OPERAND (expr, 0)))
6190 error ("cannot apply %<offsetof%> to a non constant address");
6191 return error_mark_node;
6193 return TREE_OPERAND (expr, 0);
6195 case COMPONENT_REF:
6196 base = fold_offsetof_1 (TREE_OPERAND (expr, 0), code);
6197 if (base == error_mark_node)
6198 return base;
6200 t = TREE_OPERAND (expr, 1);
6201 if (DECL_C_BIT_FIELD (t))
6203 error ("attempt to take address of bit-field structure "
6204 "member %qD", t);
6205 return error_mark_node;
6207 off = size_binop_loc (input_location, PLUS_EXPR, DECL_FIELD_OFFSET (t),
6208 size_int (tree_to_uhwi (DECL_FIELD_BIT_OFFSET (t))
6209 / BITS_PER_UNIT));
6210 break;
6212 case ARRAY_REF:
6213 base = fold_offsetof_1 (TREE_OPERAND (expr, 0), code);
6214 if (base == error_mark_node)
6215 return base;
6217 t = TREE_OPERAND (expr, 1);
6219 /* Check if the offset goes beyond the upper bound of the array. */
6220 if (TREE_CODE (t) == INTEGER_CST && tree_int_cst_sgn (t) >= 0)
6222 tree upbound = array_ref_up_bound (expr);
6223 if (upbound != NULL_TREE
6224 && TREE_CODE (upbound) == INTEGER_CST
6225 && !tree_int_cst_equal (upbound,
6226 TYPE_MAX_VALUE (TREE_TYPE (upbound))))
6228 if (ctx != ARRAY_REF && ctx != COMPONENT_REF)
6229 upbound = size_binop (PLUS_EXPR, upbound,
6230 build_int_cst (TREE_TYPE (upbound), 1));
6231 if (tree_int_cst_lt (upbound, t))
6233 tree v;
6235 for (v = TREE_OPERAND (expr, 0);
6236 TREE_CODE (v) == COMPONENT_REF;
6237 v = TREE_OPERAND (v, 0))
6238 if (TREE_CODE (TREE_TYPE (TREE_OPERAND (v, 0)))
6239 == RECORD_TYPE)
6241 tree fld_chain = DECL_CHAIN (TREE_OPERAND (v, 1));
6242 for (; fld_chain; fld_chain = DECL_CHAIN (fld_chain))
6243 if (TREE_CODE (fld_chain) == FIELD_DECL)
6244 break;
6246 if (fld_chain)
6247 break;
6249 /* Don't warn if the array might be considered a poor
6250 man's flexible array member with a very permissive
6251 definition thereof. */
6252 if (TREE_CODE (v) == ARRAY_REF
6253 || TREE_CODE (v) == COMPONENT_REF)
6254 warning (OPT_Warray_bounds,
6255 "index %E denotes an offset "
6256 "greater than size of %qT",
6257 t, TREE_TYPE (TREE_OPERAND (expr, 0)));
6262 t = convert (sizetype, t);
6263 off = size_binop (MULT_EXPR, TYPE_SIZE_UNIT (TREE_TYPE (expr)), t);
6264 break;
6266 case COMPOUND_EXPR:
6267 /* Handle static members of volatile structs. */
6268 t = TREE_OPERAND (expr, 1);
6269 gcc_assert (VAR_P (t));
6270 return fold_offsetof_1 (t);
6272 default:
6273 gcc_unreachable ();
6276 return fold_build_pointer_plus (base, off);
6279 /* Likewise, but convert it to the return type of offsetof. */
6281 tree
6282 fold_offsetof (tree expr)
6284 return convert (size_type_node, fold_offsetof_1 (expr));
6288 /* *PTYPE is an incomplete array. Complete it with a domain based on
6289 INITIAL_VALUE. If INITIAL_VALUE is not present, use 1 if DO_DEFAULT
6290 is true. Return 0 if successful, 1 if INITIAL_VALUE can't be deciphered,
6291 2 if INITIAL_VALUE was NULL, and 3 if INITIAL_VALUE was empty. */
6294 complete_array_type (tree *ptype, tree initial_value, bool do_default)
6296 tree maxindex, type, main_type, elt, unqual_elt;
6297 int failure = 0, quals;
6298 bool overflow_p = false;
6300 maxindex = size_zero_node;
6301 if (initial_value)
6303 if (TREE_CODE (initial_value) == STRING_CST)
6305 int eltsize
6306 = int_size_in_bytes (TREE_TYPE (TREE_TYPE (initial_value)));
6307 maxindex = size_int (TREE_STRING_LENGTH (initial_value)/eltsize - 1);
6309 else if (TREE_CODE (initial_value) == CONSTRUCTOR)
6311 vec<constructor_elt, va_gc> *v = CONSTRUCTOR_ELTS (initial_value);
6313 if (vec_safe_is_empty (v))
6315 if (pedantic)
6316 failure = 3;
6317 maxindex = ssize_int (-1);
6319 else
6321 tree curindex;
6322 unsigned HOST_WIDE_INT cnt;
6323 constructor_elt *ce;
6324 bool fold_p = false;
6326 if ((*v)[0].index)
6327 maxindex = (*v)[0].index, fold_p = true;
6329 curindex = maxindex;
6331 for (cnt = 1; vec_safe_iterate (v, cnt, &ce); cnt++)
6333 bool curfold_p = false;
6334 if (ce->index)
6335 curindex = ce->index, curfold_p = true;
6336 else
6338 if (fold_p)
6340 /* Since we treat size types now as ordinary
6341 unsigned types, we need an explicit overflow
6342 check. */
6343 tree orig = curindex;
6344 curindex = fold_convert (sizetype, curindex);
6345 overflow_p |= tree_int_cst_lt (curindex, orig);
6347 curindex = size_binop (PLUS_EXPR, curindex,
6348 size_one_node);
6350 if (tree_int_cst_lt (maxindex, curindex))
6351 maxindex = curindex, fold_p = curfold_p;
6353 if (fold_p)
6355 tree orig = maxindex;
6356 maxindex = fold_convert (sizetype, maxindex);
6357 overflow_p |= tree_int_cst_lt (maxindex, orig);
6361 else
6363 /* Make an error message unless that happened already. */
6364 if (initial_value != error_mark_node)
6365 failure = 1;
6368 else
6370 failure = 2;
6371 if (!do_default)
6372 return failure;
6375 type = *ptype;
6376 elt = TREE_TYPE (type);
6377 quals = TYPE_QUALS (strip_array_types (elt));
6378 if (quals == 0)
6379 unqual_elt = elt;
6380 else
6381 unqual_elt = c_build_qualified_type (elt, KEEP_QUAL_ADDR_SPACE (quals));
6383 /* Using build_distinct_type_copy and modifying things afterward instead
6384 of using build_array_type to create a new type preserves all of the
6385 TYPE_LANG_FLAG_? bits that the front end may have set. */
6386 main_type = build_distinct_type_copy (TYPE_MAIN_VARIANT (type));
6387 TREE_TYPE (main_type) = unqual_elt;
6388 TYPE_DOMAIN (main_type)
6389 = build_range_type (TREE_TYPE (maxindex),
6390 build_int_cst (TREE_TYPE (maxindex), 0), maxindex);
6391 TYPE_TYPELESS_STORAGE (main_type) = TYPE_TYPELESS_STORAGE (type);
6392 layout_type (main_type);
6394 /* Make sure we have the canonical MAIN_TYPE. */
6395 hashval_t hashcode = type_hash_canon_hash (main_type);
6396 main_type = type_hash_canon (hashcode, main_type);
6398 /* Fix the canonical type. */
6399 if (TYPE_STRUCTURAL_EQUALITY_P (TREE_TYPE (main_type))
6400 || TYPE_STRUCTURAL_EQUALITY_P (TYPE_DOMAIN (main_type)))
6401 SET_TYPE_STRUCTURAL_EQUALITY (main_type);
6402 else if (TYPE_CANONICAL (TREE_TYPE (main_type)) != TREE_TYPE (main_type)
6403 || (TYPE_CANONICAL (TYPE_DOMAIN (main_type))
6404 != TYPE_DOMAIN (main_type)))
6405 TYPE_CANONICAL (main_type)
6406 = build_array_type (TYPE_CANONICAL (TREE_TYPE (main_type)),
6407 TYPE_CANONICAL (TYPE_DOMAIN (main_type)),
6408 TYPE_TYPELESS_STORAGE (main_type));
6409 else
6410 TYPE_CANONICAL (main_type) = main_type;
6412 if (quals == 0)
6413 type = main_type;
6414 else
6415 type = c_build_qualified_type (main_type, quals);
6417 if (COMPLETE_TYPE_P (type)
6418 && TREE_CODE (TYPE_SIZE_UNIT (type)) == INTEGER_CST
6419 && (overflow_p || TREE_OVERFLOW (TYPE_SIZE_UNIT (type))))
6421 error ("size of array is too large");
6422 /* If we proceed with the array type as it is, we'll eventually
6423 crash in tree_to_[su]hwi(). */
6424 type = error_mark_node;
6427 *ptype = type;
6428 return failure;
6431 /* Like c_mark_addressable but don't check register qualifier. */
6432 void
6433 c_common_mark_addressable_vec (tree t)
6435 if (TREE_CODE (t) == C_MAYBE_CONST_EXPR)
6436 t = C_MAYBE_CONST_EXPR_EXPR (t);
6437 while (handled_component_p (t))
6438 t = TREE_OPERAND (t, 0);
6439 if (!VAR_P (t)
6440 && TREE_CODE (t) != PARM_DECL
6441 && TREE_CODE (t) != COMPOUND_LITERAL_EXPR)
6442 return;
6443 if (!VAR_P (t) || !DECL_HARD_REGISTER (t))
6444 TREE_ADDRESSABLE (t) = 1;
6449 /* Used to help initialize the builtin-types.def table. When a type of
6450 the correct size doesn't exist, use error_mark_node instead of NULL.
6451 The later results in segfaults even when a decl using the type doesn't
6452 get invoked. */
6454 tree
6455 builtin_type_for_size (int size, bool unsignedp)
6457 tree type = c_common_type_for_size (size, unsignedp);
6458 return type ? type : error_mark_node;
6461 /* A helper function for resolve_overloaded_builtin in resolving the
6462 overloaded __sync_ builtins. Returns a positive power of 2 if the
6463 first operand of PARAMS is a pointer to a supported data type.
6464 Returns 0 if an error is encountered.
6465 FETCH is true when FUNCTION is one of the _FETCH_OP_ or _OP_FETCH_
6466 built-ins. */
6468 static int
6469 sync_resolve_size (tree function, vec<tree, va_gc> *params, bool fetch)
6471 /* Type of the argument. */
6472 tree argtype;
6473 /* Type the argument points to. */
6474 tree type;
6475 int size;
6477 if (vec_safe_is_empty (params))
6479 error ("too few arguments to function %qE", function);
6480 return 0;
6483 argtype = type = TREE_TYPE ((*params)[0]);
6484 if (TREE_CODE (type) == ARRAY_TYPE && c_dialect_cxx ())
6486 /* Force array-to-pointer decay for C++. */
6487 (*params)[0] = default_conversion ((*params)[0]);
6488 type = TREE_TYPE ((*params)[0]);
6490 if (TREE_CODE (type) != POINTER_TYPE)
6491 goto incompatible;
6493 type = TREE_TYPE (type);
6494 if (!INTEGRAL_TYPE_P (type) && !POINTER_TYPE_P (type))
6495 goto incompatible;
6497 if (!COMPLETE_TYPE_P (type))
6498 goto incompatible;
6500 if (fetch && TREE_CODE (type) == BOOLEAN_TYPE)
6501 goto incompatible;
6503 size = tree_to_uhwi (TYPE_SIZE_UNIT (type));
6504 if (size == 1 || size == 2 || size == 4 || size == 8 || size == 16)
6505 return size;
6507 incompatible:
6508 /* Issue the diagnostic only if the argument is valid, otherwise
6509 it would be redundant at best and could be misleading. */
6510 if (argtype != error_mark_node)
6511 error ("operand type %qT is incompatible with argument %d of %qE",
6512 argtype, 1, function);
6513 return 0;
6516 /* A helper function for resolve_overloaded_builtin. Adds casts to
6517 PARAMS to make arguments match up with those of FUNCTION. Drops
6518 the variadic arguments at the end. Returns false if some error
6519 was encountered; true on success. */
6521 static bool
6522 sync_resolve_params (location_t loc, tree orig_function, tree function,
6523 vec<tree, va_gc> *params, bool orig_format)
6525 function_args_iterator iter;
6526 tree ptype;
6527 unsigned int parmnum;
6529 function_args_iter_init (&iter, TREE_TYPE (function));
6530 /* We've declared the implementation functions to use "volatile void *"
6531 as the pointer parameter, so we shouldn't get any complaints from the
6532 call to check_function_arguments what ever type the user used. */
6533 function_args_iter_next (&iter);
6534 ptype = TREE_TYPE (TREE_TYPE ((*params)[0]));
6535 ptype = TYPE_MAIN_VARIANT (ptype);
6537 /* For the rest of the values, we need to cast these to FTYPE, so that we
6538 don't get warnings for passing pointer types, etc. */
6539 parmnum = 0;
6540 while (1)
6542 tree val, arg_type;
6544 arg_type = function_args_iter_cond (&iter);
6545 /* XXX void_type_node belies the abstraction. */
6546 if (arg_type == void_type_node)
6547 break;
6549 ++parmnum;
6550 if (params->length () <= parmnum)
6552 error_at (loc, "too few arguments to function %qE", orig_function);
6553 return false;
6556 /* Only convert parameters if arg_type is unsigned integer type with
6557 new format sync routines, i.e. don't attempt to convert pointer
6558 arguments (e.g. EXPECTED argument of __atomic_compare_exchange_n),
6559 bool arguments (e.g. WEAK argument) or signed int arguments (memmodel
6560 kinds). */
6561 if (TREE_CODE (arg_type) == INTEGER_TYPE && TYPE_UNSIGNED (arg_type))
6563 /* Ideally for the first conversion we'd use convert_for_assignment
6564 so that we get warnings for anything that doesn't match the pointer
6565 type. This isn't portable across the C and C++ front ends atm. */
6566 val = (*params)[parmnum];
6567 val = convert (ptype, val);
6568 val = convert (arg_type, val);
6569 (*params)[parmnum] = val;
6572 function_args_iter_next (&iter);
6575 /* __atomic routines are not variadic. */
6576 if (!orig_format && params->length () != parmnum + 1)
6578 error_at (loc, "too many arguments to function %qE", orig_function);
6579 return false;
6582 /* The definition of these primitives is variadic, with the remaining
6583 being "an optional list of variables protected by the memory barrier".
6584 No clue what that's supposed to mean, precisely, but we consider all
6585 call-clobbered variables to be protected so we're safe. */
6586 params->truncate (parmnum + 1);
6588 return true;
6591 /* A helper function for resolve_overloaded_builtin. Adds a cast to
6592 RESULT to make it match the type of the first pointer argument in
6593 PARAMS. */
6595 static tree
6596 sync_resolve_return (tree first_param, tree result, bool orig_format)
6598 tree ptype = TREE_TYPE (TREE_TYPE (first_param));
6599 tree rtype = TREE_TYPE (result);
6600 ptype = TYPE_MAIN_VARIANT (ptype);
6602 /* New format doesn't require casting unless the types are the same size. */
6603 if (orig_format || tree_int_cst_equal (TYPE_SIZE (ptype), TYPE_SIZE (rtype)))
6604 return convert (ptype, result);
6605 else
6606 return result;
6609 /* This function verifies the PARAMS to generic atomic FUNCTION.
6610 It returns the size if all the parameters are the same size, otherwise
6611 0 is returned if the parameters are invalid. */
6613 static int
6614 get_atomic_generic_size (location_t loc, tree function,
6615 vec<tree, va_gc> *params)
6617 unsigned int n_param;
6618 unsigned int n_model;
6619 unsigned int x;
6620 int size_0;
6621 tree type_0;
6623 /* Determine the parameter makeup. */
6624 switch (DECL_FUNCTION_CODE (function))
6626 case BUILT_IN_ATOMIC_EXCHANGE:
6627 n_param = 4;
6628 n_model = 1;
6629 break;
6630 case BUILT_IN_ATOMIC_LOAD:
6631 case BUILT_IN_ATOMIC_STORE:
6632 n_param = 3;
6633 n_model = 1;
6634 break;
6635 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE:
6636 n_param = 6;
6637 n_model = 2;
6638 break;
6639 default:
6640 gcc_unreachable ();
6643 if (vec_safe_length (params) != n_param)
6645 error_at (loc, "incorrect number of arguments to function %qE", function);
6646 return 0;
6649 /* Get type of first parameter, and determine its size. */
6650 type_0 = TREE_TYPE ((*params)[0]);
6651 if (TREE_CODE (type_0) == ARRAY_TYPE && c_dialect_cxx ())
6653 /* Force array-to-pointer decay for C++. */
6654 (*params)[0] = default_conversion ((*params)[0]);
6655 type_0 = TREE_TYPE ((*params)[0]);
6657 if (TREE_CODE (type_0) != POINTER_TYPE || VOID_TYPE_P (TREE_TYPE (type_0)))
6659 error_at (loc, "argument 1 of %qE must be a non-void pointer type",
6660 function);
6661 return 0;
6664 /* Types must be compile time constant sizes. */
6665 if (TREE_CODE ((TYPE_SIZE_UNIT (TREE_TYPE (type_0)))) != INTEGER_CST)
6667 error_at (loc,
6668 "argument 1 of %qE must be a pointer to a constant size type",
6669 function);
6670 return 0;
6673 size_0 = tree_to_uhwi (TYPE_SIZE_UNIT (TREE_TYPE (type_0)));
6675 /* Zero size objects are not allowed. */
6676 if (size_0 == 0)
6678 error_at (loc,
6679 "argument 1 of %qE must be a pointer to a nonzero size object",
6680 function);
6681 return 0;
6684 /* Check each other parameter is a pointer and the same size. */
6685 for (x = 0; x < n_param - n_model; x++)
6687 int size;
6688 tree type = TREE_TYPE ((*params)[x]);
6689 /* __atomic_compare_exchange has a bool in the 4th position, skip it. */
6690 if (n_param == 6 && x == 3)
6691 continue;
6692 if (TREE_CODE (type) == ARRAY_TYPE && c_dialect_cxx ())
6694 /* Force array-to-pointer decay for C++. */
6695 (*params)[x] = default_conversion ((*params)[x]);
6696 type = TREE_TYPE ((*params)[x]);
6698 if (!POINTER_TYPE_P (type))
6700 error_at (loc, "argument %d of %qE must be a pointer type", x + 1,
6701 function);
6702 return 0;
6704 else if (TYPE_SIZE_UNIT (TREE_TYPE (type))
6705 && TREE_CODE ((TYPE_SIZE_UNIT (TREE_TYPE (type))))
6706 != INTEGER_CST)
6708 error_at (loc, "argument %d of %qE must be a pointer to a constant "
6709 "size type", x + 1, function);
6710 return 0;
6712 else if (FUNCTION_POINTER_TYPE_P (type))
6714 error_at (loc, "argument %d of %qE must not be a pointer to a "
6715 "function", x + 1, function);
6716 return 0;
6718 tree type_size = TYPE_SIZE_UNIT (TREE_TYPE (type));
6719 size = type_size ? tree_to_uhwi (type_size) : 0;
6720 if (size != size_0)
6722 error_at (loc, "size mismatch in argument %d of %qE", x + 1,
6723 function);
6724 return 0;
6728 /* Check memory model parameters for validity. */
6729 for (x = n_param - n_model ; x < n_param; x++)
6731 tree p = (*params)[x];
6732 if (TREE_CODE (p) == INTEGER_CST)
6734 /* memmodel_base masks the low 16 bits, thus ignore any bits above
6735 it by using TREE_INT_CST_LOW instead of tree_to_*hwi. Those high
6736 bits will be checked later during expansion in target specific
6737 way. */
6738 if (memmodel_base (TREE_INT_CST_LOW (p)) >= MEMMODEL_LAST)
6739 warning_at (loc, OPT_Winvalid_memory_model,
6740 "invalid memory model argument %d of %qE", x + 1,
6741 function);
6743 else
6744 if (!INTEGRAL_TYPE_P (TREE_TYPE (p)))
6746 error_at (loc, "non-integer memory model argument %d of %qE", x + 1,
6747 function);
6748 return 0;
6752 return size_0;
6756 /* This will take an __atomic_ generic FUNCTION call, and add a size parameter N
6757 at the beginning of the parameter list PARAMS representing the size of the
6758 objects. This is to match the library ABI requirement. LOC is the location
6759 of the function call.
6760 The new function is returned if it needed rebuilding, otherwise NULL_TREE is
6761 returned to allow the external call to be constructed. */
6763 static tree
6764 add_atomic_size_parameter (unsigned n, location_t loc, tree function,
6765 vec<tree, va_gc> *params)
6767 tree size_node;
6769 /* Insert a SIZE_T parameter as the first param. If there isn't
6770 enough space, allocate a new vector and recursively re-build with that. */
6771 if (!params->space (1))
6773 unsigned int z, len;
6774 vec<tree, va_gc> *v;
6775 tree f;
6777 len = params->length ();
6778 vec_alloc (v, len + 1);
6779 v->quick_push (build_int_cst (size_type_node, n));
6780 for (z = 0; z < len; z++)
6781 v->quick_push ((*params)[z]);
6782 f = build_function_call_vec (loc, vNULL, function, v, NULL);
6783 vec_free (v);
6784 return f;
6787 /* Add the size parameter and leave as a function call for processing. */
6788 size_node = build_int_cst (size_type_node, n);
6789 params->quick_insert (0, size_node);
6790 return NULL_TREE;
6794 /* Return whether atomic operations for naturally aligned N-byte
6795 arguments are supported, whether inline or through libatomic. */
6796 static bool
6797 atomic_size_supported_p (int n)
6799 switch (n)
6801 case 1:
6802 case 2:
6803 case 4:
6804 case 8:
6805 return true;
6807 case 16:
6808 return targetm.scalar_mode_supported_p (TImode);
6810 default:
6811 return false;
6815 /* This will process an __atomic_exchange function call, determine whether it
6816 needs to be mapped to the _N variation, or turned into a library call.
6817 LOC is the location of the builtin call.
6818 FUNCTION is the DECL that has been invoked;
6819 PARAMS is the argument list for the call. The return value is non-null
6820 TRUE is returned if it is translated into the proper format for a call to the
6821 external library, and NEW_RETURN is set the tree for that function.
6822 FALSE is returned if processing for the _N variation is required, and
6823 NEW_RETURN is set to the return value the result is copied into. */
6824 static bool
6825 resolve_overloaded_atomic_exchange (location_t loc, tree function,
6826 vec<tree, va_gc> *params, tree *new_return)
6828 tree p0, p1, p2, p3;
6829 tree I_type, I_type_ptr;
6830 int n = get_atomic_generic_size (loc, function, params);
6832 /* Size of 0 is an error condition. */
6833 if (n == 0)
6835 *new_return = error_mark_node;
6836 return true;
6839 /* If not a lock-free size, change to the library generic format. */
6840 if (!atomic_size_supported_p (n))
6842 *new_return = add_atomic_size_parameter (n, loc, function, params);
6843 return true;
6846 /* Otherwise there is a lockfree match, transform the call from:
6847 void fn(T* mem, T* desired, T* return, model)
6848 into
6849 *return = (T) (fn (In* mem, (In) *desired, model)) */
6851 p0 = (*params)[0];
6852 p1 = (*params)[1];
6853 p2 = (*params)[2];
6854 p3 = (*params)[3];
6856 /* Create pointer to appropriate size. */
6857 I_type = builtin_type_for_size (BITS_PER_UNIT * n, 1);
6858 I_type_ptr = build_pointer_type (I_type);
6860 /* Convert object pointer to required type. */
6861 p0 = build1 (VIEW_CONVERT_EXPR, I_type_ptr, p0);
6862 (*params)[0] = p0;
6863 /* Convert new value to required type, and dereference it. */
6864 p1 = build_indirect_ref (loc, p1, RO_UNARY_STAR);
6865 p1 = build1 (VIEW_CONVERT_EXPR, I_type, p1);
6866 (*params)[1] = p1;
6868 /* Move memory model to the 3rd position, and end param list. */
6869 (*params)[2] = p3;
6870 params->truncate (3);
6872 /* Convert return pointer and dereference it for later assignment. */
6873 *new_return = build_indirect_ref (loc, p2, RO_UNARY_STAR);
6875 return false;
6879 /* This will process an __atomic_compare_exchange function call, determine
6880 whether it needs to be mapped to the _N variation, or turned into a lib call.
6881 LOC is the location of the builtin call.
6882 FUNCTION is the DECL that has been invoked;
6883 PARAMS is the argument list for the call. The return value is non-null
6884 TRUE is returned if it is translated into the proper format for a call to the
6885 external library, and NEW_RETURN is set the tree for that function.
6886 FALSE is returned if processing for the _N variation is required. */
6888 static bool
6889 resolve_overloaded_atomic_compare_exchange (location_t loc, tree function,
6890 vec<tree, va_gc> *params,
6891 tree *new_return)
6893 tree p0, p1, p2;
6894 tree I_type, I_type_ptr;
6895 int n = get_atomic_generic_size (loc, function, params);
6897 /* Size of 0 is an error condition. */
6898 if (n == 0)
6900 *new_return = error_mark_node;
6901 return true;
6904 /* If not a lock-free size, change to the library generic format. */
6905 if (!atomic_size_supported_p (n))
6907 /* The library generic format does not have the weak parameter, so
6908 remove it from the param list. Since a parameter has been removed,
6909 we can be sure that there is room for the SIZE_T parameter, meaning
6910 there will not be a recursive rebuilding of the parameter list, so
6911 there is no danger this will be done twice. */
6912 if (n > 0)
6914 (*params)[3] = (*params)[4];
6915 (*params)[4] = (*params)[5];
6916 params->truncate (5);
6918 *new_return = add_atomic_size_parameter (n, loc, function, params);
6919 return true;
6922 /* Otherwise, there is a match, so the call needs to be transformed from:
6923 bool fn(T* mem, T* desired, T* return, weak, success, failure)
6924 into
6925 bool fn ((In *)mem, (In *)expected, (In) *desired, weak, succ, fail) */
6927 p0 = (*params)[0];
6928 p1 = (*params)[1];
6929 p2 = (*params)[2];
6931 /* Create pointer to appropriate size. */
6932 I_type = builtin_type_for_size (BITS_PER_UNIT * n, 1);
6933 I_type_ptr = build_pointer_type (I_type);
6935 /* Convert object pointer to required type. */
6936 p0 = build1 (VIEW_CONVERT_EXPR, I_type_ptr, p0);
6937 (*params)[0] = p0;
6939 /* Convert expected pointer to required type. */
6940 p1 = build1 (VIEW_CONVERT_EXPR, I_type_ptr, p1);
6941 (*params)[1] = p1;
6943 /* Convert desired value to required type, and dereference it. */
6944 p2 = build_indirect_ref (loc, p2, RO_UNARY_STAR);
6945 p2 = build1 (VIEW_CONVERT_EXPR, I_type, p2);
6946 (*params)[2] = p2;
6948 /* The rest of the parameters are fine. NULL means no special return value
6949 processing.*/
6950 *new_return = NULL;
6951 return false;
6955 /* This will process an __atomic_load function call, determine whether it
6956 needs to be mapped to the _N variation, or turned into a library call.
6957 LOC is the location of the builtin call.
6958 FUNCTION is the DECL that has been invoked;
6959 PARAMS is the argument list for the call. The return value is non-null
6960 TRUE is returned if it is translated into the proper format for a call to the
6961 external library, and NEW_RETURN is set the tree for that function.
6962 FALSE is returned if processing for the _N variation is required, and
6963 NEW_RETURN is set to the return value the result is copied into. */
6965 static bool
6966 resolve_overloaded_atomic_load (location_t loc, tree function,
6967 vec<tree, va_gc> *params, tree *new_return)
6969 tree p0, p1, p2;
6970 tree I_type, I_type_ptr;
6971 int n = get_atomic_generic_size (loc, function, params);
6973 /* Size of 0 is an error condition. */
6974 if (n == 0)
6976 *new_return = error_mark_node;
6977 return true;
6980 /* If not a lock-free size, change to the library generic format. */
6981 if (!atomic_size_supported_p (n))
6983 *new_return = add_atomic_size_parameter (n, loc, function, params);
6984 return true;
6987 /* Otherwise, there is a match, so the call needs to be transformed from:
6988 void fn(T* mem, T* return, model)
6989 into
6990 *return = (T) (fn ((In *) mem, model)) */
6992 p0 = (*params)[0];
6993 p1 = (*params)[1];
6994 p2 = (*params)[2];
6996 /* Create pointer to appropriate size. */
6997 I_type = builtin_type_for_size (BITS_PER_UNIT * n, 1);
6998 I_type_ptr = build_pointer_type (I_type);
7000 /* Convert object pointer to required type. */
7001 p0 = build1 (VIEW_CONVERT_EXPR, I_type_ptr, p0);
7002 (*params)[0] = p0;
7004 /* Move memory model to the 2nd position, and end param list. */
7005 (*params)[1] = p2;
7006 params->truncate (2);
7008 /* Convert return pointer and dereference it for later assignment. */
7009 *new_return = build_indirect_ref (loc, p1, RO_UNARY_STAR);
7011 return false;
7015 /* This will process an __atomic_store function call, determine whether it
7016 needs to be mapped to the _N variation, or turned into a library call.
7017 LOC is the location of the builtin call.
7018 FUNCTION is the DECL that has been invoked;
7019 PARAMS is the argument list for the call. The return value is non-null
7020 TRUE is returned if it is translated into the proper format for a call to the
7021 external library, and NEW_RETURN is set the tree for that function.
7022 FALSE is returned if processing for the _N variation is required, and
7023 NEW_RETURN is set to the return value the result is copied into. */
7025 static bool
7026 resolve_overloaded_atomic_store (location_t loc, tree function,
7027 vec<tree, va_gc> *params, tree *new_return)
7029 tree p0, p1;
7030 tree I_type, I_type_ptr;
7031 int n = get_atomic_generic_size (loc, function, params);
7033 /* Size of 0 is an error condition. */
7034 if (n == 0)
7036 *new_return = error_mark_node;
7037 return true;
7040 /* If not a lock-free size, change to the library generic format. */
7041 if (!atomic_size_supported_p (n))
7043 *new_return = add_atomic_size_parameter (n, loc, function, params);
7044 return true;
7047 /* Otherwise, there is a match, so the call needs to be transformed from:
7048 void fn(T* mem, T* value, model)
7049 into
7050 fn ((In *) mem, (In) *value, model) */
7052 p0 = (*params)[0];
7053 p1 = (*params)[1];
7055 /* Create pointer to appropriate size. */
7056 I_type = builtin_type_for_size (BITS_PER_UNIT * n, 1);
7057 I_type_ptr = build_pointer_type (I_type);
7059 /* Convert object pointer to required type. */
7060 p0 = build1 (VIEW_CONVERT_EXPR, I_type_ptr, p0);
7061 (*params)[0] = p0;
7063 /* Convert new value to required type, and dereference it. */
7064 p1 = build_indirect_ref (loc, p1, RO_UNARY_STAR);
7065 p1 = build1 (VIEW_CONVERT_EXPR, I_type, p1);
7066 (*params)[1] = p1;
7068 /* The memory model is in the right spot already. Return is void. */
7069 *new_return = NULL_TREE;
7071 return false;
7075 /* Some builtin functions are placeholders for other expressions. This
7076 function should be called immediately after parsing the call expression
7077 before surrounding code has committed to the type of the expression.
7079 LOC is the location of the builtin call.
7081 FUNCTION is the DECL that has been invoked; it is known to be a builtin.
7082 PARAMS is the argument list for the call. The return value is non-null
7083 when expansion is complete, and null if normal processing should
7084 continue. */
7086 tree
7087 resolve_overloaded_builtin (location_t loc, tree function,
7088 vec<tree, va_gc> *params)
7090 enum built_in_function orig_code = DECL_FUNCTION_CODE (function);
7092 /* Is function one of the _FETCH_OP_ or _OP_FETCH_ built-ins?
7093 Those are not valid to call with a pointer to _Bool (or C++ bool)
7094 and so must be rejected. */
7095 bool fetch_op = true;
7096 bool orig_format = true;
7097 tree new_return = NULL_TREE;
7099 switch (DECL_BUILT_IN_CLASS (function))
7101 case BUILT_IN_NORMAL:
7102 break;
7103 case BUILT_IN_MD:
7104 if (targetm.resolve_overloaded_builtin)
7105 return targetm.resolve_overloaded_builtin (loc, function, params);
7106 else
7107 return NULL_TREE;
7108 default:
7109 return NULL_TREE;
7112 /* Handle BUILT_IN_NORMAL here. */
7113 switch (orig_code)
7115 case BUILT_IN_ATOMIC_EXCHANGE:
7116 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE:
7117 case BUILT_IN_ATOMIC_LOAD:
7118 case BUILT_IN_ATOMIC_STORE:
7120 /* Handle these 4 together so that they can fall through to the next
7121 case if the call is transformed to an _N variant. */
7122 switch (orig_code)
7124 case BUILT_IN_ATOMIC_EXCHANGE:
7126 if (resolve_overloaded_atomic_exchange (loc, function, params,
7127 &new_return))
7128 return new_return;
7129 /* Change to the _N variant. */
7130 orig_code = BUILT_IN_ATOMIC_EXCHANGE_N;
7131 break;
7134 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE:
7136 if (resolve_overloaded_atomic_compare_exchange (loc, function,
7137 params,
7138 &new_return))
7139 return new_return;
7140 /* Change to the _N variant. */
7141 orig_code = BUILT_IN_ATOMIC_COMPARE_EXCHANGE_N;
7142 break;
7144 case BUILT_IN_ATOMIC_LOAD:
7146 if (resolve_overloaded_atomic_load (loc, function, params,
7147 &new_return))
7148 return new_return;
7149 /* Change to the _N variant. */
7150 orig_code = BUILT_IN_ATOMIC_LOAD_N;
7151 break;
7153 case BUILT_IN_ATOMIC_STORE:
7155 if (resolve_overloaded_atomic_store (loc, function, params,
7156 &new_return))
7157 return new_return;
7158 /* Change to the _N variant. */
7159 orig_code = BUILT_IN_ATOMIC_STORE_N;
7160 break;
7162 default:
7163 gcc_unreachable ();
7166 /* FALLTHRU */
7167 case BUILT_IN_ATOMIC_EXCHANGE_N:
7168 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_N:
7169 case BUILT_IN_ATOMIC_LOAD_N:
7170 case BUILT_IN_ATOMIC_STORE_N:
7171 fetch_op = false;
7172 /* FALLTHRU */
7173 case BUILT_IN_ATOMIC_ADD_FETCH_N:
7174 case BUILT_IN_ATOMIC_SUB_FETCH_N:
7175 case BUILT_IN_ATOMIC_AND_FETCH_N:
7176 case BUILT_IN_ATOMIC_NAND_FETCH_N:
7177 case BUILT_IN_ATOMIC_XOR_FETCH_N:
7178 case BUILT_IN_ATOMIC_OR_FETCH_N:
7179 case BUILT_IN_ATOMIC_FETCH_ADD_N:
7180 case BUILT_IN_ATOMIC_FETCH_SUB_N:
7181 case BUILT_IN_ATOMIC_FETCH_AND_N:
7182 case BUILT_IN_ATOMIC_FETCH_NAND_N:
7183 case BUILT_IN_ATOMIC_FETCH_XOR_N:
7184 case BUILT_IN_ATOMIC_FETCH_OR_N:
7185 orig_format = false;
7186 /* FALLTHRU */
7187 case BUILT_IN_SYNC_FETCH_AND_ADD_N:
7188 case BUILT_IN_SYNC_FETCH_AND_SUB_N:
7189 case BUILT_IN_SYNC_FETCH_AND_OR_N:
7190 case BUILT_IN_SYNC_FETCH_AND_AND_N:
7191 case BUILT_IN_SYNC_FETCH_AND_XOR_N:
7192 case BUILT_IN_SYNC_FETCH_AND_NAND_N:
7193 case BUILT_IN_SYNC_ADD_AND_FETCH_N:
7194 case BUILT_IN_SYNC_SUB_AND_FETCH_N:
7195 case BUILT_IN_SYNC_OR_AND_FETCH_N:
7196 case BUILT_IN_SYNC_AND_AND_FETCH_N:
7197 case BUILT_IN_SYNC_XOR_AND_FETCH_N:
7198 case BUILT_IN_SYNC_NAND_AND_FETCH_N:
7199 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_N:
7200 case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_N:
7201 case BUILT_IN_SYNC_LOCK_TEST_AND_SET_N:
7202 case BUILT_IN_SYNC_LOCK_RELEASE_N:
7204 /* The following are not _FETCH_OPs and must be accepted with
7205 pointers to _Bool (or C++ bool). */
7206 if (fetch_op)
7207 fetch_op =
7208 (orig_code != BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_N
7209 && orig_code != BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_N
7210 && orig_code != BUILT_IN_SYNC_LOCK_TEST_AND_SET_N
7211 && orig_code != BUILT_IN_SYNC_LOCK_RELEASE_N);
7213 int n = sync_resolve_size (function, params, fetch_op);
7214 tree new_function, first_param, result;
7215 enum built_in_function fncode;
7217 if (n == 0)
7218 return error_mark_node;
7220 fncode = (enum built_in_function)((int)orig_code + exact_log2 (n) + 1);
7221 new_function = builtin_decl_explicit (fncode);
7222 if (!sync_resolve_params (loc, function, new_function, params,
7223 orig_format))
7224 return error_mark_node;
7226 first_param = (*params)[0];
7227 result = build_function_call_vec (loc, vNULL, new_function, params,
7228 NULL);
7229 if (result == error_mark_node)
7230 return result;
7231 if (orig_code != BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_N
7232 && orig_code != BUILT_IN_SYNC_LOCK_RELEASE_N
7233 && orig_code != BUILT_IN_ATOMIC_STORE_N
7234 && orig_code != BUILT_IN_ATOMIC_COMPARE_EXCHANGE_N)
7235 result = sync_resolve_return (first_param, result, orig_format);
7237 if (fetch_op)
7238 /* Prevent -Wunused-value warning. */
7239 TREE_USED (result) = true;
7241 /* If new_return is set, assign function to that expr and cast the
7242 result to void since the generic interface returned void. */
7243 if (new_return)
7245 /* Cast function result from I{1,2,4,8,16} to the required type. */
7246 result = build1 (VIEW_CONVERT_EXPR, TREE_TYPE (new_return), result);
7247 result = build2 (MODIFY_EXPR, TREE_TYPE (new_return), new_return,
7248 result);
7249 TREE_SIDE_EFFECTS (result) = 1;
7250 protected_set_expr_location (result, loc);
7251 result = convert (void_type_node, result);
7253 return result;
7256 default:
7257 return NULL_TREE;
7261 /* vector_types_compatible_elements_p is used in type checks of vectors
7262 values used as operands of binary operators. Where it returns true, and
7263 the other checks of the caller succeed (being vector types in he first
7264 place, and matching number of elements), we can just treat the types
7265 as essentially the same.
7266 Contrast with vector_targets_convertible_p, which is used for vector
7267 pointer types, and vector_types_convertible_p, which will allow
7268 language-specific matches under the control of flag_lax_vector_conversions,
7269 and might still require a conversion. */
7270 /* True if vector types T1 and T2 can be inputs to the same binary
7271 operator without conversion.
7272 We don't check the overall vector size here because some of our callers
7273 want to give different error messages when the vectors are compatible
7274 except for the element count. */
7276 bool
7277 vector_types_compatible_elements_p (tree t1, tree t2)
7279 bool opaque = TYPE_VECTOR_OPAQUE (t1) || TYPE_VECTOR_OPAQUE (t2);
7280 t1 = TREE_TYPE (t1);
7281 t2 = TREE_TYPE (t2);
7283 enum tree_code c1 = TREE_CODE (t1), c2 = TREE_CODE (t2);
7285 gcc_assert ((c1 == INTEGER_TYPE || c1 == REAL_TYPE || c1 == FIXED_POINT_TYPE)
7286 && (c2 == INTEGER_TYPE || c2 == REAL_TYPE
7287 || c2 == FIXED_POINT_TYPE));
7289 t1 = c_common_signed_type (t1);
7290 t2 = c_common_signed_type (t2);
7291 /* Equality works here because c_common_signed_type uses
7292 TYPE_MAIN_VARIANT. */
7293 if (t1 == t2)
7294 return true;
7295 if (opaque && c1 == c2
7296 && (c1 == INTEGER_TYPE || c1 == REAL_TYPE)
7297 && TYPE_PRECISION (t1) == TYPE_PRECISION (t2))
7298 return true;
7299 return false;
7302 /* Check for missing format attributes on function pointers. LTYPE is
7303 the new type or left-hand side type. RTYPE is the old type or
7304 right-hand side type. Returns TRUE if LTYPE is missing the desired
7305 attribute. */
7307 bool
7308 check_missing_format_attribute (tree ltype, tree rtype)
7310 tree const ttr = TREE_TYPE (rtype), ttl = TREE_TYPE (ltype);
7311 tree ra;
7313 for (ra = TYPE_ATTRIBUTES (ttr); ra; ra = TREE_CHAIN (ra))
7314 if (is_attribute_p ("format", TREE_PURPOSE (ra)))
7315 break;
7316 if (ra)
7318 tree la;
7319 for (la = TYPE_ATTRIBUTES (ttl); la; la = TREE_CHAIN (la))
7320 if (is_attribute_p ("format", TREE_PURPOSE (la)))
7321 break;
7322 return !la;
7324 else
7325 return false;
7328 /* Setup a TYPE_DECL node as a typedef representation.
7330 X is a TYPE_DECL for a typedef statement. Create a brand new
7331 ..._TYPE node (which will be just a variant of the existing
7332 ..._TYPE node with identical properties) and then install X
7333 as the TYPE_NAME of this brand new (duplicate) ..._TYPE node.
7335 The whole point here is to end up with a situation where each
7336 and every ..._TYPE node the compiler creates will be uniquely
7337 associated with AT MOST one node representing a typedef name.
7338 This way, even though the compiler substitutes corresponding
7339 ..._TYPE nodes for TYPE_DECL (i.e. "typedef name") nodes very
7340 early on, later parts of the compiler can always do the reverse
7341 translation and get back the corresponding typedef name. For
7342 example, given:
7344 typedef struct S MY_TYPE;
7345 MY_TYPE object;
7347 Later parts of the compiler might only know that `object' was of
7348 type `struct S' if it were not for code just below. With this
7349 code however, later parts of the compiler see something like:
7351 struct S' == struct S
7352 typedef struct S' MY_TYPE;
7353 struct S' object;
7355 And they can then deduce (from the node for type struct S') that
7356 the original object declaration was:
7358 MY_TYPE object;
7360 Being able to do this is important for proper support of protoize,
7361 and also for generating precise symbolic debugging information
7362 which takes full account of the programmer's (typedef) vocabulary.
7364 Obviously, we don't want to generate a duplicate ..._TYPE node if
7365 the TYPE_DECL node that we are now processing really represents a
7366 standard built-in type. */
7368 void
7369 set_underlying_type (tree x)
7371 if (x == error_mark_node)
7372 return;
7373 if (DECL_IS_BUILTIN (x) && TREE_CODE (TREE_TYPE (x)) != ARRAY_TYPE)
7375 if (TYPE_NAME (TREE_TYPE (x)) == 0)
7376 TYPE_NAME (TREE_TYPE (x)) = x;
7378 else if (TREE_TYPE (x) != error_mark_node
7379 && DECL_ORIGINAL_TYPE (x) == NULL_TREE)
7381 tree tt = TREE_TYPE (x);
7382 DECL_ORIGINAL_TYPE (x) = tt;
7383 tt = build_variant_type_copy (tt);
7384 TYPE_STUB_DECL (tt) = TYPE_STUB_DECL (DECL_ORIGINAL_TYPE (x));
7385 TYPE_NAME (tt) = x;
7387 /* Mark the type as used only when its type decl is decorated
7388 with attribute unused. */
7389 if (lookup_attribute ("unused", DECL_ATTRIBUTES (x)))
7390 TREE_USED (tt) = 1;
7392 TREE_TYPE (x) = tt;
7396 /* Record the types used by the current global variable declaration
7397 being parsed, so that we can decide later to emit their debug info.
7398 Those types are in types_used_by_cur_var_decl, and we are going to
7399 store them in the types_used_by_vars_hash hash table.
7400 DECL is the declaration of the global variable that has been parsed. */
7402 void
7403 record_types_used_by_current_var_decl (tree decl)
7405 gcc_assert (decl && DECL_P (decl) && TREE_STATIC (decl));
7407 while (types_used_by_cur_var_decl && !types_used_by_cur_var_decl->is_empty ())
7409 tree type = types_used_by_cur_var_decl->pop ();
7410 types_used_by_var_decl_insert (type, decl);
7414 /* The C and C++ parsers both use vectors to hold function arguments.
7415 For efficiency, we keep a cache of unused vectors. This is the
7416 cache. */
7418 typedef vec<tree, va_gc> *tree_gc_vec;
7419 static GTY((deletable)) vec<tree_gc_vec, va_gc> *tree_vector_cache;
7421 /* Return a new vector from the cache. If the cache is empty,
7422 allocate a new vector. These vectors are GC'ed, so it is OK if the
7423 pointer is not released.. */
7425 vec<tree, va_gc> *
7426 make_tree_vector (void)
7428 if (tree_vector_cache && !tree_vector_cache->is_empty ())
7429 return tree_vector_cache->pop ();
7430 else
7432 /* Passing 0 to vec::alloc returns NULL, and our callers require
7433 that we always return a non-NULL value. The vector code uses
7434 4 when growing a NULL vector, so we do too. */
7435 vec<tree, va_gc> *v;
7436 vec_alloc (v, 4);
7437 return v;
7441 /* Release a vector of trees back to the cache. */
7443 void
7444 release_tree_vector (vec<tree, va_gc> *vec)
7446 if (vec != NULL)
7448 vec->truncate (0);
7449 vec_safe_push (tree_vector_cache, vec);
7453 /* Get a new tree vector holding a single tree. */
7455 vec<tree, va_gc> *
7456 make_tree_vector_single (tree t)
7458 vec<tree, va_gc> *ret = make_tree_vector ();
7459 ret->quick_push (t);
7460 return ret;
7463 /* Get a new tree vector of the TREE_VALUEs of a TREE_LIST chain. */
7465 vec<tree, va_gc> *
7466 make_tree_vector_from_list (tree list)
7468 vec<tree, va_gc> *ret = make_tree_vector ();
7469 for (; list; list = TREE_CHAIN (list))
7470 vec_safe_push (ret, TREE_VALUE (list));
7471 return ret;
7474 /* Get a new tree vector of the values of a CONSTRUCTOR. */
7476 vec<tree, va_gc> *
7477 make_tree_vector_from_ctor (tree ctor)
7479 vec<tree,va_gc> *ret = make_tree_vector ();
7480 vec_safe_reserve (ret, CONSTRUCTOR_NELTS (ctor));
7481 for (unsigned i = 0; i < CONSTRUCTOR_NELTS (ctor); ++i)
7482 ret->quick_push (CONSTRUCTOR_ELT (ctor, i)->value);
7483 return ret;
7486 /* Get a new tree vector which is a copy of an existing one. */
7488 vec<tree, va_gc> *
7489 make_tree_vector_copy (const vec<tree, va_gc> *orig)
7491 vec<tree, va_gc> *ret;
7492 unsigned int ix;
7493 tree t;
7495 ret = make_tree_vector ();
7496 vec_safe_reserve (ret, vec_safe_length (orig));
7497 FOR_EACH_VEC_SAFE_ELT (orig, ix, t)
7498 ret->quick_push (t);
7499 return ret;
7502 /* Return true if KEYWORD starts a type specifier. */
7504 bool
7505 keyword_begins_type_specifier (enum rid keyword)
7507 switch (keyword)
7509 case RID_AUTO_TYPE:
7510 case RID_INT:
7511 case RID_CHAR:
7512 case RID_FLOAT:
7513 case RID_DOUBLE:
7514 case RID_VOID:
7515 case RID_UNSIGNED:
7516 case RID_LONG:
7517 case RID_SHORT:
7518 case RID_SIGNED:
7519 CASE_RID_FLOATN_NX:
7520 case RID_DFLOAT32:
7521 case RID_DFLOAT64:
7522 case RID_DFLOAT128:
7523 case RID_FRACT:
7524 case RID_ACCUM:
7525 case RID_BOOL:
7526 case RID_WCHAR:
7527 case RID_CHAR16:
7528 case RID_CHAR32:
7529 case RID_SAT:
7530 case RID_COMPLEX:
7531 case RID_TYPEOF:
7532 case RID_STRUCT:
7533 case RID_CLASS:
7534 case RID_UNION:
7535 case RID_ENUM:
7536 return true;
7537 default:
7538 if (keyword >= RID_FIRST_INT_N
7539 && keyword < RID_FIRST_INT_N + NUM_INT_N_ENTS
7540 && int_n_enabled_p[keyword-RID_FIRST_INT_N])
7541 return true;
7542 return false;
7546 /* Return true if KEYWORD names a type qualifier. */
7548 bool
7549 keyword_is_type_qualifier (enum rid keyword)
7551 switch (keyword)
7553 case RID_CONST:
7554 case RID_VOLATILE:
7555 case RID_RESTRICT:
7556 case RID_ATOMIC:
7557 return true;
7558 default:
7559 return false;
7563 /* Return true if KEYWORD names a storage class specifier.
7565 RID_TYPEDEF is not included in this list despite `typedef' being
7566 listed in C99 6.7.1.1. 6.7.1.3 indicates that `typedef' is listed as
7567 such for syntactic convenience only. */
7569 bool
7570 keyword_is_storage_class_specifier (enum rid keyword)
7572 switch (keyword)
7574 case RID_STATIC:
7575 case RID_EXTERN:
7576 case RID_REGISTER:
7577 case RID_AUTO:
7578 case RID_MUTABLE:
7579 case RID_THREAD:
7580 return true;
7581 default:
7582 return false;
7586 /* Return true if KEYWORD names a function-specifier [dcl.fct.spec]. */
7588 static bool
7589 keyword_is_function_specifier (enum rid keyword)
7591 switch (keyword)
7593 case RID_INLINE:
7594 case RID_NORETURN:
7595 case RID_VIRTUAL:
7596 case RID_EXPLICIT:
7597 return true;
7598 default:
7599 return false;
7603 /* Return true if KEYWORD names a decl-specifier [dcl.spec] or a
7604 declaration-specifier (C99 6.7). */
7606 bool
7607 keyword_is_decl_specifier (enum rid keyword)
7609 if (keyword_is_storage_class_specifier (keyword)
7610 || keyword_is_type_qualifier (keyword)
7611 || keyword_is_function_specifier (keyword))
7612 return true;
7614 switch (keyword)
7616 case RID_TYPEDEF:
7617 case RID_FRIEND:
7618 case RID_CONSTEXPR:
7619 return true;
7620 default:
7621 return false;
7625 /* Initialize language-specific-bits of tree_contains_struct. */
7627 void
7628 c_common_init_ts (void)
7630 MARK_TS_TYPED (C_MAYBE_CONST_EXPR);
7631 MARK_TS_TYPED (EXCESS_PRECISION_EXPR);
7634 /* Build a user-defined numeric literal out of an integer constant type VALUE
7635 with identifier SUFFIX. */
7637 tree
7638 build_userdef_literal (tree suffix_id, tree value,
7639 enum overflow_type overflow, tree num_string)
7641 tree literal = make_node (USERDEF_LITERAL);
7642 USERDEF_LITERAL_SUFFIX_ID (literal) = suffix_id;
7643 USERDEF_LITERAL_VALUE (literal) = value;
7644 USERDEF_LITERAL_OVERFLOW (literal) = overflow;
7645 USERDEF_LITERAL_NUM_STRING (literal) = num_string;
7646 return literal;
7649 /* For vector[index], convert the vector to an array of the underlying type.
7650 Return true if the resulting ARRAY_REF should not be an lvalue. */
7652 bool
7653 convert_vector_to_array_for_subscript (location_t loc,
7654 tree *vecp, tree index)
7656 bool ret = false;
7657 if (VECTOR_TYPE_P (TREE_TYPE (*vecp)))
7659 tree type = TREE_TYPE (*vecp);
7661 ret = !lvalue_p (*vecp);
7663 if (TREE_CODE (index) == INTEGER_CST)
7664 if (!tree_fits_uhwi_p (index)
7665 || maybe_ge (tree_to_uhwi (index), TYPE_VECTOR_SUBPARTS (type)))
7666 warning_at (loc, OPT_Warray_bounds, "index value is out of bound");
7668 /* We are building an ARRAY_REF so mark the vector as addressable
7669 to not run into the gimplifiers premature setting of DECL_GIMPLE_REG_P
7670 for function parameters. */
7671 c_common_mark_addressable_vec (*vecp);
7673 *vecp = build1 (VIEW_CONVERT_EXPR,
7674 build_array_type_nelts (TREE_TYPE (type),
7675 TYPE_VECTOR_SUBPARTS (type)),
7676 *vecp);
7678 return ret;
7681 /* Determine which of the operands, if any, is a scalar that needs to be
7682 converted to a vector, for the range of operations. */
7683 enum stv_conv
7684 scalar_to_vector (location_t loc, enum tree_code code, tree op0, tree op1,
7685 bool complain)
7687 tree type0 = TREE_TYPE (op0);
7688 tree type1 = TREE_TYPE (op1);
7689 bool integer_only_op = false;
7690 enum stv_conv ret = stv_firstarg;
7692 gcc_assert (VECTOR_TYPE_P (type0) || VECTOR_TYPE_P (type1));
7693 switch (code)
7695 /* Most GENERIC binary expressions require homogeneous arguments.
7696 LSHIFT_EXPR and RSHIFT_EXPR are exceptions and accept a first
7697 argument that is a vector and a second one that is a scalar, so
7698 we never return stv_secondarg for them. */
7699 case RSHIFT_EXPR:
7700 case LSHIFT_EXPR:
7701 if (TREE_CODE (type0) == INTEGER_TYPE
7702 && TREE_CODE (TREE_TYPE (type1)) == INTEGER_TYPE)
7704 if (unsafe_conversion_p (loc, TREE_TYPE (type1), op0,
7705 NULL_TREE, false))
7707 if (complain)
7708 error_at (loc, "conversion of scalar %qT to vector %qT "
7709 "involves truncation", type0, type1);
7710 return stv_error;
7712 else
7713 return stv_firstarg;
7715 break;
7717 case BIT_IOR_EXPR:
7718 case BIT_XOR_EXPR:
7719 case BIT_AND_EXPR:
7720 integer_only_op = true;
7721 /* fall through */
7723 case VEC_COND_EXPR:
7725 case PLUS_EXPR:
7726 case MINUS_EXPR:
7727 case MULT_EXPR:
7728 case TRUNC_DIV_EXPR:
7729 case CEIL_DIV_EXPR:
7730 case FLOOR_DIV_EXPR:
7731 case ROUND_DIV_EXPR:
7732 case EXACT_DIV_EXPR:
7733 case TRUNC_MOD_EXPR:
7734 case FLOOR_MOD_EXPR:
7735 case RDIV_EXPR:
7736 case EQ_EXPR:
7737 case NE_EXPR:
7738 case LE_EXPR:
7739 case GE_EXPR:
7740 case LT_EXPR:
7741 case GT_EXPR:
7742 /* What about UNLT_EXPR? */
7743 if (VECTOR_TYPE_P (type0))
7745 ret = stv_secondarg;
7746 std::swap (type0, type1);
7747 std::swap (op0, op1);
7750 if (TREE_CODE (type0) == INTEGER_TYPE
7751 && TREE_CODE (TREE_TYPE (type1)) == INTEGER_TYPE)
7753 if (unsafe_conversion_p (loc, TREE_TYPE (type1), op0,
7754 NULL_TREE, false))
7756 if (complain)
7757 error_at (loc, "conversion of scalar %qT to vector %qT "
7758 "involves truncation", type0, type1);
7759 return stv_error;
7761 return ret;
7763 else if (!integer_only_op
7764 /* Allow integer --> real conversion if safe. */
7765 && (TREE_CODE (type0) == REAL_TYPE
7766 || TREE_CODE (type0) == INTEGER_TYPE)
7767 && SCALAR_FLOAT_TYPE_P (TREE_TYPE (type1)))
7769 if (unsafe_conversion_p (loc, TREE_TYPE (type1), op0,
7770 NULL_TREE, false))
7772 if (complain)
7773 error_at (loc, "conversion of scalar %qT to vector %qT "
7774 "involves truncation", type0, type1);
7775 return stv_error;
7777 return ret;
7779 default:
7780 break;
7783 return stv_nothing;
7786 /* Return the alignment of std::max_align_t.
7788 [support.types.layout] The type max_align_t is a POD type whose alignment
7789 requirement is at least as great as that of every scalar type, and whose
7790 alignment requirement is supported in every context. */
7792 unsigned
7793 max_align_t_align ()
7795 unsigned int max_align = MAX (TYPE_ALIGN (long_long_integer_type_node),
7796 TYPE_ALIGN (long_double_type_node));
7797 if (float128_type_node != NULL_TREE)
7798 max_align = MAX (max_align, TYPE_ALIGN (float128_type_node));
7799 return max_align;
7802 /* Return true iff ALIGN is an integral constant that is a fundamental
7803 alignment, as defined by [basic.align] in the c++-11
7804 specifications.
7806 That is:
7808 [A fundamental alignment is represented by an alignment less than or
7809 equal to the greatest alignment supported by the implementation
7810 in all contexts, which is equal to alignof(max_align_t)]. */
7812 bool
7813 cxx_fundamental_alignment_p (unsigned align)
7815 return (align <= max_align_t_align ());
7818 /* Return true if T is a pointer to a zero-sized aggregate. */
7820 bool
7821 pointer_to_zero_sized_aggr_p (tree t)
7823 if (!POINTER_TYPE_P (t))
7824 return false;
7825 t = TREE_TYPE (t);
7826 return (TYPE_SIZE (t) && integer_zerop (TYPE_SIZE (t)));
7829 /* For an EXPR of a FUNCTION_TYPE that references a GCC built-in function
7830 with no library fallback or for an ADDR_EXPR whose operand is such type
7831 issues an error pointing to the location LOC.
7832 Returns true when the expression has been diagnosed and false
7833 otherwise. */
7835 bool
7836 reject_gcc_builtin (const_tree expr, location_t loc /* = UNKNOWN_LOCATION */)
7838 if (TREE_CODE (expr) == ADDR_EXPR)
7839 expr = TREE_OPERAND (expr, 0);
7841 if (TREE_TYPE (expr)
7842 && TREE_CODE (TREE_TYPE (expr)) == FUNCTION_TYPE
7843 && TREE_CODE (expr) == FUNCTION_DECL
7844 /* The intersection of DECL_BUILT_IN and DECL_IS_BUILTIN avoids
7845 false positives for user-declared built-ins such as abs or
7846 strlen, and for C++ operators new and delete.
7847 The c_decl_implicit() test avoids false positives for implicitly
7848 declared built-ins with library fallbacks (such as abs). */
7849 && DECL_BUILT_IN (expr)
7850 && DECL_IS_BUILTIN (expr)
7851 && !c_decl_implicit (expr)
7852 && !DECL_ASSEMBLER_NAME_SET_P (expr))
7854 if (loc == UNKNOWN_LOCATION)
7855 loc = EXPR_LOC_OR_LOC (expr, input_location);
7857 /* Reject arguments that are built-in functions with
7858 no library fallback. */
7859 error_at (loc, "built-in function %qE must be directly called", expr);
7861 return true;
7864 return false;
7867 /* Check if array size calculations overflow or if the array covers more
7868 than half of the address space. Return true if the size of the array
7869 is valid, false otherwise. TYPE is the type of the array and NAME is
7870 the name of the array, or NULL_TREE for unnamed arrays. */
7872 bool
7873 valid_array_size_p (location_t loc, tree type, tree name)
7875 if (type != error_mark_node
7876 && COMPLETE_TYPE_P (type)
7877 && TREE_CODE (TYPE_SIZE_UNIT (type)) == INTEGER_CST
7878 && !valid_constant_size_p (TYPE_SIZE_UNIT (type)))
7880 if (name)
7881 error_at (loc, "size of array %qE is too large", name);
7882 else
7883 error_at (loc, "size of unnamed array is too large");
7884 return false;
7886 return true;
7889 /* Read SOURCE_DATE_EPOCH from environment to have a deterministic
7890 timestamp to replace embedded current dates to get reproducible
7891 results. Returns -1 if SOURCE_DATE_EPOCH is not defined. */
7893 time_t
7894 cb_get_source_date_epoch (cpp_reader *pfile ATTRIBUTE_UNUSED)
7896 char *source_date_epoch;
7897 int64_t epoch;
7898 char *endptr;
7900 source_date_epoch = getenv ("SOURCE_DATE_EPOCH");
7901 if (!source_date_epoch)
7902 return (time_t) -1;
7904 errno = 0;
7905 #if defined(INT64_T_IS_LONG)
7906 epoch = strtol (source_date_epoch, &endptr, 10);
7907 #else
7908 epoch = strtoll (source_date_epoch, &endptr, 10);
7909 #endif
7910 if (errno != 0 || endptr == source_date_epoch || *endptr != '\0'
7911 || epoch < 0 || epoch > MAX_SOURCE_DATE_EPOCH)
7913 error_at (input_location, "environment variable SOURCE_DATE_EPOCH must "
7914 "expand to a non-negative integer less than or equal to %wd",
7915 MAX_SOURCE_DATE_EPOCH);
7916 return (time_t) -1;
7919 return (time_t) epoch;
7922 /* Callback for libcpp for offering spelling suggestions for misspelled
7923 directives. GOAL is an unrecognized string; CANDIDATES is a
7924 NULL-terminated array of candidate strings. Return the closest
7925 match to GOAL within CANDIDATES, or NULL if none are good
7926 suggestions. */
7928 const char *
7929 cb_get_suggestion (cpp_reader *, const char *goal,
7930 const char *const *candidates)
7932 best_match<const char *, const char *> bm (goal);
7933 while (*candidates)
7934 bm.consider (*candidates++);
7935 return bm.get_best_meaningful_candidate ();
7938 /* Return the latice point which is the wider of the two FLT_EVAL_METHOD
7939 modes X, Y. This isn't just >, as the FLT_EVAL_METHOD values added
7940 by C TS 18661-3 for interchange types that are computed in their
7941 native precision are larger than the C11 values for evaluating in the
7942 precision of float/double/long double. If either mode is
7943 FLT_EVAL_METHOD_UNPREDICTABLE, return that. */
7945 enum flt_eval_method
7946 excess_precision_mode_join (enum flt_eval_method x,
7947 enum flt_eval_method y)
7949 if (x == FLT_EVAL_METHOD_UNPREDICTABLE
7950 || y == FLT_EVAL_METHOD_UNPREDICTABLE)
7951 return FLT_EVAL_METHOD_UNPREDICTABLE;
7953 /* GCC only supports one interchange type right now, _Float16. If
7954 we're evaluating _Float16 in 16-bit precision, then flt_eval_method
7955 will be FLT_EVAL_METHOD_PROMOTE_TO_FLOAT16. */
7956 if (x == FLT_EVAL_METHOD_PROMOTE_TO_FLOAT16)
7957 return y;
7958 if (y == FLT_EVAL_METHOD_PROMOTE_TO_FLOAT16)
7959 return x;
7961 /* Other values for flt_eval_method are directly comparable, and we want
7962 the maximum. */
7963 return MAX (x, y);
7966 /* Return the value that should be set for FLT_EVAL_METHOD in the
7967 context of ISO/IEC TS 18861-3.
7969 This relates to the effective excess precision seen by the user,
7970 which is the join point of the precision the target requests for
7971 -fexcess-precision={standard,fast} and the implicit excess precision
7972 the target uses. */
7974 static enum flt_eval_method
7975 c_ts18661_flt_eval_method (void)
7977 enum flt_eval_method implicit
7978 = targetm.c.excess_precision (EXCESS_PRECISION_TYPE_IMPLICIT);
7980 enum excess_precision_type flag_type
7981 = (flag_excess_precision_cmdline == EXCESS_PRECISION_STANDARD
7982 ? EXCESS_PRECISION_TYPE_STANDARD
7983 : EXCESS_PRECISION_TYPE_FAST);
7985 enum flt_eval_method requested
7986 = targetm.c.excess_precision (flag_type);
7988 return excess_precision_mode_join (implicit, requested);
7991 /* As c_cpp_ts18661_flt_eval_method, but clamps the expected values to
7992 those that were permitted by C11. That is to say, eliminates
7993 FLT_EVAL_METHOD_PROMOTE_TO_FLOAT16. */
7995 static enum flt_eval_method
7996 c_c11_flt_eval_method (void)
7998 return excess_precision_mode_join (c_ts18661_flt_eval_method (),
7999 FLT_EVAL_METHOD_PROMOTE_TO_FLOAT);
8002 /* Return the value that should be set for FLT_EVAL_METHOD.
8003 MAYBE_C11_ONLY_P is TRUE if we should check
8004 FLAG_PERMITTED_EVAL_METHODS as to whether we should limit the possible
8005 values we can return to those from C99/C11, and FALSE otherwise.
8006 See the comments on c_ts18661_flt_eval_method for what value we choose
8007 to set here. */
8010 c_flt_eval_method (bool maybe_c11_only_p)
8012 if (maybe_c11_only_p
8013 && flag_permitted_flt_eval_methods
8014 == PERMITTED_FLT_EVAL_METHODS_C11)
8015 return c_c11_flt_eval_method ();
8016 else
8017 return c_ts18661_flt_eval_method ();
8020 /* An enum for get_missing_token_insertion_kind for describing the best
8021 place to insert a missing token, if there is one. */
8023 enum missing_token_insertion_kind
8025 MTIK_IMPOSSIBLE,
8026 MTIK_INSERT_BEFORE_NEXT,
8027 MTIK_INSERT_AFTER_PREV
8030 /* Given a missing token of TYPE, determine if it is reasonable to
8031 emit a fix-it hint suggesting the insertion of the token, and,
8032 if so, where the token should be inserted relative to other tokens.
8034 It only makes sense to do this for values of TYPE that are symbols.
8036 Some symbols should go before the next token, e.g. in:
8037 if flag)
8038 we want to insert the missing '(' immediately before "flag",
8039 giving:
8040 if (flag)
8041 rather than:
8042 if( flag)
8043 These use MTIK_INSERT_BEFORE_NEXT.
8045 Other symbols should go after the previous token, e.g. in:
8046 if (flag
8047 do_something ();
8048 we want to insert the missing ')' immediately after the "flag",
8049 giving:
8050 if (flag)
8051 do_something ();
8052 rather than:
8053 if (flag
8054 )do_something ();
8055 These use MTIK_INSERT_AFTER_PREV. */
8057 static enum missing_token_insertion_kind
8058 get_missing_token_insertion_kind (enum cpp_ttype type)
8060 switch (type)
8062 /* Insert missing "opening" brackets immediately
8063 before the next token. */
8064 case CPP_OPEN_SQUARE:
8065 case CPP_OPEN_PAREN:
8066 return MTIK_INSERT_BEFORE_NEXT;
8068 /* Insert other missing symbols immediately after
8069 the previous token. */
8070 case CPP_CLOSE_PAREN:
8071 case CPP_CLOSE_SQUARE:
8072 case CPP_SEMICOLON:
8073 case CPP_COMMA:
8074 case CPP_COLON:
8075 return MTIK_INSERT_AFTER_PREV;
8077 /* Other kinds of token don't get fix-it hints. */
8078 default:
8079 return MTIK_IMPOSSIBLE;
8083 /* Given RICHLOC, a location for a diagnostic describing a missing token
8084 of kind TOKEN_TYPE, potentially add a fix-it hint suggesting the
8085 insertion of the token.
8087 The location of the attempted fix-it hint depends on TOKEN_TYPE:
8088 it will either be:
8089 (a) immediately after PREV_TOKEN_LOC, or
8091 (b) immediately before the primary location within RICHLOC (taken to
8092 be that of the token following where the token was expected).
8094 If we manage to add a fix-it hint, then the location of the
8095 fix-it hint is likely to be more useful as the primary location
8096 of the diagnostic than that of the following token, so we swap
8097 these locations.
8099 For example, given this bogus code:
8100 123456789012345678901234567890
8101 1 | int missing_semicolon (void)
8102 2 | {
8103 3 | return 42
8104 4 | }
8106 we will emit:
8108 "expected ';' before '}'"
8110 RICHLOC's primary location is at the closing brace, so before "swapping"
8111 we would emit the error at line 4 column 1:
8113 123456789012345678901234567890
8114 3 | return 42 |< fix-it hint emitted for this line
8115 | ; |
8116 4 | } |< "expected ';' before '}'" emitted at this line
8117 | ^ |
8119 It's more useful for the location of the diagnostic to be at the
8120 fix-it hint, so we swap the locations, so the primary location
8121 is at the fix-it hint, with the old primary location inserted
8122 as a secondary location, giving this, with the error at line 3
8123 column 12:
8125 123456789012345678901234567890
8126 3 | return 42 |< "expected ';' before '}'" emitted at this line,
8127 | ^ | with fix-it hint
8128 4 | ; |
8129 | } |< secondary range emitted here
8130 | ~ |. */
8132 void
8133 maybe_suggest_missing_token_insertion (rich_location *richloc,
8134 enum cpp_ttype token_type,
8135 location_t prev_token_loc)
8137 gcc_assert (richloc);
8139 enum missing_token_insertion_kind mtik
8140 = get_missing_token_insertion_kind (token_type);
8142 switch (mtik)
8144 default:
8145 gcc_unreachable ();
8146 break;
8148 case MTIK_IMPOSSIBLE:
8149 return;
8151 case MTIK_INSERT_BEFORE_NEXT:
8152 /* Attempt to add the fix-it hint before the primary location
8153 of RICHLOC. */
8154 richloc->add_fixit_insert_before (cpp_type2name (token_type, 0));
8155 break;
8157 case MTIK_INSERT_AFTER_PREV:
8158 /* Attempt to add the fix-it hint after PREV_TOKEN_LOC. */
8159 richloc->add_fixit_insert_after (prev_token_loc,
8160 cpp_type2name (token_type, 0));
8161 break;
8164 /* If we were successful, use the fix-it hint's location as the
8165 primary location within RICHLOC, adding the old primary location
8166 back as a secondary location. */
8167 if (!richloc->seen_impossible_fixit_p ())
8169 fixit_hint *hint = richloc->get_last_fixit_hint ();
8170 location_t hint_loc = hint->get_start_loc ();
8171 location_t old_loc = richloc->get_loc ();
8173 richloc->set_range (line_table, 0, hint_loc, true);
8174 richloc->add_range (old_loc, false);
8178 #if CHECKING_P
8180 namespace selftest {
8182 /* Run all of the tests within c-family. */
8184 void
8185 c_family_tests (void)
8187 c_format_c_tests ();
8188 c_spellcheck_cc_tests ();
8191 } // namespace selftest
8193 #endif /* #if CHECKING_P */
8195 /* Attempt to locate a suitable location within FILE for a
8196 #include directive to be inserted before. FILE should
8197 be a string from libcpp (pointer equality is used).
8198 LOC is the location of the relevant diagnostic.
8200 Attempt to return the location within FILE immediately
8201 after the last #include within that file, or the start of
8202 that file if it has no #include directives.
8204 Return UNKNOWN_LOCATION if no suitable location is found,
8205 or if an error occurs. */
8207 static location_t
8208 try_to_locate_new_include_insertion_point (const char *file, location_t loc)
8210 /* Locate the last ordinary map within FILE that ended with a #include. */
8211 const line_map_ordinary *last_include_ord_map = NULL;
8213 /* ...and the next ordinary map within FILE after that one. */
8214 const line_map_ordinary *last_ord_map_after_include = NULL;
8216 /* ...and the first ordinary map within FILE. */
8217 const line_map_ordinary *first_ord_map_in_file = NULL;
8219 /* Get ordinary map containing LOC (or its expansion). */
8220 const line_map_ordinary *ord_map_for_loc = NULL;
8221 loc = linemap_resolve_location (line_table, loc, LRK_MACRO_EXPANSION_POINT,
8222 &ord_map_for_loc);
8223 gcc_assert (ord_map_for_loc);
8225 for (unsigned int i = 0; i < LINEMAPS_ORDINARY_USED (line_table); i++)
8227 const line_map_ordinary *ord_map
8228 = LINEMAPS_ORDINARY_MAP_AT (line_table, i);
8230 const line_map_ordinary *from = INCLUDED_FROM (line_table, ord_map);
8231 if (from)
8232 if (from->to_file == file)
8234 last_include_ord_map = from;
8235 last_ord_map_after_include = NULL;
8238 if (ord_map->to_file == file)
8240 if (!first_ord_map_in_file)
8241 first_ord_map_in_file = ord_map;
8242 if (last_include_ord_map && !last_ord_map_after_include)
8243 last_ord_map_after_include = ord_map;
8246 /* Stop searching when reaching the ord_map containing LOC,
8247 as it makes no sense to provide fix-it hints that appear
8248 after the diagnostic in question. */
8249 if (ord_map == ord_map_for_loc)
8250 break;
8253 /* Determine where to insert the #include. */
8254 const line_map_ordinary *ord_map_for_insertion;
8256 /* We want the next ordmap in the file after the last one that's a
8257 #include, but failing that, the start of the file. */
8258 if (last_ord_map_after_include)
8259 ord_map_for_insertion = last_ord_map_after_include;
8260 else
8261 ord_map_for_insertion = first_ord_map_in_file;
8263 if (!ord_map_for_insertion)
8264 return UNKNOWN_LOCATION;
8266 /* The "start_location" is column 0, meaning "the whole line".
8267 rich_location and edit_context can't cope with this, so use
8268 column 1 instead. */
8269 location_t col_0 = ord_map_for_insertion->start_location;
8270 return linemap_position_for_loc_and_offset (line_table, col_0, 1);
8273 /* A map from filenames to sets of headers added to them, for
8274 ensuring idempotency within maybe_add_include_fixit. */
8276 /* The values within the map. We need string comparison as there's
8277 no guarantee that two different diagnostics that are recommending
8278 adding e.g. "<stdio.h>" are using the same buffer. */
8280 typedef hash_set <const char *, nofree_string_hash> per_file_includes_t;
8282 /* The map itself. We don't need string comparison for the filename keys,
8283 as they come from libcpp. */
8285 typedef hash_map <const char *, per_file_includes_t *> added_includes_t;
8286 static added_includes_t *added_includes;
8288 /* Attempt to add a fix-it hint to RICHLOC, adding "#include HEADER\n"
8289 in a suitable location within the file of RICHLOC's primary
8290 location.
8292 This function is idempotent: a header will be added at most once to
8293 any given file. */
8295 void
8296 maybe_add_include_fixit (rich_location *richloc, const char *header)
8298 location_t loc = richloc->get_loc ();
8299 const char *file = LOCATION_FILE (loc);
8300 if (!file)
8301 return;
8303 /* Idempotency: don't add the same header more than once to a given file. */
8304 if (!added_includes)
8305 added_includes = new added_includes_t ();
8306 per_file_includes_t *&set = added_includes->get_or_insert (file);
8307 if (set)
8308 if (set->contains (header))
8309 /* ...then we've already added HEADER to that file. */
8310 return;
8311 if (!set)
8312 set = new per_file_includes_t ();
8313 set->add (header);
8315 /* Attempt to locate a suitable place for the new directive. */
8316 location_t include_insert_loc
8317 = try_to_locate_new_include_insertion_point (file, loc);
8318 if (include_insert_loc == UNKNOWN_LOCATION)
8319 return;
8321 char *text = xasprintf ("#include %s\n", header);
8322 richloc->add_fixit_insert_before (include_insert_loc, text);
8323 free (text);
8326 #include "gt-c-family-c-common.h"