[gcc]
[official-gcc.git] / gcc / c-family / c-warn.c
blob5d67395c5020230cff3572093c155a94bc3913c4
1 /* Diagnostic routines shared by all languages that are variants of C.
2 Copyright (C) 1992-2017 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 #include "config.h"
21 #include "system.h"
22 #include "coretypes.h"
23 #include "target.h"
24 #include "function.h"
25 #include "tree.h"
26 #include "c-common.h"
27 #include "memmodel.h"
28 #include "tm_p.h"
29 #include "diagnostic.h"
30 #include "intl.h"
31 #include "asan.h"
32 #include "gcc-rich-location.h"
33 #include "gimplify.h"
34 #include "c-family/c-indentation.h"
36 /* Print a warning if a constant expression had overflow in folding.
37 Invoke this function on every expression that the language
38 requires to be a constant expression.
39 Note the ANSI C standard says it is erroneous for a
40 constant expression to overflow. */
42 void
43 constant_expression_warning (tree value)
45 if (warn_overflow && pedantic
46 && (TREE_CODE (value) == INTEGER_CST || TREE_CODE (value) == REAL_CST
47 || TREE_CODE (value) == FIXED_CST
48 || TREE_CODE (value) == VECTOR_CST
49 || TREE_CODE (value) == COMPLEX_CST)
50 && TREE_OVERFLOW (value))
51 pedwarn (input_location, OPT_Woverflow, "overflow in constant expression");
54 /* The same as above but print an unconditional error. */
56 void
57 constant_expression_error (tree value)
59 if ((TREE_CODE (value) == INTEGER_CST || TREE_CODE (value) == REAL_CST
60 || TREE_CODE (value) == FIXED_CST
61 || TREE_CODE (value) == VECTOR_CST
62 || TREE_CODE (value) == COMPLEX_CST)
63 && TREE_OVERFLOW (value))
64 error ("overflow in constant expression");
67 /* Print a warning if an expression result VALUE had an overflow
68 in folding and its operands hadn't. EXPR, which may be null, is
69 the operand of the expression.
71 Invoke this function on every expression that
72 (1) appears in the source code, and
73 (2) is a constant expression that overflowed, and
74 (3) is not already checked by convert_and_check;
75 however, do not invoke this function on operands of explicit casts
76 or when the expression is the result of an operator and any operand
77 already overflowed. */
79 void
80 overflow_warning (location_t loc, tree value, tree expr)
82 if (c_inhibit_evaluation_warnings != 0)
83 return;
85 const char *warnfmt = NULL;
87 switch (TREE_CODE (value))
89 case INTEGER_CST:
90 warnfmt = (expr
91 ? G_("integer overflow in expression %qE of type %qT "
92 "results in %qE")
93 : G_("integer overflow in expression of type %qT "
94 "results in %qE"));
95 break;
97 case REAL_CST:
98 warnfmt = (expr
99 ? G_ ("floating point overflow in expression %qE "
100 "of type %qT results in %qE")
101 : G_ ("floating point overflow in expression of type %qT "
102 "results in %qE"));
103 break;
105 case FIXED_CST:
106 warnfmt = (expr
107 ? G_("fixed-point overflow in expression %qE of type %qT "
108 "results in %qE")
109 : G_("fixed-point overflow in expression of type %qT "
110 "results in %qE"));
111 break;
113 case VECTOR_CST:
114 warnfmt = (expr
115 ? G_("vector overflow in expression %qE of type %qT "
116 "results in %qE")
117 : G_("vector overflow in expression of type %qT "
118 "results in %qE"));
119 break;
121 case COMPLEX_CST:
122 if (TREE_CODE (TREE_REALPART (value)) == INTEGER_CST)
123 warnfmt = (expr
124 ? G_("complex integer overflow in expression %qE "
125 "of type %qT results in %qE")
126 : G_("complex integer overflow in expression of type %qT "
127 "results in %qE"));
128 else if (TREE_CODE (TREE_REALPART (value)) == REAL_CST)
129 warnfmt = (expr
130 ? G_("complex floating point overflow in expression %qE "
131 "of type %qT results in %qE")
132 : G_("complex floating point overflow in expression "
133 "of type %qT results in %qE"));
134 else
135 return;
136 break;
138 default:
139 return;
142 if (expr)
143 warning_at (loc, OPT_Woverflow, warnfmt, expr, TREE_TYPE (expr), value);
144 else
145 warning_at (loc, OPT_Woverflow, warnfmt, TREE_TYPE (value), value);
147 TREE_NO_WARNING (value) = 1;
150 /* Helper function for walk_tree. Unwrap C_MAYBE_CONST_EXPRs in an expression
151 pointed to by TP. */
153 static tree
154 unwrap_c_maybe_const (tree *tp, int *walk_subtrees, void *)
156 if (TREE_CODE (*tp) == C_MAYBE_CONST_EXPR)
158 *tp = C_MAYBE_CONST_EXPR_EXPR (*tp);
159 /* C_MAYBE_CONST_EXPRs don't nest. */
160 *walk_subtrees = false;
162 return NULL_TREE;
165 /* Warn about uses of logical || / && operator in a context where it
166 is likely that the bitwise equivalent was intended by the
167 programmer. We have seen an expression in which CODE is a binary
168 operator used to combine expressions OP_LEFT and OP_RIGHT, which before folding
169 had CODE_LEFT and CODE_RIGHT, into an expression of type TYPE. */
171 void
172 warn_logical_operator (location_t location, enum tree_code code, tree type,
173 enum tree_code code_left, tree op_left,
174 enum tree_code ARG_UNUSED (code_right), tree op_right)
176 int or_op = (code == TRUTH_ORIF_EXPR || code == TRUTH_OR_EXPR);
177 int in0_p, in1_p, in_p;
178 tree low0, low1, low, high0, high1, high, lhs, rhs, tem;
179 bool strict_overflow_p = false;
181 if (code != TRUTH_ANDIF_EXPR
182 && code != TRUTH_AND_EXPR
183 && code != TRUTH_ORIF_EXPR
184 && code != TRUTH_OR_EXPR)
185 return;
187 /* We don't want to warn if either operand comes from a macro
188 expansion. ??? This doesn't work with e.g. NEGATE_EXPR yet;
189 see PR61534. */
190 if (from_macro_expansion_at (EXPR_LOCATION (op_left))
191 || from_macro_expansion_at (EXPR_LOCATION (op_right)))
192 return;
194 /* Warn if &&/|| are being used in a context where it is
195 likely that the bitwise equivalent was intended by the
196 programmer. That is, an expression such as op && MASK
197 where op should not be any boolean expression, nor a
198 constant, and mask seems to be a non-boolean integer constant. */
199 if (TREE_CODE (op_right) == CONST_DECL)
200 /* An enumerator counts as a constant. */
201 op_right = DECL_INITIAL (op_right);
202 if (!truth_value_p (code_left)
203 && INTEGRAL_TYPE_P (TREE_TYPE (op_left))
204 && !CONSTANT_CLASS_P (op_left)
205 && !TREE_NO_WARNING (op_left)
206 && TREE_CODE (op_right) == INTEGER_CST
207 && !integer_zerop (op_right)
208 && !integer_onep (op_right))
210 if (or_op)
211 warning_at (location, OPT_Wlogical_op, "logical %<or%>"
212 " applied to non-boolean constant");
213 else
214 warning_at (location, OPT_Wlogical_op, "logical %<and%>"
215 " applied to non-boolean constant");
216 TREE_NO_WARNING (op_left) = true;
217 return;
220 /* We do not warn for constants because they are typical of macro
221 expansions that test for features. */
222 if (CONSTANT_CLASS_P (fold_for_warn (op_left))
223 || CONSTANT_CLASS_P (fold_for_warn (op_right)))
224 return;
226 /* This warning only makes sense with logical operands. */
227 if (!(truth_value_p (TREE_CODE (op_left))
228 || INTEGRAL_TYPE_P (TREE_TYPE (op_left)))
229 || !(truth_value_p (TREE_CODE (op_right))
230 || INTEGRAL_TYPE_P (TREE_TYPE (op_right))))
231 return;
233 /* The range computations only work with scalars. */
234 if (VECTOR_TYPE_P (TREE_TYPE (op_left))
235 || VECTOR_TYPE_P (TREE_TYPE (op_right)))
236 return;
238 /* We first test whether either side separately is trivially true
239 (with OR) or trivially false (with AND). If so, do not warn.
240 This is a common idiom for testing ranges of data types in
241 portable code. */
242 op_left = unshare_expr (op_left);
243 walk_tree_without_duplicates (&op_left, unwrap_c_maybe_const, NULL);
244 lhs = make_range (op_left, &in0_p, &low0, &high0, &strict_overflow_p);
245 if (!lhs)
246 return;
248 /* If this is an OR operation, invert both sides; now, the result
249 should be always false to get a warning. */
250 if (or_op)
251 in0_p = !in0_p;
253 tem = build_range_check (UNKNOWN_LOCATION, type, lhs, in0_p, low0, high0);
254 if (tem && integer_zerop (tem))
255 return;
257 op_right = unshare_expr (op_right);
258 walk_tree_without_duplicates (&op_right, unwrap_c_maybe_const, NULL);
259 rhs = make_range (op_right, &in1_p, &low1, &high1, &strict_overflow_p);
260 if (!rhs)
261 return;
263 /* If this is an OR operation, invert both sides; now, the result
264 should be always false to get a warning. */
265 if (or_op)
266 in1_p = !in1_p;
268 tem = build_range_check (UNKNOWN_LOCATION, type, rhs, in1_p, low1, high1);
269 if (tem && integer_zerop (tem))
270 return;
272 /* If both expressions have the same operand, if we can merge the
273 ranges, ... */
274 if (operand_equal_p (lhs, rhs, 0)
275 && merge_ranges (&in_p, &low, &high, in0_p, low0, high0,
276 in1_p, low1, high1))
278 tem = build_range_check (UNKNOWN_LOCATION, type, lhs, in_p, low, high);
279 /* ... and if the range test is always false, then warn. */
280 if (tem && integer_zerop (tem))
282 if (or_op)
283 warning_at (location, OPT_Wlogical_op,
284 "logical %<or%> of collectively exhaustive tests is "
285 "always true");
286 else
287 warning_at (location, OPT_Wlogical_op,
288 "logical %<and%> of mutually exclusive tests is "
289 "always false");
291 /* Or warn if the operands have exactly the same range, e.g.
292 A > 0 && A > 0. */
293 else if (tree_int_cst_equal (low0, low1)
294 && tree_int_cst_equal (high0, high1))
296 if (or_op)
297 warning_at (location, OPT_Wlogical_op,
298 "logical %<or%> of equal expressions");
299 else
300 warning_at (location, OPT_Wlogical_op,
301 "logical %<and%> of equal expressions");
306 /* Helper function for warn_tautological_cmp. Look for ARRAY_REFs
307 with constant indices. */
309 static tree
310 find_array_ref_with_const_idx_r (tree *expr_p, int *, void *)
312 tree expr = *expr_p;
314 if ((TREE_CODE (expr) == ARRAY_REF
315 || TREE_CODE (expr) == ARRAY_RANGE_REF)
316 && TREE_CODE (TREE_OPERAND (expr, 1)) == INTEGER_CST)
317 return integer_type_node;
319 return NULL_TREE;
322 /* Warn if a self-comparison always evaluates to true or false. LOC
323 is the location of the comparison with code CODE, LHS and RHS are
324 operands of the comparison. */
326 void
327 warn_tautological_cmp (location_t loc, enum tree_code code, tree lhs, tree rhs)
329 if (TREE_CODE_CLASS (code) != tcc_comparison)
330 return;
332 /* Don't warn for various macro expansions. */
333 if (from_macro_expansion_at (loc)
334 || from_macro_expansion_at (EXPR_LOCATION (lhs))
335 || from_macro_expansion_at (EXPR_LOCATION (rhs)))
336 return;
338 /* We do not warn for constants because they are typical of macro
339 expansions that test for features, sizeof, and similar. */
340 if (CONSTANT_CLASS_P (fold_for_warn (lhs))
341 || CONSTANT_CLASS_P (fold_for_warn (rhs)))
342 return;
344 /* Don't warn for e.g.
345 HOST_WIDE_INT n;
347 if (n == (long) n) ...
349 if ((CONVERT_EXPR_P (lhs) || TREE_CODE (lhs) == NON_LVALUE_EXPR)
350 || (CONVERT_EXPR_P (rhs) || TREE_CODE (rhs) == NON_LVALUE_EXPR))
351 return;
353 /* Don't warn if either LHS or RHS has an IEEE floating-point type.
354 It could be a NaN, and NaN never compares equal to anything, even
355 itself. */
356 if (FLOAT_TYPE_P (TREE_TYPE (lhs)) || FLOAT_TYPE_P (TREE_TYPE (rhs)))
357 return;
359 if (operand_equal_p (lhs, rhs, 0))
361 /* Don't warn about array references with constant indices;
362 these are likely to come from a macro. */
363 if (walk_tree_without_duplicates (&lhs, find_array_ref_with_const_idx_r,
364 NULL))
365 return;
366 const bool always_true = (code == EQ_EXPR || code == LE_EXPR
367 || code == GE_EXPR || code == UNLE_EXPR
368 || code == UNGE_EXPR || code == UNEQ_EXPR);
369 if (always_true)
370 warning_at (loc, OPT_Wtautological_compare,
371 "self-comparison always evaluates to true");
372 else
373 warning_at (loc, OPT_Wtautological_compare,
374 "self-comparison always evaluates to false");
378 /* Return true iff EXPR only contains boolean operands, or comparisons. */
380 static bool
381 expr_has_boolean_operands_p (tree expr)
383 STRIP_NOPS (expr);
385 if (CONVERT_EXPR_P (expr))
386 return bool_promoted_to_int_p (expr);
387 else if (UNARY_CLASS_P (expr))
388 return expr_has_boolean_operands_p (TREE_OPERAND (expr, 0));
389 else if (BINARY_CLASS_P (expr))
390 return (expr_has_boolean_operands_p (TREE_OPERAND (expr, 0))
391 && expr_has_boolean_operands_p (TREE_OPERAND (expr, 1)));
392 else if (COMPARISON_CLASS_P (expr))
393 return true;
394 else
395 return false;
398 /* Warn about logical not used on the left hand side operand of a comparison.
399 This function assumes that the LHS is inside of TRUTH_NOT_EXPR.
400 Do not warn if RHS is of a boolean type, a logical operator, or
401 a comparison. */
403 void
404 warn_logical_not_parentheses (location_t location, enum tree_code code,
405 tree lhs, tree rhs)
407 if (TREE_CODE_CLASS (code) != tcc_comparison
408 || TREE_TYPE (rhs) == NULL_TREE
409 || TREE_CODE (TREE_TYPE (rhs)) == BOOLEAN_TYPE
410 || truth_value_p (TREE_CODE (rhs)))
411 return;
413 /* Don't warn for expression like !x == ~(bool1 | bool2). */
414 if (expr_has_boolean_operands_p (rhs))
415 return;
417 /* Don't warn for !x == 0 or !y != 0, those are equivalent to
418 !(x == 0) or !(y != 0). */
419 if ((code == EQ_EXPR || code == NE_EXPR)
420 && integer_zerop (rhs))
421 return;
423 if (warning_at (location, OPT_Wlogical_not_parentheses,
424 "logical not is only applied to the left hand side of "
425 "comparison")
426 && EXPR_HAS_LOCATION (lhs))
428 location_t lhs_loc = EXPR_LOCATION (lhs);
429 rich_location richloc (line_table, lhs_loc);
430 richloc.add_fixit_insert_before (lhs_loc, "(");
431 richloc.add_fixit_insert_after (lhs_loc, ")");
432 inform_at_rich_loc (&richloc, "add parentheses around left hand side "
433 "expression to silence this warning");
437 /* Warn if EXP contains any computations whose results are not used.
438 Return true if a warning is printed; false otherwise. LOCUS is the
439 (potential) location of the expression. */
441 bool
442 warn_if_unused_value (const_tree exp, location_t locus)
444 restart:
445 if (TREE_USED (exp) || TREE_NO_WARNING (exp))
446 return false;
448 /* Don't warn about void constructs. This includes casting to void,
449 void function calls, and statement expressions with a final cast
450 to void. */
451 if (VOID_TYPE_P (TREE_TYPE (exp)))
452 return false;
454 if (EXPR_HAS_LOCATION (exp))
455 locus = EXPR_LOCATION (exp);
457 switch (TREE_CODE (exp))
459 case PREINCREMENT_EXPR:
460 case POSTINCREMENT_EXPR:
461 case PREDECREMENT_EXPR:
462 case POSTDECREMENT_EXPR:
463 case MODIFY_EXPR:
464 case INIT_EXPR:
465 case TARGET_EXPR:
466 case CALL_EXPR:
467 case TRY_CATCH_EXPR:
468 case WITH_CLEANUP_EXPR:
469 case EXIT_EXPR:
470 case VA_ARG_EXPR:
471 return false;
473 case BIND_EXPR:
474 /* For a binding, warn if no side effect within it. */
475 exp = BIND_EXPR_BODY (exp);
476 goto restart;
478 case SAVE_EXPR:
479 case NON_LVALUE_EXPR:
480 case NOP_EXPR:
481 exp = TREE_OPERAND (exp, 0);
482 goto restart;
484 case TRUTH_ORIF_EXPR:
485 case TRUTH_ANDIF_EXPR:
486 /* In && or ||, warn if 2nd operand has no side effect. */
487 exp = TREE_OPERAND (exp, 1);
488 goto restart;
490 case COMPOUND_EXPR:
491 if (warn_if_unused_value (TREE_OPERAND (exp, 0), locus))
492 return true;
493 /* Let people do `(foo (), 0)' without a warning. */
494 if (TREE_CONSTANT (TREE_OPERAND (exp, 1)))
495 return false;
496 exp = TREE_OPERAND (exp, 1);
497 goto restart;
499 case COND_EXPR:
500 /* If this is an expression with side effects, don't warn; this
501 case commonly appears in macro expansions. */
502 if (TREE_SIDE_EFFECTS (exp))
503 return false;
504 goto warn;
506 case INDIRECT_REF:
507 /* Don't warn about automatic dereferencing of references, since
508 the user cannot control it. */
509 if (TREE_CODE (TREE_TYPE (TREE_OPERAND (exp, 0))) == REFERENCE_TYPE)
511 exp = TREE_OPERAND (exp, 0);
512 goto restart;
514 /* Fall through. */
516 default:
517 /* Referencing a volatile value is a side effect, so don't warn. */
518 if ((DECL_P (exp) || REFERENCE_CLASS_P (exp))
519 && TREE_THIS_VOLATILE (exp))
520 return false;
522 /* If this is an expression which has no operands, there is no value
523 to be unused. There are no such language-independent codes,
524 but front ends may define such. */
525 if (EXPRESSION_CLASS_P (exp) && TREE_OPERAND_LENGTH (exp) == 0)
526 return false;
528 warn:
529 return warning_at (locus, OPT_Wunused_value, "value computed is not used");
533 /* Print a warning about casts that might indicate violation
534 of strict aliasing rules if -Wstrict-aliasing is used and
535 strict aliasing mode is in effect. OTYPE is the original
536 TREE_TYPE of EXPR, and TYPE the type we're casting to. */
538 bool
539 strict_aliasing_warning (tree otype, tree type, tree expr)
541 /* Strip pointer conversion chains and get to the correct original type. */
542 STRIP_NOPS (expr);
543 otype = TREE_TYPE (expr);
545 if (!(flag_strict_aliasing
546 && POINTER_TYPE_P (type)
547 && POINTER_TYPE_P (otype)
548 && !VOID_TYPE_P (TREE_TYPE (type)))
549 /* If the type we are casting to is a ref-all pointer
550 dereferencing it is always valid. */
551 || TYPE_REF_CAN_ALIAS_ALL (type))
552 return false;
554 if ((warn_strict_aliasing > 1) && TREE_CODE (expr) == ADDR_EXPR
555 && (DECL_P (TREE_OPERAND (expr, 0))
556 || handled_component_p (TREE_OPERAND (expr, 0))))
558 /* Casting the address of an object to non void pointer. Warn
559 if the cast breaks type based aliasing. */
560 if (!COMPLETE_TYPE_P (TREE_TYPE (type)) && warn_strict_aliasing == 2)
562 warning (OPT_Wstrict_aliasing, "type-punning to incomplete type "
563 "might break strict-aliasing rules");
564 return true;
566 else
568 /* warn_strict_aliasing >= 3. This includes the default (3).
569 Only warn if the cast is dereferenced immediately. */
570 alias_set_type set1
571 = get_alias_set (TREE_TYPE (TREE_OPERAND (expr, 0)));
572 alias_set_type set2 = get_alias_set (TREE_TYPE (type));
574 if (set2 != 0
575 && set1 != set2
576 && !alias_set_subset_of (set2, set1)
577 && !alias_sets_conflict_p (set1, set2))
579 warning (OPT_Wstrict_aliasing, "dereferencing type-punned "
580 "pointer will break strict-aliasing rules");
581 return true;
583 else if (warn_strict_aliasing == 2
584 && !alias_sets_must_conflict_p (set1, set2))
586 warning (OPT_Wstrict_aliasing, "dereferencing type-punned "
587 "pointer might break strict-aliasing rules");
588 return true;
592 else if ((warn_strict_aliasing == 1) && !VOID_TYPE_P (TREE_TYPE (otype)))
594 /* At this level, warn for any conversions, even if an address is
595 not taken in the same statement. This will likely produce many
596 false positives, but could be useful to pinpoint problems that
597 are not revealed at higher levels. */
598 alias_set_type set1 = get_alias_set (TREE_TYPE (otype));
599 alias_set_type set2 = get_alias_set (TREE_TYPE (type));
600 if (!COMPLETE_TYPE_P (type)
601 || !alias_sets_must_conflict_p (set1, set2))
603 warning (OPT_Wstrict_aliasing, "dereferencing type-punned "
604 "pointer might break strict-aliasing rules");
605 return true;
609 return false;
612 /* Warn about memset (&a, 0, sizeof (&a)); and similar mistakes with
613 sizeof as last operand of certain builtins. */
615 void
616 sizeof_pointer_memaccess_warning (location_t *sizeof_arg_loc, tree callee,
617 vec<tree, va_gc> *params, tree *sizeof_arg,
618 bool (*comp_types) (tree, tree))
620 tree type, dest = NULL_TREE, src = NULL_TREE, tem;
621 bool strop = false, cmp = false;
622 unsigned int idx = ~0;
623 location_t loc;
625 if (TREE_CODE (callee) != FUNCTION_DECL
626 || DECL_BUILT_IN_CLASS (callee) != BUILT_IN_NORMAL
627 || vec_safe_length (params) <= 1)
628 return;
630 switch (DECL_FUNCTION_CODE (callee))
632 case BUILT_IN_STRNCMP:
633 case BUILT_IN_STRNCASECMP:
634 cmp = true;
635 /* FALLTHRU */
636 case BUILT_IN_STRNCPY:
637 case BUILT_IN_STRNCPY_CHK:
638 case BUILT_IN_STRNCAT:
639 case BUILT_IN_STRNCAT_CHK:
640 case BUILT_IN_STPNCPY:
641 case BUILT_IN_STPNCPY_CHK:
642 strop = true;
643 /* FALLTHRU */
644 case BUILT_IN_MEMCPY:
645 case BUILT_IN_MEMCPY_CHK:
646 case BUILT_IN_MEMMOVE:
647 case BUILT_IN_MEMMOVE_CHK:
648 if (params->length () < 3)
649 return;
650 src = (*params)[1];
651 dest = (*params)[0];
652 idx = 2;
653 break;
654 case BUILT_IN_BCOPY:
655 if (params->length () < 3)
656 return;
657 src = (*params)[0];
658 dest = (*params)[1];
659 idx = 2;
660 break;
661 case BUILT_IN_MEMCMP:
662 case BUILT_IN_BCMP:
663 if (params->length () < 3)
664 return;
665 src = (*params)[1];
666 dest = (*params)[0];
667 idx = 2;
668 cmp = true;
669 break;
670 case BUILT_IN_MEMSET:
671 case BUILT_IN_MEMSET_CHK:
672 if (params->length () < 3)
673 return;
674 dest = (*params)[0];
675 idx = 2;
676 break;
677 case BUILT_IN_BZERO:
678 dest = (*params)[0];
679 idx = 1;
680 break;
681 case BUILT_IN_STRNDUP:
682 src = (*params)[0];
683 strop = true;
684 idx = 1;
685 break;
686 case BUILT_IN_MEMCHR:
687 if (params->length () < 3)
688 return;
689 src = (*params)[0];
690 idx = 2;
691 break;
692 case BUILT_IN_SNPRINTF:
693 case BUILT_IN_SNPRINTF_CHK:
694 case BUILT_IN_VSNPRINTF:
695 case BUILT_IN_VSNPRINTF_CHK:
696 dest = (*params)[0];
697 idx = 1;
698 strop = true;
699 break;
700 default:
701 break;
704 if (idx >= 3)
705 return;
707 if (sizeof_arg[idx] == NULL || sizeof_arg[idx] == error_mark_node)
708 return;
710 type = TYPE_P (sizeof_arg[idx])
711 ? sizeof_arg[idx] : TREE_TYPE (sizeof_arg[idx]);
712 if (!POINTER_TYPE_P (type))
713 return;
715 if (dest
716 && (tem = tree_strip_nop_conversions (dest))
717 && POINTER_TYPE_P (TREE_TYPE (tem))
718 && comp_types (TREE_TYPE (TREE_TYPE (tem)), type))
719 return;
721 if (src
722 && (tem = tree_strip_nop_conversions (src))
723 && POINTER_TYPE_P (TREE_TYPE (tem))
724 && comp_types (TREE_TYPE (TREE_TYPE (tem)), type))
725 return;
727 loc = sizeof_arg_loc[idx];
729 if (dest && !cmp)
731 if (!TYPE_P (sizeof_arg[idx])
732 && operand_equal_p (dest, sizeof_arg[idx], 0)
733 && comp_types (TREE_TYPE (dest), type))
735 if (TREE_CODE (sizeof_arg[idx]) == ADDR_EXPR && !strop)
736 warning_at (loc, OPT_Wsizeof_pointer_memaccess,
737 "argument to %<sizeof%> in %qD call is the same "
738 "expression as the destination; did you mean to "
739 "remove the addressof?", callee);
740 else if ((TYPE_PRECISION (TREE_TYPE (type))
741 == TYPE_PRECISION (char_type_node))
742 || strop)
743 warning_at (loc, OPT_Wsizeof_pointer_memaccess,
744 "argument to %<sizeof%> in %qD call is the same "
745 "expression as the destination; did you mean to "
746 "provide an explicit length?", callee);
747 else
748 warning_at (loc, OPT_Wsizeof_pointer_memaccess,
749 "argument to %<sizeof%> in %qD call is the same "
750 "expression as the destination; did you mean to "
751 "dereference it?", callee);
752 return;
755 if (POINTER_TYPE_P (TREE_TYPE (dest))
756 && !strop
757 && comp_types (TREE_TYPE (dest), type)
758 && !VOID_TYPE_P (TREE_TYPE (type)))
760 warning_at (loc, OPT_Wsizeof_pointer_memaccess,
761 "argument to %<sizeof%> in %qD call is the same "
762 "pointer type %qT as the destination; expected %qT "
763 "or an explicit length", callee, TREE_TYPE (dest),
764 TREE_TYPE (TREE_TYPE (dest)));
765 return;
769 if (src && !cmp)
771 if (!TYPE_P (sizeof_arg[idx])
772 && operand_equal_p (src, sizeof_arg[idx], 0)
773 && comp_types (TREE_TYPE (src), type))
775 if (TREE_CODE (sizeof_arg[idx]) == ADDR_EXPR && !strop)
776 warning_at (loc, OPT_Wsizeof_pointer_memaccess,
777 "argument to %<sizeof%> in %qD call is the same "
778 "expression as the source; did you mean to "
779 "remove the addressof?", callee);
780 else if ((TYPE_PRECISION (TREE_TYPE (type))
781 == TYPE_PRECISION (char_type_node))
782 || strop)
783 warning_at (loc, OPT_Wsizeof_pointer_memaccess,
784 "argument to %<sizeof%> in %qD call is the same "
785 "expression as the source; did you mean to "
786 "provide an explicit length?", callee);
787 else
788 warning_at (loc, OPT_Wsizeof_pointer_memaccess,
789 "argument to %<sizeof%> in %qD call is the same "
790 "expression as the source; did you mean to "
791 "dereference it?", callee);
792 return;
795 if (POINTER_TYPE_P (TREE_TYPE (src))
796 && !strop
797 && comp_types (TREE_TYPE (src), type)
798 && !VOID_TYPE_P (TREE_TYPE (type)))
800 warning_at (loc, OPT_Wsizeof_pointer_memaccess,
801 "argument to %<sizeof%> in %qD call is the same "
802 "pointer type %qT as the source; expected %qT "
803 "or an explicit length", callee, TREE_TYPE (src),
804 TREE_TYPE (TREE_TYPE (src)));
805 return;
809 if (dest)
811 if (!TYPE_P (sizeof_arg[idx])
812 && operand_equal_p (dest, sizeof_arg[idx], 0)
813 && comp_types (TREE_TYPE (dest), type))
815 if (TREE_CODE (sizeof_arg[idx]) == ADDR_EXPR && !strop)
816 warning_at (loc, OPT_Wsizeof_pointer_memaccess,
817 "argument to %<sizeof%> in %qD call is the same "
818 "expression as the first source; did you mean to "
819 "remove the addressof?", callee);
820 else if ((TYPE_PRECISION (TREE_TYPE (type))
821 == TYPE_PRECISION (char_type_node))
822 || strop)
823 warning_at (loc, OPT_Wsizeof_pointer_memaccess,
824 "argument to %<sizeof%> in %qD call is the same "
825 "expression as the first source; did you mean to "
826 "provide an explicit length?", callee);
827 else
828 warning_at (loc, OPT_Wsizeof_pointer_memaccess,
829 "argument to %<sizeof%> in %qD call is the same "
830 "expression as the first source; did you mean to "
831 "dereference it?", callee);
832 return;
835 if (POINTER_TYPE_P (TREE_TYPE (dest))
836 && !strop
837 && comp_types (TREE_TYPE (dest), type)
838 && !VOID_TYPE_P (TREE_TYPE (type)))
840 warning_at (loc, OPT_Wsizeof_pointer_memaccess,
841 "argument to %<sizeof%> in %qD call is the same "
842 "pointer type %qT as the first source; expected %qT "
843 "or an explicit length", callee, TREE_TYPE (dest),
844 TREE_TYPE (TREE_TYPE (dest)));
845 return;
849 if (src)
851 if (!TYPE_P (sizeof_arg[idx])
852 && operand_equal_p (src, sizeof_arg[idx], 0)
853 && comp_types (TREE_TYPE (src), type))
855 if (TREE_CODE (sizeof_arg[idx]) == ADDR_EXPR && !strop)
856 warning_at (loc, OPT_Wsizeof_pointer_memaccess,
857 "argument to %<sizeof%> in %qD call is the same "
858 "expression as the second source; did you mean to "
859 "remove the addressof?", callee);
860 else if ((TYPE_PRECISION (TREE_TYPE (type))
861 == TYPE_PRECISION (char_type_node))
862 || strop)
863 warning_at (loc, OPT_Wsizeof_pointer_memaccess,
864 "argument to %<sizeof%> in %qD call is the same "
865 "expression as the second source; did you mean to "
866 "provide an explicit length?", callee);
867 else
868 warning_at (loc, OPT_Wsizeof_pointer_memaccess,
869 "argument to %<sizeof%> in %qD call is the same "
870 "expression as the second source; did you mean to "
871 "dereference it?", callee);
872 return;
875 if (POINTER_TYPE_P (TREE_TYPE (src))
876 && !strop
877 && comp_types (TREE_TYPE (src), type)
878 && !VOID_TYPE_P (TREE_TYPE (type)))
880 warning_at (loc, OPT_Wsizeof_pointer_memaccess,
881 "argument to %<sizeof%> in %qD call is the same "
882 "pointer type %qT as the second source; expected %qT "
883 "or an explicit length", callee, TREE_TYPE (src),
884 TREE_TYPE (TREE_TYPE (src)));
885 return;
891 /* Warn for unlikely, improbable, or stupid DECL declarations
892 of `main'. */
894 void
895 check_main_parameter_types (tree decl)
897 function_args_iterator iter;
898 tree type;
899 int argct = 0;
901 FOREACH_FUNCTION_ARGS (TREE_TYPE (decl), type, iter)
903 /* XXX void_type_node belies the abstraction. */
904 if (type == void_type_node || type == error_mark_node)
905 break;
907 tree t = type;
908 if (TYPE_ATOMIC (t))
909 pedwarn (input_location, OPT_Wmain,
910 "%<_Atomic%>-qualified parameter type %qT of %q+D",
911 type, decl);
912 while (POINTER_TYPE_P (t))
914 t = TREE_TYPE (t);
915 if (TYPE_ATOMIC (t))
916 pedwarn (input_location, OPT_Wmain,
917 "%<_Atomic%>-qualified parameter type %qT of %q+D",
918 type, decl);
921 ++argct;
922 switch (argct)
924 case 1:
925 if (TYPE_MAIN_VARIANT (type) != integer_type_node)
926 pedwarn (input_location, OPT_Wmain,
927 "first argument of %q+D should be %<int%>", decl);
928 break;
930 case 2:
931 if (TREE_CODE (type) != POINTER_TYPE
932 || TREE_CODE (TREE_TYPE (type)) != POINTER_TYPE
933 || (TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (type)))
934 != char_type_node))
935 pedwarn (input_location, OPT_Wmain,
936 "second argument of %q+D should be %<char **%>", decl);
937 break;
939 case 3:
940 if (TREE_CODE (type) != POINTER_TYPE
941 || TREE_CODE (TREE_TYPE (type)) != POINTER_TYPE
942 || (TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (type)))
943 != char_type_node))
944 pedwarn (input_location, OPT_Wmain,
945 "third argument of %q+D should probably be "
946 "%<char **%>", decl);
947 break;
951 /* It is intentional that this message does not mention the third
952 argument because it's only mentioned in an appendix of the
953 standard. */
954 if (argct > 0 && (argct < 2 || argct > 3))
955 pedwarn (input_location, OPT_Wmain,
956 "%q+D takes only zero or two arguments", decl);
958 if (stdarg_p (TREE_TYPE (decl)))
959 pedwarn (input_location, OPT_Wmain,
960 "%q+D declared as variadic function", decl);
963 /* Warns if the conversion of EXPR to TYPE may alter a value.
964 This is a helper function for warnings_for_convert_and_check. */
966 static void
967 conversion_warning (location_t loc, tree type, tree expr, tree result)
969 tree expr_type = TREE_TYPE (expr);
970 enum conversion_safety conversion_kind;
972 if (!warn_conversion && !warn_sign_conversion && !warn_float_conversion)
973 return;
975 /* This may happen, because for LHS op= RHS we preevaluate
976 RHS and create C_MAYBE_CONST_EXPR <SAVE_EXPR <RHS>>, which
977 means we could no longer see the code of the EXPR. */
978 if (TREE_CODE (expr) == C_MAYBE_CONST_EXPR)
979 expr = C_MAYBE_CONST_EXPR_EXPR (expr);
980 if (TREE_CODE (expr) == SAVE_EXPR)
981 expr = TREE_OPERAND (expr, 0);
983 switch (TREE_CODE (expr))
985 case EQ_EXPR:
986 case NE_EXPR:
987 case LE_EXPR:
988 case GE_EXPR:
989 case LT_EXPR:
990 case GT_EXPR:
991 case TRUTH_ANDIF_EXPR:
992 case TRUTH_ORIF_EXPR:
993 case TRUTH_AND_EXPR:
994 case TRUTH_OR_EXPR:
995 case TRUTH_XOR_EXPR:
996 case TRUTH_NOT_EXPR:
997 /* Conversion from boolean to a signed:1 bit-field (which only
998 can hold the values 0 and -1) doesn't lose information - but
999 it does change the value. */
1000 if (TYPE_PRECISION (type) == 1 && !TYPE_UNSIGNED (type))
1001 warning_at (loc, OPT_Wconversion,
1002 "conversion to %qT from boolean expression", type);
1003 return;
1005 case REAL_CST:
1006 case INTEGER_CST:
1007 case COMPLEX_CST:
1009 conversion_kind = unsafe_conversion_p (loc, type, expr, result, true);
1010 int warnopt;
1011 if (conversion_kind == UNSAFE_REAL)
1012 warnopt = OPT_Wfloat_conversion;
1013 else if (conversion_kind)
1014 warnopt = OPT_Wconversion;
1015 else
1016 break;
1018 if (TREE_CODE_CLASS (TREE_CODE (result)) == tcc_constant)
1019 warning_at (loc, warnopt,
1020 "conversion from %qT to %qT changes value from %qE to %qE",
1021 expr_type, type, expr, result);
1022 else
1023 warning_at (loc, warnopt,
1024 "conversion from %qT to %qT changes the value of %qE",
1025 expr_type, type, expr);
1026 break;
1028 case COND_EXPR:
1030 /* In case of COND_EXPR, we do not care about the type of
1031 COND_EXPR, only about the conversion of each operand. */
1032 tree op1 = TREE_OPERAND (expr, 1);
1033 tree op2 = TREE_OPERAND (expr, 2);
1035 conversion_warning (loc, type, op1, result);
1036 conversion_warning (loc, type, op2, result);
1037 return;
1040 default: /* 'expr' is not a constant. */
1041 conversion_kind = unsafe_conversion_p (loc, type, expr, result, true);
1042 if (conversion_kind == UNSAFE_IMAGINARY)
1043 warning_at (loc, OPT_Wconversion,
1044 "conversion from %qT to to %qT discards imaginary "
1045 "component",
1046 expr_type, type);
1047 else
1049 int warnopt;
1050 if (conversion_kind == UNSAFE_REAL)
1051 warnopt = OPT_Wfloat_conversion;
1052 else if (conversion_kind)
1053 warnopt = OPT_Wconversion;
1054 else
1055 break;
1056 warning_at (loc, warnopt,
1057 "conversion from %qT to %qT may change value",
1058 expr_type, type);
1063 /* Produce warnings after a conversion. RESULT is the result of
1064 converting EXPR to TYPE. This is a helper function for
1065 convert_and_check and cp_convert_and_check. */
1067 void
1068 warnings_for_convert_and_check (location_t loc, tree type, tree expr,
1069 tree result)
1071 loc = expansion_point_location_if_in_system_header (loc);
1073 bool cst = TREE_CODE_CLASS (TREE_CODE (result)) == tcc_constant;
1075 tree exprtype = TREE_TYPE (expr);
1077 if (TREE_CODE (expr) == INTEGER_CST
1078 && (TREE_CODE (type) == INTEGER_TYPE
1079 || TREE_CODE (type) == ENUMERAL_TYPE)
1080 && !int_fits_type_p (expr, type))
1082 /* Do not diagnose overflow in a constant expression merely
1083 because a conversion overflowed. */
1084 if (TREE_OVERFLOW (result))
1085 TREE_OVERFLOW (result) = TREE_OVERFLOW (expr);
1087 if (TYPE_UNSIGNED (type))
1089 /* This detects cases like converting -129 or 256 to
1090 unsigned char. */
1091 if (!int_fits_type_p (expr, c_common_signed_type (type)))
1093 if (cst)
1094 warning_at (loc, OPT_Woverflow,
1095 (TYPE_UNSIGNED (exprtype)
1096 ? G_("conversion from %qT to %qT "
1097 "changes value from %qE to %qE")
1098 : G_("unsigned conversion from %qT to %qT "
1099 "changes value from %qE to %qE")),
1100 exprtype, type, expr, result);
1101 else
1102 warning_at (loc, OPT_Woverflow,
1103 (TYPE_UNSIGNED (exprtype)
1104 ? G_("conversion from %qT to %qT "
1105 "changes the value of %qE")
1106 : G_("unsigned conversion from %qT to %qT "
1107 "changes the value of %qE")),
1108 exprtype, type, expr);
1110 else
1111 conversion_warning (loc, type, expr, result);
1113 else if (!int_fits_type_p (expr, c_common_unsigned_type (type)))
1115 if (cst)
1116 warning_at (loc, OPT_Woverflow,
1117 "overflow in conversion from %qT to %qT "
1118 "changes value from %qE to %qE",
1119 exprtype, type, expr, result);
1120 else
1121 warning_at (loc, OPT_Woverflow,
1122 "overflow in conversion from %qT to %qT "
1123 "changes the value of %qE",
1124 exprtype, type, expr);
1126 /* No warning for converting 0x80000000 to int. */
1127 else if (pedantic
1128 && (TREE_CODE (exprtype) != INTEGER_TYPE
1129 || TYPE_PRECISION (exprtype)
1130 != TYPE_PRECISION (type)))
1132 if (cst)
1133 warning_at (loc, OPT_Woverflow,
1134 "overflow in conversion from %qT to %qT "
1135 "changes value from %qE to %qE",
1136 exprtype, type, expr, result);
1137 else
1138 warning_at (loc, OPT_Woverflow,
1139 "overflow in conversion from %qT to %qT "
1140 "changes the value of %qE",
1141 exprtype, type, expr);
1143 else
1144 conversion_warning (loc, type, expr, result);
1146 else if ((TREE_CODE (result) == INTEGER_CST
1147 || TREE_CODE (result) == FIXED_CST) && TREE_OVERFLOW (result))
1149 if (cst)
1150 warning_at (loc, OPT_Woverflow,
1151 "overflow in conversion from %qT to %qT "
1152 "chages value from %qE to %qE",
1153 exprtype, type, expr, result);
1154 else
1155 warning_at (loc, OPT_Woverflow,
1156 "overflow in conversion from %qT to %qT "
1157 "chages the value of %qE",
1158 exprtype, type, expr);
1160 else
1161 conversion_warning (loc, type, expr, result);
1164 /* Subroutines of c_do_switch_warnings, called via splay_tree_foreach.
1165 Used to verify that case values match up with enumerator values. */
1167 static void
1168 match_case_to_enum_1 (tree key, tree type, tree label)
1170 /* Avoid warning about enums that have no enumerators. */
1171 if (TYPE_VALUES (type) == NULL_TREE)
1172 return;
1174 char buf[WIDE_INT_PRINT_BUFFER_SIZE];
1176 if (tree_fits_uhwi_p (key))
1177 print_dec (key, buf, UNSIGNED);
1178 else if (tree_fits_shwi_p (key))
1179 print_dec (key, buf, SIGNED);
1180 else
1181 print_hex (key, buf);
1183 if (TYPE_NAME (type) == NULL_TREE)
1184 warning_at (DECL_SOURCE_LOCATION (CASE_LABEL (label)),
1185 warn_switch ? OPT_Wswitch : OPT_Wswitch_enum,
1186 "case value %qs not in enumerated type",
1187 buf);
1188 else
1189 warning_at (DECL_SOURCE_LOCATION (CASE_LABEL (label)),
1190 warn_switch ? OPT_Wswitch : OPT_Wswitch_enum,
1191 "case value %qs not in enumerated type %qT",
1192 buf, type);
1195 /* Subroutine of c_do_switch_warnings, called via splay_tree_foreach.
1196 Used to verify that case values match up with enumerator values. */
1198 static int
1199 match_case_to_enum (splay_tree_node node, void *data)
1201 tree label = (tree) node->value;
1202 tree type = (tree) data;
1204 /* Skip default case. */
1205 if (!CASE_LOW (label))
1206 return 0;
1208 /* If CASE_LOW_SEEN is not set, that means CASE_LOW did not appear
1209 when we did our enum->case scan. Reset our scratch bit after. */
1210 if (!CASE_LOW_SEEN (label))
1211 match_case_to_enum_1 (CASE_LOW (label), type, label);
1212 else
1213 CASE_LOW_SEEN (label) = 0;
1215 /* If CASE_HIGH is non-null, we have a range. If CASE_HIGH_SEEN is
1216 not set, that means that CASE_HIGH did not appear when we did our
1217 enum->case scan. Reset our scratch bit after. */
1218 if (CASE_HIGH (label))
1220 if (!CASE_HIGH_SEEN (label))
1221 match_case_to_enum_1 (CASE_HIGH (label), type, label);
1222 else
1223 CASE_HIGH_SEEN (label) = 0;
1226 return 0;
1229 /* Handle -Wswitch*. Called from the front end after parsing the
1230 switch construct. */
1231 /* ??? Should probably be somewhere generic, since other languages
1232 besides C and C++ would want this. At the moment, however, C/C++
1233 are the only tree-ssa languages that support enumerations at all,
1234 so the point is moot. */
1236 void
1237 c_do_switch_warnings (splay_tree cases, location_t switch_location,
1238 tree type, tree cond, bool bool_cond_p,
1239 bool outside_range_p)
1241 splay_tree_node default_node;
1242 splay_tree_node node;
1243 tree chain;
1245 if (!warn_switch && !warn_switch_enum && !warn_switch_default
1246 && !warn_switch_bool)
1247 return;
1249 default_node = splay_tree_lookup (cases, (splay_tree_key) NULL);
1250 if (!default_node)
1251 warning_at (switch_location, OPT_Wswitch_default,
1252 "switch missing default case");
1254 /* There are certain cases where -Wswitch-bool warnings aren't
1255 desirable, such as
1256 switch (boolean)
1258 case true: ...
1259 case false: ...
1261 so be careful here. */
1262 if (warn_switch_bool && bool_cond_p)
1264 splay_tree_node min_node;
1265 /* If there's a default node, it's also the value with the minimal
1266 key. So look at the penultimate key (if any). */
1267 if (default_node)
1268 min_node = splay_tree_successor (cases, (splay_tree_key) NULL);
1269 else
1270 min_node = splay_tree_min (cases);
1271 tree min = min_node ? (tree) min_node->key : NULL_TREE;
1273 splay_tree_node max_node = splay_tree_max (cases);
1274 /* This might be a case range, so look at the value with the
1275 maximal key and then check CASE_HIGH. */
1276 tree max = max_node ? (tree) max_node->value : NULL_TREE;
1277 if (max)
1278 max = CASE_HIGH (max) ? CASE_HIGH (max) : CASE_LOW (max);
1280 /* If there's a case value > 1 or < 0, that is outside bool
1281 range, warn. */
1282 if (outside_range_p
1283 || (max && wi::gts_p (max, 1))
1284 || (min && wi::lts_p (min, 0))
1285 /* And handle the
1286 switch (boolean)
1288 case true: ...
1289 case false: ...
1290 default: ...
1292 case, where we want to warn. */
1293 || (default_node
1294 && max && wi::eq_p (max, 1)
1295 && min && wi::eq_p (min, 0)))
1296 warning_at (switch_location, OPT_Wswitch_bool,
1297 "switch condition has boolean value");
1300 /* From here on, we only care about enumerated types. */
1301 if (!type || TREE_CODE (type) != ENUMERAL_TYPE)
1302 return;
1304 /* From here on, we only care about -Wswitch and -Wswitch-enum. */
1305 if (!warn_switch_enum && !warn_switch)
1306 return;
1308 /* Check the cases. Warn about case values which are not members of
1309 the enumerated type. For -Wswitch-enum, or for -Wswitch when
1310 there is no default case, check that exactly all enumeration
1311 literals are covered by the cases. */
1313 /* Clearing COND if it is not an integer constant simplifies
1314 the tests inside the loop below. */
1315 if (TREE_CODE (cond) != INTEGER_CST)
1316 cond = NULL_TREE;
1318 /* The time complexity here is O(N*lg(N)) worst case, but for the
1319 common case of monotonically increasing enumerators, it is
1320 O(N), since the nature of the splay tree will keep the next
1321 element adjacent to the root at all times. */
1323 for (chain = TYPE_VALUES (type); chain; chain = TREE_CHAIN (chain))
1325 tree value = TREE_VALUE (chain);
1326 if (TREE_CODE (value) == CONST_DECL)
1327 value = DECL_INITIAL (value);
1328 node = splay_tree_lookup (cases, (splay_tree_key) value);
1329 if (node)
1331 /* Mark the CASE_LOW part of the case entry as seen. */
1332 tree label = (tree) node->value;
1333 CASE_LOW_SEEN (label) = 1;
1334 continue;
1337 /* Even though there wasn't an exact match, there might be a
1338 case range which includes the enumerator's value. */
1339 node = splay_tree_predecessor (cases, (splay_tree_key) value);
1340 if (node && CASE_HIGH ((tree) node->value))
1342 tree label = (tree) node->value;
1343 int cmp = tree_int_cst_compare (CASE_HIGH (label), value);
1344 if (cmp >= 0)
1346 /* If we match the upper bound exactly, mark the CASE_HIGH
1347 part of the case entry as seen. */
1348 if (cmp == 0)
1349 CASE_HIGH_SEEN (label) = 1;
1350 continue;
1354 /* We've now determined that this enumerated literal isn't
1355 handled by the case labels of the switch statement. */
1357 /* If the switch expression is a constant, we only really care
1358 about whether that constant is handled by the switch. */
1359 if (cond && tree_int_cst_compare (cond, value))
1360 continue;
1362 /* If there is a default_node, the only relevant option is
1363 Wswitch-enum. Otherwise, if both are enabled then we prefer
1364 to warn using -Wswitch because -Wswitch is enabled by -Wall
1365 while -Wswitch-enum is explicit. */
1366 warning_at (switch_location,
1367 (default_node || !warn_switch
1368 ? OPT_Wswitch_enum
1369 : OPT_Wswitch),
1370 "enumeration value %qE not handled in switch",
1371 TREE_PURPOSE (chain));
1374 /* Warn if there are case expressions that don't correspond to
1375 enumerators. This can occur since C and C++ don't enforce
1376 type-checking of assignments to enumeration variables.
1378 The time complexity here is now always O(N) worst case, since
1379 we should have marked both the lower bound and upper bound of
1380 every disjoint case label, with CASE_LOW_SEEN and CASE_HIGH_SEEN
1381 above. This scan also resets those fields. */
1383 splay_tree_foreach (cases, match_case_to_enum, type);
1386 /* Warn for A ?: C expressions (with B omitted) where A is a boolean
1387 expression, because B will always be true. */
1389 void
1390 warn_for_omitted_condop (location_t location, tree cond)
1392 /* In C++ template declarations it can happen that the type is dependent
1393 and not yet known, thus TREE_TYPE (cond) == NULL_TREE. */
1394 if (truth_value_p (TREE_CODE (cond))
1395 || (TREE_TYPE (cond) != NULL_TREE
1396 && TREE_CODE (TREE_TYPE (cond)) == BOOLEAN_TYPE))
1397 warning_at (location, OPT_Wparentheses,
1398 "the omitted middle operand in ?: will always be %<true%>, "
1399 "suggest explicit middle operand");
1402 /* Give an error for storing into ARG, which is 'const'. USE indicates
1403 how ARG was being used. */
1405 void
1406 readonly_error (location_t loc, tree arg, enum lvalue_use use)
1408 gcc_assert (use == lv_assign || use == lv_increment || use == lv_decrement
1409 || use == lv_asm);
1410 /* Using this macro rather than (for example) arrays of messages
1411 ensures that all the format strings are checked at compile
1412 time. */
1413 #define READONLY_MSG(A, I, D, AS) (use == lv_assign ? (A) \
1414 : (use == lv_increment ? (I) \
1415 : (use == lv_decrement ? (D) : (AS))))
1416 if (TREE_CODE (arg) == COMPONENT_REF)
1418 if (TYPE_READONLY (TREE_TYPE (TREE_OPERAND (arg, 0))))
1419 error_at (loc, READONLY_MSG (G_("assignment of member "
1420 "%qD in read-only object"),
1421 G_("increment of member "
1422 "%qD in read-only object"),
1423 G_("decrement of member "
1424 "%qD in read-only object"),
1425 G_("member %qD in read-only object "
1426 "used as %<asm%> output")),
1427 TREE_OPERAND (arg, 1));
1428 else
1429 error_at (loc, READONLY_MSG (G_("assignment of read-only member %qD"),
1430 G_("increment of read-only member %qD"),
1431 G_("decrement of read-only member %qD"),
1432 G_("read-only member %qD used as %<asm%> output")),
1433 TREE_OPERAND (arg, 1));
1435 else if (VAR_P (arg))
1436 error_at (loc, READONLY_MSG (G_("assignment of read-only variable %qD"),
1437 G_("increment of read-only variable %qD"),
1438 G_("decrement of read-only variable %qD"),
1439 G_("read-only variable %qD used as %<asm%> output")),
1440 arg);
1441 else if (TREE_CODE (arg) == PARM_DECL)
1442 error_at (loc, READONLY_MSG (G_("assignment of read-only parameter %qD"),
1443 G_("increment of read-only parameter %qD"),
1444 G_("decrement of read-only parameter %qD"),
1445 G_("read-only parameter %qD use as %<asm%> output")),
1446 arg);
1447 else if (TREE_CODE (arg) == RESULT_DECL)
1449 gcc_assert (c_dialect_cxx ());
1450 error_at (loc, READONLY_MSG (G_("assignment of "
1451 "read-only named return value %qD"),
1452 G_("increment of "
1453 "read-only named return value %qD"),
1454 G_("decrement of "
1455 "read-only named return value %qD"),
1456 G_("read-only named return value %qD "
1457 "used as %<asm%>output")),
1458 arg);
1460 else if (TREE_CODE (arg) == FUNCTION_DECL)
1461 error_at (loc, READONLY_MSG (G_("assignment of function %qD"),
1462 G_("increment of function %qD"),
1463 G_("decrement of function %qD"),
1464 G_("function %qD used as %<asm%> output")),
1465 arg);
1466 else
1467 error_at (loc, READONLY_MSG (G_("assignment of read-only location %qE"),
1468 G_("increment of read-only location %qE"),
1469 G_("decrement of read-only location %qE"),
1470 G_("read-only location %qE used as %<asm%> output")),
1471 arg);
1474 /* Print an error message for an invalid lvalue. USE says
1475 how the lvalue is being used and so selects the error message. LOC
1476 is the location for the error. */
1478 void
1479 lvalue_error (location_t loc, enum lvalue_use use)
1481 switch (use)
1483 case lv_assign:
1484 error_at (loc, "lvalue required as left operand of assignment");
1485 break;
1486 case lv_increment:
1487 error_at (loc, "lvalue required as increment operand");
1488 break;
1489 case lv_decrement:
1490 error_at (loc, "lvalue required as decrement operand");
1491 break;
1492 case lv_addressof:
1493 error_at (loc, "lvalue required as unary %<&%> operand");
1494 break;
1495 case lv_asm:
1496 error_at (loc, "lvalue required in asm statement");
1497 break;
1498 default:
1499 gcc_unreachable ();
1503 /* Print an error message for an invalid indirection of type TYPE.
1504 ERRSTRING is the name of the operator for the indirection. */
1506 void
1507 invalid_indirection_error (location_t loc, tree type, ref_operator errstring)
1509 switch (errstring)
1511 case RO_NULL:
1512 gcc_assert (c_dialect_cxx ());
1513 error_at (loc, "invalid type argument (have %qT)", type);
1514 break;
1515 case RO_ARRAY_INDEXING:
1516 error_at (loc,
1517 "invalid type argument of array indexing (have %qT)",
1518 type);
1519 break;
1520 case RO_UNARY_STAR:
1521 error_at (loc,
1522 "invalid type argument of unary %<*%> (have %qT)",
1523 type);
1524 break;
1525 case RO_ARROW:
1526 error_at (loc,
1527 "invalid type argument of %<->%> (have %qT)",
1528 type);
1529 break;
1530 case RO_ARROW_STAR:
1531 error_at (loc,
1532 "invalid type argument of %<->*%> (have %qT)",
1533 type);
1534 break;
1535 case RO_IMPLICIT_CONVERSION:
1536 error_at (loc,
1537 "invalid type argument of implicit conversion (have %qT)",
1538 type);
1539 break;
1540 default:
1541 gcc_unreachable ();
1545 /* Subscripting with type char is likely to lose on a machine where
1546 chars are signed. So warn on any machine, but optionally. Don't
1547 warn for unsigned char since that type is safe. Don't warn for
1548 signed char because anyone who uses that must have done so
1549 deliberately. Furthermore, we reduce the false positive load by
1550 warning only for non-constant value of type char. */
1552 void
1553 warn_array_subscript_with_type_char (location_t loc, tree index)
1555 if (TYPE_MAIN_VARIANT (TREE_TYPE (index)) == char_type_node
1556 && TREE_CODE (index) != INTEGER_CST)
1557 warning_at (loc, OPT_Wchar_subscripts,
1558 "array subscript has type %<char%>");
1561 /* Implement -Wparentheses for the unexpected C precedence rules, to
1562 cover cases like x + y << z which readers are likely to
1563 misinterpret. We have seen an expression in which CODE is a binary
1564 operator used to combine expressions ARG_LEFT and ARG_RIGHT, which
1565 before folding had CODE_LEFT and CODE_RIGHT. CODE_LEFT and
1566 CODE_RIGHT may be ERROR_MARK, which means that that side of the
1567 expression was not formed using a binary or unary operator, or it
1568 was enclosed in parentheses. */
1570 void
1571 warn_about_parentheses (location_t loc, enum tree_code code,
1572 enum tree_code code_left, tree arg_left,
1573 enum tree_code code_right, tree arg_right)
1575 if (!warn_parentheses)
1576 return;
1578 /* This macro tests that the expression ARG with original tree code
1579 CODE appears to be a boolean expression. or the result of folding a
1580 boolean expression. */
1581 #define APPEARS_TO_BE_BOOLEAN_EXPR_P(CODE, ARG) \
1582 (truth_value_p (TREE_CODE (ARG)) \
1583 || TREE_CODE (TREE_TYPE (ARG)) == BOOLEAN_TYPE \
1584 /* Folding may create 0 or 1 integers from other expressions. */ \
1585 || ((CODE) != INTEGER_CST \
1586 && (integer_onep (ARG) || integer_zerop (ARG))))
1588 switch (code)
1590 case LSHIFT_EXPR:
1591 if (code_left == PLUS_EXPR)
1592 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
1593 "suggest parentheses around %<+%> inside %<<<%>");
1594 else if (code_right == PLUS_EXPR)
1595 warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
1596 "suggest parentheses around %<+%> inside %<<<%>");
1597 else if (code_left == MINUS_EXPR)
1598 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
1599 "suggest parentheses around %<-%> inside %<<<%>");
1600 else if (code_right == MINUS_EXPR)
1601 warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
1602 "suggest parentheses around %<-%> inside %<<<%>");
1603 return;
1605 case RSHIFT_EXPR:
1606 if (code_left == PLUS_EXPR)
1607 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
1608 "suggest parentheses around %<+%> inside %<>>%>");
1609 else if (code_right == PLUS_EXPR)
1610 warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
1611 "suggest parentheses around %<+%> inside %<>>%>");
1612 else if (code_left == MINUS_EXPR)
1613 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
1614 "suggest parentheses around %<-%> inside %<>>%>");
1615 else if (code_right == MINUS_EXPR)
1616 warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
1617 "suggest parentheses around %<-%> inside %<>>%>");
1618 return;
1620 case TRUTH_ORIF_EXPR:
1621 if (code_left == TRUTH_ANDIF_EXPR)
1622 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
1623 "suggest parentheses around %<&&%> within %<||%>");
1624 else if (code_right == TRUTH_ANDIF_EXPR)
1625 warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
1626 "suggest parentheses around %<&&%> within %<||%>");
1627 return;
1629 case BIT_IOR_EXPR:
1630 if (code_left == BIT_AND_EXPR || code_left == BIT_XOR_EXPR
1631 || code_left == PLUS_EXPR || code_left == MINUS_EXPR)
1632 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
1633 "suggest parentheses around arithmetic in operand of %<|%>");
1634 else if (code_right == BIT_AND_EXPR || code_right == BIT_XOR_EXPR
1635 || code_right == PLUS_EXPR || code_right == MINUS_EXPR)
1636 warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
1637 "suggest parentheses around arithmetic in operand of %<|%>");
1638 /* Check cases like x|y==z */
1639 else if (TREE_CODE_CLASS (code_left) == tcc_comparison)
1640 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
1641 "suggest parentheses around comparison in operand of %<|%>");
1642 else if (TREE_CODE_CLASS (code_right) == tcc_comparison)
1643 warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
1644 "suggest parentheses around comparison in operand of %<|%>");
1645 /* Check cases like !x | y */
1646 else if (code_left == TRUTH_NOT_EXPR
1647 && !APPEARS_TO_BE_BOOLEAN_EXPR_P (code_right, arg_right))
1648 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
1649 "suggest parentheses around operand of "
1650 "%<!%> or change %<|%> to %<||%> or %<!%> to %<~%>");
1651 return;
1653 case BIT_XOR_EXPR:
1654 if (code_left == BIT_AND_EXPR
1655 || code_left == PLUS_EXPR || code_left == MINUS_EXPR)
1656 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
1657 "suggest parentheses around arithmetic in operand of %<^%>");
1658 else if (code_right == BIT_AND_EXPR
1659 || code_right == PLUS_EXPR || code_right == MINUS_EXPR)
1660 warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
1661 "suggest parentheses around arithmetic in operand of %<^%>");
1662 /* Check cases like x^y==z */
1663 else if (TREE_CODE_CLASS (code_left) == tcc_comparison)
1664 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
1665 "suggest parentheses around comparison in operand of %<^%>");
1666 else if (TREE_CODE_CLASS (code_right) == tcc_comparison)
1667 warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
1668 "suggest parentheses around comparison in operand of %<^%>");
1669 return;
1671 case BIT_AND_EXPR:
1672 if (code_left == PLUS_EXPR)
1673 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
1674 "suggest parentheses around %<+%> in operand of %<&%>");
1675 else if (code_right == PLUS_EXPR)
1676 warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
1677 "suggest parentheses around %<+%> in operand of %<&%>");
1678 else if (code_left == MINUS_EXPR)
1679 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
1680 "suggest parentheses around %<-%> in operand of %<&%>");
1681 else if (code_right == MINUS_EXPR)
1682 warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
1683 "suggest parentheses around %<-%> in operand of %<&%>");
1684 /* Check cases like x&y==z */
1685 else if (TREE_CODE_CLASS (code_left) == tcc_comparison)
1686 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
1687 "suggest parentheses around comparison in operand of %<&%>");
1688 else if (TREE_CODE_CLASS (code_right) == tcc_comparison)
1689 warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
1690 "suggest parentheses around comparison in operand of %<&%>");
1691 /* Check cases like !x & y */
1692 else if (code_left == TRUTH_NOT_EXPR
1693 && !APPEARS_TO_BE_BOOLEAN_EXPR_P (code_right, arg_right))
1694 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
1695 "suggest parentheses around operand of "
1696 "%<!%> or change %<&%> to %<&&%> or %<!%> to %<~%>");
1697 return;
1699 case EQ_EXPR:
1700 if (TREE_CODE_CLASS (code_left) == tcc_comparison)
1701 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
1702 "suggest parentheses around comparison in operand of %<==%>");
1703 else if (TREE_CODE_CLASS (code_right) == tcc_comparison)
1704 warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
1705 "suggest parentheses around comparison in operand of %<==%>");
1706 return;
1707 case NE_EXPR:
1708 if (TREE_CODE_CLASS (code_left) == tcc_comparison)
1709 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
1710 "suggest parentheses around comparison in operand of %<!=%>");
1711 else if (TREE_CODE_CLASS (code_right) == tcc_comparison)
1712 warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
1713 "suggest parentheses around comparison in operand of %<!=%>");
1714 return;
1716 default:
1717 if (TREE_CODE_CLASS (code) == tcc_comparison)
1719 if (TREE_CODE_CLASS (code_left) == tcc_comparison
1720 && code_left != NE_EXPR && code_left != EQ_EXPR
1721 && INTEGRAL_TYPE_P (TREE_TYPE (arg_left)))
1722 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
1723 "comparisons like %<X<=Y<=Z%> do not "
1724 "have their mathematical meaning");
1725 else if (TREE_CODE_CLASS (code_right) == tcc_comparison
1726 && code_right != NE_EXPR && code_right != EQ_EXPR
1727 && INTEGRAL_TYPE_P (TREE_TYPE (arg_right)))
1728 warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
1729 "comparisons like %<X<=Y<=Z%> do not "
1730 "have their mathematical meaning");
1732 return;
1734 #undef NOT_A_BOOLEAN_EXPR_P
1737 /* If LABEL (a LABEL_DECL) has not been used, issue a warning. */
1739 void
1740 warn_for_unused_label (tree label)
1742 if (!TREE_USED (label))
1744 if (DECL_INITIAL (label))
1745 warning (OPT_Wunused_label, "label %q+D defined but not used", label);
1746 else
1747 warning (OPT_Wunused_label, "label %q+D declared but not defined", label);
1749 else if (asan_sanitize_use_after_scope ())
1751 if (asan_used_labels == NULL)
1752 asan_used_labels = new hash_set<tree> (16);
1754 asan_used_labels->add (label);
1758 /* Warn for division by zero according to the value of DIVISOR. LOC
1759 is the location of the division operator. */
1761 void
1762 warn_for_div_by_zero (location_t loc, tree divisor)
1764 /* If DIVISOR is zero, and has integral or fixed-point type, issue a warning
1765 about division by zero. Do not issue a warning if DIVISOR has a
1766 floating-point type, since we consider 0.0/0.0 a valid way of
1767 generating a NaN. */
1768 if (c_inhibit_evaluation_warnings == 0
1769 && (integer_zerop (divisor) || fixed_zerop (divisor)))
1770 warning_at (loc, OPT_Wdiv_by_zero, "division by zero");
1773 /* Warn for patterns where memset appears to be used incorrectly. The
1774 warning location should be LOC. ARG0, and ARG2 are the first and
1775 last arguments to the call, while LITERAL_ZERO_MASK has a 1 bit for
1776 each argument that was a literal zero. */
1778 void
1779 warn_for_memset (location_t loc, tree arg0, tree arg2,
1780 int literal_zero_mask)
1782 if (warn_memset_transposed_args
1783 && integer_zerop (arg2)
1784 && (literal_zero_mask & (1 << 2)) != 0
1785 && (literal_zero_mask & (1 << 1)) == 0)
1786 warning_at (loc, OPT_Wmemset_transposed_args,
1787 "%<memset%> used with constant zero length "
1788 "parameter; this could be due to transposed "
1789 "parameters");
1791 if (warn_memset_elt_size && TREE_CODE (arg2) == INTEGER_CST)
1793 STRIP_NOPS (arg0);
1794 if (TREE_CODE (arg0) == ADDR_EXPR)
1795 arg0 = TREE_OPERAND (arg0, 0);
1796 tree type = TREE_TYPE (arg0);
1797 if (type != NULL_TREE && TREE_CODE (type) == ARRAY_TYPE)
1799 tree elt_type = TREE_TYPE (type);
1800 tree domain = TYPE_DOMAIN (type);
1801 if (!integer_onep (TYPE_SIZE_UNIT (elt_type))
1802 && domain != NULL_TREE
1803 && TYPE_MAXVAL (domain)
1804 && TYPE_MINVAL (domain)
1805 && integer_zerop (TYPE_MINVAL (domain))
1806 && integer_onep (fold_build2 (MINUS_EXPR, domain,
1807 arg2,
1808 TYPE_MAXVAL (domain))))
1809 warning_at (loc, OPT_Wmemset_elt_size,
1810 "%<memset%> used with length equal to "
1811 "number of elements without multiplication "
1812 "by element size");
1817 /* Subroutine of build_binary_op. Give warnings for comparisons
1818 between signed and unsigned quantities that may fail. Do the
1819 checking based on the original operand trees ORIG_OP0 and ORIG_OP1,
1820 so that casts will be considered, but default promotions won't
1823 LOCATION is the location of the comparison operator.
1825 The arguments of this function map directly to local variables
1826 of build_binary_op. */
1828 void
1829 warn_for_sign_compare (location_t location,
1830 tree orig_op0, tree orig_op1,
1831 tree op0, tree op1,
1832 tree result_type, enum tree_code resultcode)
1834 int op0_signed = !TYPE_UNSIGNED (TREE_TYPE (orig_op0));
1835 int op1_signed = !TYPE_UNSIGNED (TREE_TYPE (orig_op1));
1836 int unsignedp0, unsignedp1;
1838 /* In C++, check for comparison of different enum types. */
1839 if (c_dialect_cxx()
1840 && TREE_CODE (TREE_TYPE (orig_op0)) == ENUMERAL_TYPE
1841 && TREE_CODE (TREE_TYPE (orig_op1)) == ENUMERAL_TYPE
1842 && TYPE_MAIN_VARIANT (TREE_TYPE (orig_op0))
1843 != TYPE_MAIN_VARIANT (TREE_TYPE (orig_op1)))
1845 warning_at (location,
1846 OPT_Wsign_compare, "comparison between types %qT and %qT",
1847 TREE_TYPE (orig_op0), TREE_TYPE (orig_op1));
1850 /* Do not warn if the comparison is being done in a signed type,
1851 since the signed type will only be chosen if it can represent
1852 all the values of the unsigned type. */
1853 if (!TYPE_UNSIGNED (result_type))
1854 /* OK */;
1855 /* Do not warn if both operands are unsigned. */
1856 else if (op0_signed == op1_signed)
1857 /* OK */;
1858 else
1860 tree sop, uop, base_type;
1861 bool ovf;
1863 if (op0_signed)
1864 sop = orig_op0, uop = orig_op1;
1865 else
1866 sop = orig_op1, uop = orig_op0;
1868 STRIP_TYPE_NOPS (sop);
1869 STRIP_TYPE_NOPS (uop);
1870 base_type = (TREE_CODE (result_type) == COMPLEX_TYPE
1871 ? TREE_TYPE (result_type) : result_type);
1873 /* Do not warn if the signed quantity is an unsuffixed integer
1874 literal (or some static constant expression involving such
1875 literals or a conditional expression involving such literals)
1876 and it is non-negative. */
1877 if (tree_expr_nonnegative_warnv_p (sop, &ovf))
1878 /* OK */;
1879 /* Do not warn if the comparison is an equality operation, the
1880 unsigned quantity is an integral constant, and it would fit
1881 in the result if the result were signed. */
1882 else if (TREE_CODE (uop) == INTEGER_CST
1883 && (resultcode == EQ_EXPR || resultcode == NE_EXPR)
1884 && int_fits_type_p (uop, c_common_signed_type (base_type)))
1885 /* OK */;
1886 /* In C, do not warn if the unsigned quantity is an enumeration
1887 constant and its maximum value would fit in the result if the
1888 result were signed. */
1889 else if (!c_dialect_cxx() && TREE_CODE (uop) == INTEGER_CST
1890 && TREE_CODE (TREE_TYPE (uop)) == ENUMERAL_TYPE
1891 && int_fits_type_p (TYPE_MAX_VALUE (TREE_TYPE (uop)),
1892 c_common_signed_type (base_type)))
1893 /* OK */;
1894 else
1895 warning_at (location,
1896 OPT_Wsign_compare,
1897 "comparison between signed and unsigned integer expressions");
1900 /* Warn if two unsigned values are being compared in a size larger
1901 than their original size, and one (and only one) is the result of
1902 a `~' operator. This comparison will always fail.
1904 Also warn if one operand is a constant, and the constant does not
1905 have all bits set that are set in the ~ operand when it is
1906 extended. */
1908 op0 = c_common_get_narrower (op0, &unsignedp0);
1909 op1 = c_common_get_narrower (op1, &unsignedp1);
1911 if ((TREE_CODE (op0) == BIT_NOT_EXPR)
1912 ^ (TREE_CODE (op1) == BIT_NOT_EXPR))
1914 if (TREE_CODE (op0) == BIT_NOT_EXPR)
1915 op0 = c_common_get_narrower (TREE_OPERAND (op0, 0), &unsignedp0);
1916 if (TREE_CODE (op1) == BIT_NOT_EXPR)
1917 op1 = c_common_get_narrower (TREE_OPERAND (op1, 0), &unsignedp1);
1919 if (tree_fits_shwi_p (op0) || tree_fits_shwi_p (op1))
1921 tree primop;
1922 HOST_WIDE_INT constant, mask;
1923 int unsignedp;
1924 unsigned int bits;
1926 if (tree_fits_shwi_p (op0))
1928 primop = op1;
1929 unsignedp = unsignedp1;
1930 constant = tree_to_shwi (op0);
1932 else
1934 primop = op0;
1935 unsignedp = unsignedp0;
1936 constant = tree_to_shwi (op1);
1939 bits = TYPE_PRECISION (TREE_TYPE (primop));
1940 if (bits < TYPE_PRECISION (result_type)
1941 && bits < HOST_BITS_PER_LONG && unsignedp)
1943 mask = HOST_WIDE_INT_M1U << bits;
1944 if ((mask & constant) != mask)
1946 if (constant == 0)
1947 warning_at (location, OPT_Wsign_compare,
1948 "promoted ~unsigned is always non-zero");
1949 else
1950 warning_at (location, OPT_Wsign_compare,
1951 "comparison of promoted ~unsigned with constant");
1955 else if (unsignedp0 && unsignedp1
1956 && (TYPE_PRECISION (TREE_TYPE (op0))
1957 < TYPE_PRECISION (result_type))
1958 && (TYPE_PRECISION (TREE_TYPE (op1))
1959 < TYPE_PRECISION (result_type)))
1960 warning_at (location, OPT_Wsign_compare,
1961 "comparison of promoted ~unsigned with unsigned");
1965 /* RESULT_TYPE is the result of converting TYPE1 and TYPE2 to a common
1966 type via c_common_type. If -Wdouble-promotion is in use, and the
1967 conditions for warning have been met, issue a warning. GMSGID is
1968 the warning message. It must have two %T specifiers for the type
1969 that was converted (generally "float") and the type to which it was
1970 converted (generally "double), respectively. LOC is the location
1971 to which the warning should refer. */
1973 void
1974 do_warn_double_promotion (tree result_type, tree type1, tree type2,
1975 const char *gmsgid, location_t loc)
1977 tree source_type;
1979 if (!warn_double_promotion)
1980 return;
1981 /* If the conversion will not occur at run-time, there is no need to
1982 warn about it. */
1983 if (c_inhibit_evaluation_warnings)
1984 return;
1985 /* If an invalid conversion has occured, don't warn. */
1986 if (result_type == error_mark_node)
1987 return;
1988 if (TYPE_MAIN_VARIANT (result_type) != double_type_node
1989 && TYPE_MAIN_VARIANT (result_type) != complex_double_type_node)
1990 return;
1991 if (TYPE_MAIN_VARIANT (type1) == float_type_node
1992 || TYPE_MAIN_VARIANT (type1) == complex_float_type_node)
1993 source_type = type1;
1994 else if (TYPE_MAIN_VARIANT (type2) == float_type_node
1995 || TYPE_MAIN_VARIANT (type2) == complex_float_type_node)
1996 source_type = type2;
1997 else
1998 return;
1999 warning_at (loc, OPT_Wdouble_promotion, gmsgid, source_type, result_type);
2002 /* Possibly warn about unused parameters. */
2004 void
2005 do_warn_unused_parameter (tree fn)
2007 tree decl;
2009 for (decl = DECL_ARGUMENTS (fn);
2010 decl; decl = DECL_CHAIN (decl))
2011 if (!TREE_USED (decl) && TREE_CODE (decl) == PARM_DECL
2012 && DECL_NAME (decl) && !DECL_ARTIFICIAL (decl)
2013 && !TREE_NO_WARNING (decl))
2014 warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wunused_parameter,
2015 "unused parameter %qD", decl);
2018 /* If DECL is a typedef that is declared in the current function,
2019 record it for the purpose of -Wunused-local-typedefs. */
2021 void
2022 record_locally_defined_typedef (tree decl)
2024 struct c_language_function *l;
2026 if (!warn_unused_local_typedefs
2027 || cfun == NULL
2028 /* if this is not a locally defined typedef then we are not
2029 interested. */
2030 || !is_typedef_decl (decl)
2031 || !decl_function_context (decl))
2032 return;
2034 l = (struct c_language_function *) cfun->language;
2035 vec_safe_push (l->local_typedefs, decl);
2038 /* If T is a TYPE_DECL declared locally, mark it as used. */
2040 void
2041 maybe_record_typedef_use (tree t)
2043 if (!is_typedef_decl (t))
2044 return;
2046 TREE_USED (t) = true;
2049 /* Warn if there are some unused locally defined typedefs in the
2050 current function. */
2052 void
2053 maybe_warn_unused_local_typedefs (void)
2055 int i;
2056 tree decl;
2057 /* The number of times we have emitted -Wunused-local-typedefs
2058 warnings. If this is different from errorcount, that means some
2059 unrelated errors have been issued. In which case, we'll avoid
2060 emitting "unused-local-typedefs" warnings. */
2061 static int unused_local_typedefs_warn_count;
2062 struct c_language_function *l;
2064 if (cfun == NULL)
2065 return;
2067 if ((l = (struct c_language_function *) cfun->language) == NULL)
2068 return;
2070 if (warn_unused_local_typedefs
2071 && errorcount == unused_local_typedefs_warn_count)
2073 FOR_EACH_VEC_SAFE_ELT (l->local_typedefs, i, decl)
2074 if (!TREE_USED (decl))
2075 warning_at (DECL_SOURCE_LOCATION (decl),
2076 OPT_Wunused_local_typedefs,
2077 "typedef %qD locally defined but not used", decl);
2078 unused_local_typedefs_warn_count = errorcount;
2081 vec_free (l->local_typedefs);
2084 /* If we're creating an if-else-if condition chain, first see if we
2085 already have this COND in the CHAIN. If so, warn and don't add COND
2086 into the vector, otherwise add the COND there. LOC is the location
2087 of COND. */
2089 void
2090 warn_duplicated_cond_add_or_warn (location_t loc, tree cond, vec<tree> **chain)
2092 /* No chain has been created yet. Do nothing. */
2093 if (*chain == NULL)
2094 return;
2096 if (TREE_SIDE_EFFECTS (cond))
2098 /* Uh-oh! This condition has a side-effect, thus invalidates
2099 the whole chain. */
2100 delete *chain;
2101 *chain = NULL;
2102 return;
2105 unsigned int ix;
2106 tree t;
2107 bool found = false;
2108 FOR_EACH_VEC_ELT (**chain, ix, t)
2109 if (operand_equal_p (cond, t, 0))
2111 if (warning_at (loc, OPT_Wduplicated_cond,
2112 "duplicated %<if%> condition"))
2113 inform (EXPR_LOCATION (t), "previously used here");
2114 found = true;
2115 break;
2118 if (!found
2119 && !CONSTANT_CLASS_P (cond)
2120 /* Don't infinitely grow the chain. */
2121 && (*chain)->length () < 512)
2122 (*chain)->safe_push (cond);
2125 /* Check and possibly warn if two declarations have contradictory
2126 attributes, such as always_inline vs. noinline. */
2128 bool
2129 diagnose_mismatched_attributes (tree olddecl, tree newdecl)
2131 bool warned = false;
2133 tree a1 = lookup_attribute ("optimize", DECL_ATTRIBUTES (olddecl));
2134 tree a2 = lookup_attribute ("optimize", DECL_ATTRIBUTES (newdecl));
2135 /* An optimization attribute applied on a declaration after the
2136 definition is likely not what the user wanted. */
2137 if (a2 != NULL_TREE
2138 && DECL_SAVED_TREE (olddecl) != NULL_TREE
2139 && (a1 == NULL_TREE || !attribute_list_equal (a1, a2)))
2140 warned |= warning (OPT_Wattributes,
2141 "optimization attribute on %qD follows "
2142 "definition but the attribute doesn%'t match",
2143 newdecl);
2145 /* Diagnose inline __attribute__ ((noinline)) which is silly. */
2146 if (DECL_DECLARED_INLINE_P (newdecl)
2147 && DECL_UNINLINABLE (olddecl)
2148 && lookup_attribute ("noinline", DECL_ATTRIBUTES (olddecl)))
2149 warned |= warning (OPT_Wattributes, "inline declaration of %qD follows "
2150 "declaration with attribute noinline", newdecl);
2151 else if (DECL_DECLARED_INLINE_P (olddecl)
2152 && DECL_UNINLINABLE (newdecl)
2153 && lookup_attribute ("noinline", DECL_ATTRIBUTES (newdecl)))
2154 warned |= warning (OPT_Wattributes, "declaration of %q+D with attribute "
2155 "noinline follows inline declaration ", newdecl);
2156 else if (lookup_attribute ("noinline", DECL_ATTRIBUTES (newdecl))
2157 && lookup_attribute ("always_inline", DECL_ATTRIBUTES (olddecl)))
2158 warned |= warning (OPT_Wattributes, "declaration of %q+D with attribute "
2159 "%qs follows declaration with attribute %qs",
2160 newdecl, "noinline", "always_inline");
2161 else if (lookup_attribute ("always_inline", DECL_ATTRIBUTES (newdecl))
2162 && lookup_attribute ("noinline", DECL_ATTRIBUTES (olddecl)))
2163 warned |= warning (OPT_Wattributes, "declaration of %q+D with attribute "
2164 "%qs follows declaration with attribute %qs",
2165 newdecl, "always_inline", "noinline");
2166 else if (lookup_attribute ("cold", DECL_ATTRIBUTES (newdecl))
2167 && lookup_attribute ("hot", DECL_ATTRIBUTES (olddecl)))
2168 warned |= warning (OPT_Wattributes, "declaration of %q+D with attribute "
2169 "%qs follows declaration with attribute %qs",
2170 newdecl, "cold", "hot");
2171 else if (lookup_attribute ("hot", DECL_ATTRIBUTES (newdecl))
2172 && lookup_attribute ("cold", DECL_ATTRIBUTES (olddecl)))
2173 warned |= warning (OPT_Wattributes, "declaration of %q+D with attribute "
2174 "%qs follows declaration with attribute %qs",
2175 newdecl, "hot", "cold");
2176 return warned;
2179 /* Warn if signed left shift overflows. We don't warn
2180 about left-shifting 1 into the sign bit in C++14; cf.
2181 <http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3367.html#1457>
2182 LOC is a location of the shift; OP0 and OP1 are the operands.
2183 Return true if an overflow is detected, false otherwise. */
2185 bool
2186 maybe_warn_shift_overflow (location_t loc, tree op0, tree op1)
2188 if (TREE_CODE (op0) != INTEGER_CST
2189 || TREE_CODE (op1) != INTEGER_CST)
2190 return false;
2192 tree type0 = TREE_TYPE (op0);
2193 unsigned int prec0 = TYPE_PRECISION (type0);
2195 /* Left-hand operand must be signed. */
2196 if (TYPE_UNSIGNED (type0))
2197 return false;
2199 unsigned int min_prec = (wi::min_precision (op0, SIGNED)
2200 + TREE_INT_CST_LOW (op1));
2201 /* Handle the case of left-shifting 1 into the sign bit.
2202 * However, shifting 1 _out_ of the sign bit, as in
2203 * INT_MIN << 1, is considered an overflow.
2205 if (!tree_int_cst_sign_bit(op0) && min_prec == prec0 + 1)
2207 /* Never warn for C++14 onwards. */
2208 if (cxx_dialect >= cxx14)
2209 return false;
2210 /* Otherwise only if -Wshift-overflow=2. But return
2211 true to signal an overflow for the sake of integer
2212 constant expressions. */
2213 if (warn_shift_overflow < 2)
2214 return true;
2217 bool overflowed = min_prec > prec0;
2218 if (overflowed && c_inhibit_evaluation_warnings == 0)
2219 warning_at (loc, OPT_Wshift_overflow_,
2220 "result of %qE requires %u bits to represent, "
2221 "but %qT only has %u bits",
2222 build2_loc (loc, LSHIFT_EXPR, type0, op0, op1),
2223 min_prec, type0, prec0);
2225 return overflowed;
2228 /* Warn about boolean expression compared with an integer value different
2229 from true/false. Warns also e.g. about "(i1 == i2) == 2".
2230 LOC is the location of the comparison, CODE is its code, OP0 and OP1
2231 are the operands of the comparison. The caller must ensure that
2232 either operand is a boolean expression. */
2234 void
2235 maybe_warn_bool_compare (location_t loc, enum tree_code code, tree op0,
2236 tree op1)
2238 if (TREE_CODE_CLASS (code) != tcc_comparison)
2239 return;
2241 tree f, cst;
2242 if (f = fold_for_warn (op0),
2243 TREE_CODE (f) == INTEGER_CST)
2244 cst = op0 = f;
2245 else if (f = fold_for_warn (op1),
2246 TREE_CODE (f) == INTEGER_CST)
2247 cst = op1 = f;
2248 else
2249 return;
2251 if (!integer_zerop (cst) && !integer_onep (cst))
2253 int sign = (TREE_CODE (op0) == INTEGER_CST
2254 ? tree_int_cst_sgn (cst) : -tree_int_cst_sgn (cst));
2255 if (code == EQ_EXPR
2256 || ((code == GT_EXPR || code == GE_EXPR) && sign < 0)
2257 || ((code == LT_EXPR || code == LE_EXPR) && sign > 0))
2258 warning_at (loc, OPT_Wbool_compare, "comparison of constant %qE "
2259 "with boolean expression is always false", cst);
2260 else
2261 warning_at (loc, OPT_Wbool_compare, "comparison of constant %qE "
2262 "with boolean expression is always true", cst);
2264 else if (integer_zerop (cst) || integer_onep (cst))
2266 /* If the non-constant operand isn't of a boolean type, we
2267 don't want to warn here. */
2268 tree noncst = TREE_CODE (op0) == INTEGER_CST ? op1 : op0;
2269 /* Handle booleans promoted to integers. */
2270 if (bool_promoted_to_int_p (noncst))
2271 /* Warn. */;
2272 else if (TREE_CODE (TREE_TYPE (noncst)) != BOOLEAN_TYPE
2273 && !truth_value_p (TREE_CODE (noncst)))
2274 return;
2275 /* Do some magic to get the right diagnostics. */
2276 bool flag = TREE_CODE (op0) == INTEGER_CST;
2277 flag = integer_zerop (cst) ? flag : !flag;
2278 if ((code == GE_EXPR && !flag) || (code == LE_EXPR && flag))
2279 warning_at (loc, OPT_Wbool_compare, "comparison of constant %qE "
2280 "with boolean expression is always true", cst);
2281 else if ((code == LT_EXPR && !flag) || (code == GT_EXPR && flag))
2282 warning_at (loc, OPT_Wbool_compare, "comparison of constant %qE "
2283 "with boolean expression is always false", cst);
2287 /* Warn if an argument at position param_pos is passed to a
2288 restrict-qualified param, and it aliases with another argument. */
2290 void
2291 warn_for_restrict (unsigned param_pos, tree *argarray, unsigned nargs)
2293 tree arg = argarray[param_pos];
2294 if (TREE_VISITED (arg) || integer_zerop (arg))
2295 return;
2297 location_t loc = EXPR_LOC_OR_LOC (arg, input_location);
2298 gcc_rich_location richloc (loc);
2300 unsigned i;
2301 auto_vec<int, 16> arg_positions;
2303 for (i = 0; i < nargs; i++)
2305 if (i == param_pos)
2306 continue;
2308 tree current_arg = argarray[i];
2309 if (operand_equal_p (arg, current_arg, 0))
2311 TREE_VISITED (current_arg) = 1;
2312 arg_positions.safe_push (i + 1);
2316 if (arg_positions.is_empty ())
2317 return;
2319 int pos;
2320 FOR_EACH_VEC_ELT (arg_positions, i, pos)
2322 arg = argarray[pos - 1];
2323 if (EXPR_HAS_LOCATION (arg))
2324 richloc.add_range (EXPR_LOCATION (arg), false);
2327 warning_at_rich_loc_n (&richloc, OPT_Wrestrict, arg_positions.length (),
2328 "passing argument %i to restrict-qualified parameter"
2329 " aliases with argument %Z",
2330 "passing argument %i to restrict-qualified parameter"
2331 " aliases with arguments %Z",
2332 param_pos + 1, arg_positions.address (),
2333 arg_positions.length ());
2336 /* Callback function to determine whether an expression TP or one of its
2337 subexpressions comes from macro expansion. Used to suppress bogus
2338 warnings. */
2340 static tree
2341 expr_from_macro_expansion_r (tree *tp, int *, void *)
2343 if (CAN_HAVE_LOCATION_P (*tp)
2344 && from_macro_expansion_at (EXPR_LOCATION (*tp)))
2345 return integer_zero_node;
2347 return NULL_TREE;
2350 /* Possibly warn when an if-else has identical branches. */
2352 static void
2353 do_warn_duplicated_branches (tree expr)
2355 tree thenb = COND_EXPR_THEN (expr);
2356 tree elseb = COND_EXPR_ELSE (expr);
2358 /* Don't bother if any of the branches is missing. */
2359 if (thenb == NULL_TREE || elseb == NULL_TREE)
2360 return;
2362 /* And don't warn for empty statements. */
2363 if (TREE_CODE (thenb) == NOP_EXPR
2364 && TREE_TYPE (thenb) == void_type_node
2365 && TREE_OPERAND (thenb, 0) == size_zero_node)
2366 return;
2368 /* ... or empty branches. */
2369 if (TREE_CODE (thenb) == STATEMENT_LIST
2370 && STATEMENT_LIST_HEAD (thenb) == NULL)
2371 return;
2373 /* Compute the hash of the then branch. */
2374 inchash::hash hstate0 (0);
2375 inchash::add_expr (thenb, hstate0);
2376 hashval_t h0 = hstate0.end ();
2378 /* Compute the hash of the else branch. */
2379 inchash::hash hstate1 (0);
2380 inchash::add_expr (elseb, hstate1);
2381 hashval_t h1 = hstate1.end ();
2383 /* Compare the hashes. */
2384 if (h0 == h1
2385 && operand_equal_p (thenb, elseb, OEP_LEXICOGRAPHIC)
2386 /* Don't warn if any of the branches or their subexpressions comes
2387 from a macro. */
2388 && !walk_tree_without_duplicates (&thenb, expr_from_macro_expansion_r,
2389 NULL)
2390 && !walk_tree_without_duplicates (&elseb, expr_from_macro_expansion_r,
2391 NULL))
2392 warning_at (EXPR_LOCATION (expr), OPT_Wduplicated_branches,
2393 "this condition has identical branches");
2396 /* Callback for c_genericize to implement -Wduplicated-branches. */
2398 tree
2399 do_warn_duplicated_branches_r (tree *tp, int *, void *)
2401 if (TREE_CODE (*tp) == COND_EXPR)
2402 do_warn_duplicated_branches (*tp);
2403 return NULL_TREE;
2406 /* Implementation of -Wmultistatement-macros. This warning warns about
2407 cases when a macro expands to multiple statements not wrapped in
2408 do {} while (0) or ({ }) and is used as a body of if/else/for/while
2409 conditionals. For example,
2411 #define DOIT x++; y++
2413 if (c)
2414 DOIT;
2416 will increment y unconditionally.
2418 BODY_LOC is the location of the first token in the body after labels
2419 have been parsed, NEXT_LOC is the location of the next token after the
2420 body of the conditional has been parsed, and GUARD_LOC is the location
2421 of the conditional. */
2423 void
2424 warn_for_multistatement_macros (location_t body_loc, location_t next_loc,
2425 location_t guard_loc, enum rid keyword)
2427 if (!warn_multistatement_macros)
2428 return;
2430 /* Ain't got time to waste. We only care about macros here. */
2431 if (!from_macro_expansion_at (body_loc)
2432 || !from_macro_expansion_at (next_loc))
2433 return;
2435 /* Let's skip macros defined in system headers. */
2436 if (in_system_header_at (body_loc)
2437 || in_system_header_at (next_loc))
2438 return;
2440 /* Find the actual tokens in the macro definition. BODY_LOC and
2441 NEXT_LOC have to come from the same spelling location, but they
2442 will resolve to different locations in the context of the macro
2443 definition. */
2444 location_t body_loc_exp
2445 = linemap_resolve_location (line_table, body_loc,
2446 LRK_MACRO_DEFINITION_LOCATION, NULL);
2447 location_t next_loc_exp
2448 = linemap_resolve_location (line_table, next_loc,
2449 LRK_MACRO_DEFINITION_LOCATION, NULL);
2450 location_t guard_loc_exp
2451 = linemap_resolve_location (line_table, guard_loc,
2452 LRK_MACRO_DEFINITION_LOCATION, NULL);
2454 /* These are some funky cases we don't want to warn about. */
2455 if (body_loc_exp == guard_loc_exp
2456 || next_loc_exp == guard_loc_exp
2457 || body_loc_exp == next_loc_exp)
2458 return;
2460 /* Find the macro map for the macro expansion BODY_LOC. */
2461 const line_map *map = linemap_lookup (line_table, body_loc);
2462 const line_map_macro *macro_map = linemap_check_macro (map);
2464 /* Now see if the following token is coming from the same macro
2465 expansion. If it is, it's a problem, because it should've been
2466 parsed at this point. We only look at odd-numbered indexes
2467 within the MACRO_MAP_LOCATIONS array, i.e. the spelling locations
2468 of the tokens. */
2469 bool found_guard = false;
2470 bool found_next = false;
2471 for (unsigned int i = 1;
2472 i < 2 * MACRO_MAP_NUM_MACRO_TOKENS (macro_map);
2473 i += 2)
2475 if (MACRO_MAP_LOCATIONS (macro_map)[i] == next_loc_exp)
2476 found_next = true;
2477 if (MACRO_MAP_LOCATIONS (macro_map)[i] == guard_loc_exp)
2478 found_guard = true;
2481 /* The conditional itself must not come from the same expansion, because
2482 we don't want to warn about
2483 #define IF if (x) x++; y++
2484 and similar. */
2485 if (!found_next || found_guard)
2486 return;
2488 if (warning_at (body_loc, OPT_Wmultistatement_macros,
2489 "macro expands to multiple statements"))
2490 inform (guard_loc, "some parts of macro expansion are not guarded by "
2491 "this %qs clause", guard_tinfo_to_string (keyword));