1 /* Diagnostic routines shared by all languages that are variants of C.
2 Copyright (C) 1992-2021 Free Software Foundation, Inc.
3
4 This file is part of GCC.
5
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.
10
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.
15
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/>. */
19
20 #define INCLUDE_STRING
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "target.h"
25 #include "function.h"
26 #include "tree.h"
27 #include "c-common.h"
28 #include "memmodel.h"
29 #include "tm_p.h"
30 #include "diagnostic.h"
31 #include "intl.h"
32 #include "stringpool.h"
33 #include "attribs.h"
34 #include "asan.h"
35 #include "gcc-rich-location.h"
36 #include "gimplify.h"
37 #include "c-family/c-indentation.h"
38 #include "c-family/c-spellcheck.h"
39 #include "calls.h"
40 #include "stor-layout.h"
41 #include "tree-pretty-print.h"
42
43 /* Print a warning if a constant expression had overflow in folding.
44 Invoke this function on every expression that the language
45 requires to be a constant expression.
46 Note the ANSI C standard says it is erroneous for a
47 constant expression to overflow. */
48
49 void
constant_expression_warning(tree value)50 constant_expression_warning (tree value)
51 {
52 if (warn_overflow && pedantic
53 && (TREE_CODE (value) == INTEGER_CST || TREE_CODE (value) == REAL_CST
54 || TREE_CODE (value) == FIXED_CST
55 || TREE_CODE (value) == VECTOR_CST
56 || TREE_CODE (value) == COMPLEX_CST)
57 && TREE_OVERFLOW (value))
58 pedwarn (input_location, OPT_Woverflow, "overflow in constant expression");
59 }
60
61 /* The same as above but print an unconditional error. */
62
63 void
constant_expression_error(tree value)64 constant_expression_error (tree value)
65 {
66 if ((TREE_CODE (value) == INTEGER_CST || TREE_CODE (value) == REAL_CST
67 || TREE_CODE (value) == FIXED_CST
68 || TREE_CODE (value) == VECTOR_CST
69 || TREE_CODE (value) == COMPLEX_CST)
70 && TREE_OVERFLOW (value))
71 error ("overflow in constant expression");
72 }
73
74 /* Print a warning if an expression result VALUE had an overflow
75 in folding and its operands hadn't. EXPR, which may be null, is
76 the operand of the expression.
77
78 Invoke this function on every expression that
79 (1) appears in the source code, and
80 (2) is a constant expression that overflowed, and
81 (3) is not already checked by convert_and_check;
82 however, do not invoke this function on operands of explicit casts
83 or when the expression is the result of an operator and any operand
84 already overflowed. */
85
86 void
overflow_warning(location_t loc,tree value,tree expr)87 overflow_warning (location_t loc, tree value, tree expr)
88 {
89 if (c_inhibit_evaluation_warnings != 0)
90 return;
91
92 const char *warnfmt = NULL;
93
94 switch (TREE_CODE (value))
95 {
96 case INTEGER_CST:
97 warnfmt = (expr
98 ? G_("integer overflow in expression %qE of type %qT "
99 "results in %qE")
100 : G_("integer overflow in expression of type %qT "
101 "results in %qE"));
102 break;
103
104 case REAL_CST:
105 warnfmt = (expr
106 ? G_("floating point overflow in expression %qE "
107 "of type %qT results in %qE")
108 : G_("floating point overflow in expression of type %qT "
109 "results in %qE"));
110 break;
111
112 case FIXED_CST:
113 warnfmt = (expr
114 ? G_("fixed-point overflow in expression %qE of type %qT "
115 "results in %qE")
116 : G_("fixed-point overflow in expression of type %qT "
117 "results in %qE"));
118 break;
119
120 case VECTOR_CST:
121 warnfmt = (expr
122 ? G_("vector overflow in expression %qE of type %qT "
123 "results in %qE")
124 : G_("vector overflow in expression of type %qT "
125 "results in %qE"));
126 break;
127
128 case COMPLEX_CST:
129 if (TREE_CODE (TREE_REALPART (value)) == INTEGER_CST)
130 warnfmt = (expr
131 ? G_("complex integer overflow in expression %qE "
132 "of type %qT results in %qE")
133 : G_("complex integer overflow in expression of type %qT "
134 "results in %qE"));
135 else if (TREE_CODE (TREE_REALPART (value)) == REAL_CST)
136 warnfmt = (expr
137 ? G_("complex floating point overflow in expression %qE "
138 "of type %qT results in %qE")
139 : G_("complex floating point overflow in expression "
140 "of type %qT results in %qE"));
141 else
142 return;
143 break;
144
145 default:
146 return;
147 }
148
149 bool warned;
150 if (expr)
151 warned = warning_at (loc, OPT_Woverflow, warnfmt, expr, TREE_TYPE (expr),
152 value);
153 else
154 warned = warning_at (loc, OPT_Woverflow, warnfmt, TREE_TYPE (value),
155 value);
156
157 if (warned)
158 suppress_warning (value, OPT_Woverflow);
159 }
160
161 /* Helper function for walk_tree. Unwrap C_MAYBE_CONST_EXPRs in an expression
162 pointed to by TP. */
163
164 static tree
unwrap_c_maybe_const(tree * tp,int * walk_subtrees,void *)165 unwrap_c_maybe_const (tree *tp, int *walk_subtrees, void *)
166 {
167 if (TREE_CODE (*tp) == C_MAYBE_CONST_EXPR)
168 {
169 *tp = C_MAYBE_CONST_EXPR_EXPR (*tp);
170 /* C_MAYBE_CONST_EXPRs don't nest. */
171 *walk_subtrees = false;
172 }
173 return NULL_TREE;
174 }
175
176 /* Warn about uses of logical || / && operator in a context where it
177 is likely that the bitwise equivalent was intended by the
178 programmer. We have seen an expression in which CODE is a binary
179 operator used to combine expressions OP_LEFT and OP_RIGHT, which before folding
180 had CODE_LEFT and CODE_RIGHT, into an expression of type TYPE. */
181
182 void
warn_logical_operator(location_t location,enum tree_code code,tree type,enum tree_code code_left,tree op_left,enum tree_code ARG_UNUSED (code_right),tree op_right)183 warn_logical_operator (location_t location, enum tree_code code, tree type,
184 enum tree_code code_left, tree op_left,
185 enum tree_code ARG_UNUSED (code_right), tree op_right)
186 {
187 int or_op = (code == TRUTH_ORIF_EXPR || code == TRUTH_OR_EXPR);
188 int in0_p, in1_p, in_p;
189 tree low0, low1, low, high0, high1, high, lhs, rhs, tem;
190 bool strict_overflow_p = false;
191
192 if (!warn_logical_op)
193 return;
194
195 if (code != TRUTH_ANDIF_EXPR
196 && code != TRUTH_AND_EXPR
197 && code != TRUTH_ORIF_EXPR
198 && code != TRUTH_OR_EXPR)
199 return;
200
201 /* We don't want to warn if either operand comes from a macro
202 expansion. ??? This doesn't work with e.g. NEGATE_EXPR yet;
203 see PR61534. */
204 if (from_macro_expansion_at (EXPR_LOCATION (op_left))
205 || from_macro_expansion_at (EXPR_LOCATION (op_right)))
206 return;
207
208 /* Warn if &&/|| are being used in a context where it is
209 likely that the bitwise equivalent was intended by the
210 programmer. That is, an expression such as op && MASK
211 where op should not be any boolean expression, nor a
212 constant, and mask seems to be a non-boolean integer constant. */
213 STRIP_ANY_LOCATION_WRAPPER (op_right);
214 if (TREE_CODE (op_right) == CONST_DECL)
215 /* An enumerator counts as a constant. */
216 op_right = DECL_INITIAL (op_right);
217 tree stripped_op_left = tree_strip_any_location_wrapper (op_left);
218 if (!truth_value_p (code_left)
219 && INTEGRAL_TYPE_P (TREE_TYPE (op_left))
220 && !CONSTANT_CLASS_P (stripped_op_left)
221 && TREE_CODE (stripped_op_left) != CONST_DECL
222 && !warning_suppressed_p (op_left, OPT_Wlogical_op)
223 && TREE_CODE (op_right) == INTEGER_CST
224 && !integer_zerop (op_right)
225 && !integer_onep (op_right))
226 {
227 bool warned;
228 if (or_op)
229 warned
230 = warning_at (location, OPT_Wlogical_op,
231 "logical %<or%> applied to non-boolean constant");
232 else
233 warned
234 = warning_at (location, OPT_Wlogical_op,
235 "logical %<and%> applied to non-boolean constant");
236 if (warned)
237 suppress_warning (op_left, OPT_Wlogical_op);
238 return;
239 }
240
241 /* We do not warn for constants because they are typical of macro
242 expansions that test for features. */
243 if (CONSTANT_CLASS_P (fold_for_warn (op_left))
244 || CONSTANT_CLASS_P (fold_for_warn (op_right)))
245 return;
246
247 /* This warning only makes sense with logical operands. */
248 if (!(truth_value_p (TREE_CODE (op_left))
249 || INTEGRAL_TYPE_P (TREE_TYPE (op_left)))
250 || !(truth_value_p (TREE_CODE (op_right))
251 || INTEGRAL_TYPE_P (TREE_TYPE (op_right))))
252 return;
253
254 /* The range computations only work with scalars. */
255 if (VECTOR_TYPE_P (TREE_TYPE (op_left))
256 || VECTOR_TYPE_P (TREE_TYPE (op_right)))
257 return;
258
259 /* We first test whether either side separately is trivially true
260 (with OR) or trivially false (with AND). If so, do not warn.
261 This is a common idiom for testing ranges of data types in
262 portable code. */
263 op_left = unshare_expr (op_left);
264 walk_tree_without_duplicates (&op_left, unwrap_c_maybe_const, NULL);
265 lhs = make_range (op_left, &in0_p, &low0, &high0, &strict_overflow_p);
266 if (!lhs)
267 return;
268
269 /* If this is an OR operation, invert both sides; now, the result
270 should be always false to get a warning. */
271 if (or_op)
272 in0_p = !in0_p;
273
274 tem = build_range_check (UNKNOWN_LOCATION, type, lhs, in0_p, low0, high0);
275 if (tem && integer_zerop (tem))
276 return;
277
278 op_right = unshare_expr (op_right);
279 walk_tree_without_duplicates (&op_right, unwrap_c_maybe_const, NULL);
280 rhs = make_range (op_right, &in1_p, &low1, &high1, &strict_overflow_p);
281 if (!rhs)
282 return;
283
284 /* If this is an OR operation, invert both sides; now, the result
285 should be always false to get a warning. */
286 if (or_op)
287 in1_p = !in1_p;
288
289 tem = build_range_check (UNKNOWN_LOCATION, type, rhs, in1_p, low1, high1);
290 if (tem && integer_zerop (tem))
291 return;
292
293 /* If both expressions have the same operand, if we can merge the
294 ranges, ... */
295 if (operand_equal_p (lhs, rhs, 0)
296 && merge_ranges (&in_p, &low, &high, in0_p, low0, high0,
297 in1_p, low1, high1))
298 {
299 tem = build_range_check (UNKNOWN_LOCATION, type, lhs, in_p, low, high);
300 /* ... and if the range test is always false, then warn. */
301 if (tem && integer_zerop (tem))
302 {
303 if (or_op)
304 warning_at (location, OPT_Wlogical_op,
305 "logical %<or%> of collectively exhaustive tests is "
306 "always true");
307 else
308 warning_at (location, OPT_Wlogical_op,
309 "logical %<and%> of mutually exclusive tests is "
310 "always false");
311 }
312 /* Or warn if the operands have exactly the same range, e.g.
313 A > 0 && A > 0. */
314 else if (tree_int_cst_equal (low0, low1)
315 && tree_int_cst_equal (high0, high1))
316 {
317 if (or_op)
318 warning_at (location, OPT_Wlogical_op,
319 "logical %<or%> of equal expressions");
320 else
321 warning_at (location, OPT_Wlogical_op,
322 "logical %<and%> of equal expressions");
323 }
324 }
325 }
326
327 /* Helper function for warn_tautological_cmp. Look for ARRAY_REFs
328 with constant indices. */
329
330 static tree
find_array_ref_with_const_idx_r(tree * expr_p,int *,void *)331 find_array_ref_with_const_idx_r (tree *expr_p, int *, void *)
332 {
333 tree expr = *expr_p;
334
335 if ((TREE_CODE (expr) == ARRAY_REF
336 || TREE_CODE (expr) == ARRAY_RANGE_REF)
337 && (TREE_CODE (fold_for_warn (TREE_OPERAND (expr, 1)))
338 == INTEGER_CST))
339 return integer_type_node;
340
341 return NULL_TREE;
342 }
343
344 /* Subroutine of warn_tautological_cmp. Warn about bitwise comparison
345 that always evaluate to true or false. LOC is the location of the
346 ==/!= comparison specified by CODE; LHS and RHS are the usual operands
347 of this comparison. */
348
349 static void
warn_tautological_bitwise_comparison(const op_location_t & loc,tree_code code,tree lhs,tree rhs)350 warn_tautological_bitwise_comparison (const op_location_t &loc, tree_code code,
351 tree lhs, tree rhs)
352 {
353 if (code != EQ_EXPR && code != NE_EXPR)
354 return;
355
356 /* Extract the operands from e.g. (x & 8) == 4. */
357 tree bitop;
358 tree cst;
359 tree stripped_lhs = tree_strip_any_location_wrapper (lhs);
360 tree stripped_rhs = tree_strip_any_location_wrapper (rhs);
361 if ((TREE_CODE (lhs) == BIT_AND_EXPR
362 || TREE_CODE (lhs) == BIT_IOR_EXPR)
363 && TREE_CODE (stripped_rhs) == INTEGER_CST)
364 bitop = lhs, cst = stripped_rhs;
365 else if ((TREE_CODE (rhs) == BIT_AND_EXPR
366 || TREE_CODE (rhs) == BIT_IOR_EXPR)
367 && TREE_CODE (stripped_lhs) == INTEGER_CST)
368 bitop = rhs, cst = stripped_lhs;
369 else
370 return;
371
372 tree bitopcst;
373 tree bitop_op0 = fold_for_warn (TREE_OPERAND (bitop, 0));
374 if (TREE_CODE (bitop_op0) == INTEGER_CST)
375 bitopcst = bitop_op0;
376 else {
377 tree bitop_op1 = fold_for_warn (TREE_OPERAND (bitop, 1));
378 if (TREE_CODE (bitop_op1) == INTEGER_CST)
379 bitopcst = bitop_op1;
380 else
381 return;
382 }
383
384 /* Note that the two operands are from before the usual integer
385 conversions, so their types might not be the same.
386 Use the larger of the two precisions and ignore bits outside
387 of that. */
388 int prec = MAX (TYPE_PRECISION (TREE_TYPE (cst)),
389 TYPE_PRECISION (TREE_TYPE (bitopcst)));
390
391 wide_int bitopcstw = wi::to_wide (bitopcst, prec);
392 wide_int cstw = wi::to_wide (cst, prec);
393
394 wide_int res;
395 if (TREE_CODE (bitop) == BIT_AND_EXPR)
396 res = bitopcstw & cstw;
397 else
398 res = bitopcstw | cstw;
399
400 /* For BIT_AND only warn if (CST2 & CST1) != CST1, and
401 for BIT_OR only if (CST2 | CST1) != CST1. */
402 if (res == cstw)
403 return;
404
405 binary_op_rich_location richloc (loc, lhs, rhs, false);
406 if (code == EQ_EXPR)
407 warning_at (&richloc, OPT_Wtautological_compare,
408 "bitwise comparison always evaluates to false");
409 else
410 warning_at (&richloc, OPT_Wtautological_compare,
411 "bitwise comparison always evaluates to true");
412 }
413
414 /* Given LOC from a macro expansion, return the map for the outermost
415 macro in the nest of expansions. */
416
417 static const line_map_macro *
get_outermost_macro_expansion(location_t loc)418 get_outermost_macro_expansion (location_t loc)
419 {
420 gcc_assert (from_macro_expansion_at (loc));
421
422 const line_map *map = linemap_lookup (line_table, loc);
423 const line_map_macro *macro_map;
424 do
425 {
426 macro_map = linemap_check_macro (map);
427 loc = linemap_unwind_toward_expansion (line_table, loc, &map);
428 } while (linemap_macro_expansion_map_p (map));
429
430 return macro_map;
431 }
432
433 /* Given LOC_A and LOC_B from macro expansions, return true if
434 they are "spelled the same" i.e. if they are both directly from
435 expansion of the same non-function-like macro. */
436
437 static bool
spelled_the_same_p(location_t loc_a,location_t loc_b)438 spelled_the_same_p (location_t loc_a, location_t loc_b)
439 {
440 gcc_assert (from_macro_expansion_at (loc_a));
441 gcc_assert (from_macro_expansion_at (loc_b));
442
443 const line_map_macro *map_a = get_outermost_macro_expansion (loc_a);
444 const line_map_macro *map_b = get_outermost_macro_expansion (loc_b);
445
446 if (map_a->macro == map_b->macro)
447 if (!cpp_fun_like_macro_p (map_a->macro))
448 return true;
449
450 return false;
451 }
452
453 /* Warn if a self-comparison always evaluates to true or false. LOC
454 is the location of the comparison with code CODE, LHS and RHS are
455 operands of the comparison. */
456
457 void
warn_tautological_cmp(const op_location_t & loc,enum tree_code code,tree lhs,tree rhs)458 warn_tautological_cmp (const op_location_t &loc, enum tree_code code,
459 tree lhs, tree rhs)
460 {
461 if (TREE_CODE_CLASS (code) != tcc_comparison)
462 return;
463
464 /* Don't warn for various macro expansions. */
465 if (from_macro_expansion_at (loc))
466 return;
467 bool lhs_in_macro = from_macro_expansion_at (EXPR_LOCATION (lhs));
468 bool rhs_in_macro = from_macro_expansion_at (EXPR_LOCATION (rhs));
469 if (lhs_in_macro || rhs_in_macro)
470 {
471 /* Don't warn if exactly one is from a macro. */
472 if (!(lhs_in_macro && rhs_in_macro))
473 return;
474
475 /* If both are in a macro, only warn if they're spelled the same. */
476 if (!spelled_the_same_p (EXPR_LOCATION (lhs), EXPR_LOCATION (rhs)))
477 return;
478 }
479
480 warn_tautological_bitwise_comparison (loc, code, lhs, rhs);
481
482 /* We do not warn for constants because they are typical of macro
483 expansions that test for features, sizeof, and similar. */
484 if (CONSTANT_CLASS_P (fold_for_warn (lhs))
485 || CONSTANT_CLASS_P (fold_for_warn (rhs)))
486 return;
487
488 /* Don't warn for e.g.
489 HOST_WIDE_INT n;
490 ...
491 if (n == (long) n) ...
492 */
493 if ((CONVERT_EXPR_P (lhs) || TREE_CODE (lhs) == NON_LVALUE_EXPR)
494 || (CONVERT_EXPR_P (rhs) || TREE_CODE (rhs) == NON_LVALUE_EXPR))
495 return;
496
497 /* Don't warn if either LHS or RHS has an IEEE floating-point type.
498 It could be a NaN, and NaN never compares equal to anything, even
499 itself. */
500 if (FLOAT_TYPE_P (TREE_TYPE (lhs)) || FLOAT_TYPE_P (TREE_TYPE (rhs)))
501 return;
502
503 if (operand_equal_p (lhs, rhs, 0))
504 {
505 /* Don't warn about array references with constant indices;
506 these are likely to come from a macro. */
507 if (walk_tree_without_duplicates (&lhs, find_array_ref_with_const_idx_r,
508 NULL))
509 return;
510 const bool always_true = (code == EQ_EXPR || code == LE_EXPR
511 || code == GE_EXPR || code == UNLE_EXPR
512 || code == UNGE_EXPR || code == UNEQ_EXPR);
513 binary_op_rich_location richloc (loc, lhs, rhs, false);
514 if (always_true)
515 warning_at (&richloc, OPT_Wtautological_compare,
516 "self-comparison always evaluates to true");
517 else
518 warning_at (&richloc, OPT_Wtautological_compare,
519 "self-comparison always evaluates to false");
520 }
521 }
522
523 /* Return true iff EXPR only contains boolean operands, or comparisons. */
524
525 static bool
expr_has_boolean_operands_p(tree expr)526 expr_has_boolean_operands_p (tree expr)
527 {
528 STRIP_NOPS (expr);
529
530 if (CONVERT_EXPR_P (expr))
531 return bool_promoted_to_int_p (expr);
532 else if (UNARY_CLASS_P (expr))
533 return expr_has_boolean_operands_p (TREE_OPERAND (expr, 0));
534 else if (BINARY_CLASS_P (expr))
535 return (expr_has_boolean_operands_p (TREE_OPERAND (expr, 0))
536 && expr_has_boolean_operands_p (TREE_OPERAND (expr, 1)));
537 else if (COMPARISON_CLASS_P (expr))
538 return true;
539 else
540 return false;
541 }
542
543 /* Warn about logical not used on the left hand side operand of a comparison.
544 This function assumes that the LHS is inside of TRUTH_NOT_EXPR.
545 Do not warn if RHS is of a boolean type, a logical operator, or
546 a comparison. */
547
548 void
warn_logical_not_parentheses(location_t location,enum tree_code code,tree lhs,tree rhs)549 warn_logical_not_parentheses (location_t location, enum tree_code code,
550 tree lhs, tree rhs)
551 {
552 if (TREE_CODE_CLASS (code) != tcc_comparison
553 || TREE_TYPE (rhs) == NULL_TREE
554 || TREE_CODE (TREE_TYPE (rhs)) == BOOLEAN_TYPE
555 || truth_value_p (TREE_CODE (rhs)))
556 return;
557
558 /* Don't warn for expression like !x == ~(bool1 | bool2). */
559 if (expr_has_boolean_operands_p (rhs))
560 return;
561
562 /* Don't warn for !x == 0 or !y != 0, those are equivalent to
563 !(x == 0) or !(y != 0). */
564 if ((code == EQ_EXPR || code == NE_EXPR)
565 && integer_zerop (rhs))
566 return;
567
568 auto_diagnostic_group d;
569 if (warning_at (location, OPT_Wlogical_not_parentheses,
570 "logical not is only applied to the left hand side of "
571 "comparison")
572 && EXPR_HAS_LOCATION (lhs))
573 {
574 location_t lhs_loc = EXPR_LOCATION (lhs);
575 rich_location richloc (line_table, lhs_loc);
576 richloc.add_fixit_insert_before (lhs_loc, "(");
577 richloc.add_fixit_insert_after (lhs_loc, ")");
578 inform (&richloc, "add parentheses around left hand side "
579 "expression to silence this warning");
580 }
581 }
582
583 /* Warn if EXP contains any computations whose results are not used.
584 Return true if a warning is printed; false otherwise. LOCUS is the
585 (potential) location of the expression. */
586
587 bool
warn_if_unused_value(const_tree exp,location_t locus,bool quiet)588 warn_if_unused_value (const_tree exp, location_t locus, bool quiet)
589 {
590 restart:
591 if (TREE_USED (exp) || warning_suppressed_p (exp, OPT_Wunused_value))
592 return false;
593
594 /* Don't warn about void constructs. This includes casting to void,
595 void function calls, and statement expressions with a final cast
596 to void. */
597 if (VOID_TYPE_P (TREE_TYPE (exp)))
598 return false;
599
600 if (EXPR_HAS_LOCATION (exp))
601 locus = EXPR_LOCATION (exp);
602
603 switch (TREE_CODE (exp))
604 {
605 case PREINCREMENT_EXPR:
606 case POSTINCREMENT_EXPR:
607 case PREDECREMENT_EXPR:
608 case POSTDECREMENT_EXPR:
609 case MODIFY_EXPR:
610 case INIT_EXPR:
611 case TARGET_EXPR:
612 case CALL_EXPR:
613 case TRY_CATCH_EXPR:
614 case EXIT_EXPR:
615 case VA_ARG_EXPR:
616 return false;
617
618 case BIND_EXPR:
619 /* For a binding, warn if no side effect within it. */
620 exp = BIND_EXPR_BODY (exp);
621 goto restart;
622
623 case SAVE_EXPR:
624 case NON_LVALUE_EXPR:
625 case NOP_EXPR:
626 exp = TREE_OPERAND (exp, 0);
627 goto restart;
628
629 case TRUTH_ORIF_EXPR:
630 case TRUTH_ANDIF_EXPR:
631 /* In && or ||, warn if 2nd operand has no side effect. */
632 exp = TREE_OPERAND (exp, 1);
633 goto restart;
634
635 case COMPOUND_EXPR:
636 if (warn_if_unused_value (TREE_OPERAND (exp, 0), locus, quiet))
637 return true;
638 /* Let people do `(foo (), 0)' without a warning. */
639 if (TREE_CONSTANT (TREE_OPERAND (exp, 1)))
640 return false;
641 exp = TREE_OPERAND (exp, 1);
642 goto restart;
643
644 case COND_EXPR:
645 /* If this is an expression with side effects, don't warn; this
646 case commonly appears in macro expansions. */
647 if (TREE_SIDE_EFFECTS (exp))
648 return false;
649 goto warn;
650
651 case COMPLEX_EXPR:
652 /* Warn only if both operands are unused. */
653 if (warn_if_unused_value (TREE_OPERAND (exp, 0), locus, true)
654 && warn_if_unused_value (TREE_OPERAND (exp, 1), locus, true))
655 goto warn;
656 return false;
657
658 case INDIRECT_REF:
659 /* Don't warn about automatic dereferencing of references, since
660 the user cannot control it. */
661 if (TREE_CODE (TREE_TYPE (TREE_OPERAND (exp, 0))) == REFERENCE_TYPE)
662 {
663 exp = TREE_OPERAND (exp, 0);
664 goto restart;
665 }
666 /* Fall through. */
667
668 default:
669 /* Referencing a volatile value is a side effect, so don't warn. */
670 if ((DECL_P (exp) || REFERENCE_CLASS_P (exp))
671 && TREE_THIS_VOLATILE (exp))
672 return false;
673
674 /* If this is an expression which has no operands, there is no value
675 to be unused. There are no such language-independent codes,
676 but front ends may define such. */
677 if (EXPRESSION_CLASS_P (exp) && TREE_OPERAND_LENGTH (exp) == 0)
678 return false;
679
680 warn:
681 if (quiet)
682 return true;
683 return warning_at (locus, OPT_Wunused_value, "value computed is not used");
684 }
685 }
686
687 /* Print a warning about casts that might indicate violation of strict
688 aliasing rules if -Wstrict-aliasing is used and strict aliasing
689 mode is in effect. LOC is the location of the expression being
690 cast, EXPR might be from inside it. TYPE is the type we're casting
691 to. */
692
693 bool
strict_aliasing_warning(location_t loc,tree type,tree expr)694 strict_aliasing_warning (location_t loc, tree type, tree expr)
695 {
696 if (loc == UNKNOWN_LOCATION)
697 loc = input_location;
698
699 /* Strip pointer conversion chains and get to the correct original type. */
700 STRIP_NOPS (expr);
701 tree otype = TREE_TYPE (expr);
702
703 if (!(flag_strict_aliasing
704 && POINTER_TYPE_P (type)
705 && POINTER_TYPE_P (otype)
706 && !VOID_TYPE_P (TREE_TYPE (type)))
707 /* If the type we are casting to is a ref-all pointer
708 dereferencing it is always valid. */
709 || TYPE_REF_CAN_ALIAS_ALL (type))
710 return false;
711
712 if ((warn_strict_aliasing > 1) && TREE_CODE (expr) == ADDR_EXPR
713 && (DECL_P (TREE_OPERAND (expr, 0))
714 || handled_component_p (TREE_OPERAND (expr, 0))))
715 {
716 /* Casting the address of an object to non void pointer. Warn
717 if the cast breaks type based aliasing. */
718 if (!COMPLETE_TYPE_P (TREE_TYPE (type)) && warn_strict_aliasing == 2)
719 {
720 warning_at (loc, OPT_Wstrict_aliasing,
721 "type-punning to incomplete type "
722 "might break strict-aliasing rules");
723 return true;
724 }
725 else
726 {
727 /* warn_strict_aliasing >= 3. This includes the default (3).
728 Only warn if the cast is dereferenced immediately. */
729 alias_set_type set1
730 = get_alias_set (TREE_TYPE (TREE_OPERAND (expr, 0)));
731 alias_set_type set2 = get_alias_set (TREE_TYPE (type));
732
733 if (set2 != 0
734 && set1 != set2
735 && !alias_set_subset_of (set2, set1)
736 && !alias_sets_conflict_p (set1, set2))
737 {
738 warning_at (loc, OPT_Wstrict_aliasing,
739 "dereferencing type-punned "
740 "pointer will break strict-aliasing rules");
741 return true;
742 }
743 else if (warn_strict_aliasing == 2
744 && !alias_sets_must_conflict_p (set1, set2))
745 {
746 warning_at (loc, OPT_Wstrict_aliasing,
747 "dereferencing type-punned "
748 "pointer might break strict-aliasing rules");
749 return true;
750 }
751 }
752 }
753 else if ((warn_strict_aliasing == 1) && !VOID_TYPE_P (TREE_TYPE (otype)))
754 {
755 /* At this level, warn for any conversions, even if an address is
756 not taken in the same statement. This will likely produce many
757 false positives, but could be useful to pinpoint problems that
758 are not revealed at higher levels. */
759 alias_set_type set1 = get_alias_set (TREE_TYPE (otype));
760 alias_set_type set2 = get_alias_set (TREE_TYPE (type));
761 if (!COMPLETE_TYPE_P (TREE_TYPE (type))
762 || !alias_sets_must_conflict_p (set1, set2))
763 {
764 warning_at (loc, OPT_Wstrict_aliasing,
765 "dereferencing type-punned "
766 "pointer might break strict-aliasing rules");
767 return true;
768 }
769 }
770
771 return false;
772 }
773
774 /* Warn about memset (&a, 0, sizeof (&a)); and similar mistakes with
775 sizeof as last operand of certain builtins. */
776
777 void
sizeof_pointer_memaccess_warning(location_t * sizeof_arg_loc,tree callee,vec<tree,va_gc> * params,tree * sizeof_arg,bool (* comp_types)(tree,tree))778 sizeof_pointer_memaccess_warning (location_t *sizeof_arg_loc, tree callee,
779 vec<tree, va_gc> *params, tree *sizeof_arg,
780 bool (*comp_types) (tree, tree))
781 {
782 tree type, dest = NULL_TREE, src = NULL_TREE, tem;
783 bool strop = false, cmp = false;
784 unsigned int idx = ~0;
785 location_t loc;
786
787 if (TREE_CODE (callee) != FUNCTION_DECL
788 || !fndecl_built_in_p (callee, BUILT_IN_NORMAL)
789 || vec_safe_length (params) <= 1)
790 return;
791
792 enum built_in_function fncode = DECL_FUNCTION_CODE (callee);
793 switch (fncode)
794 {
795 case BUILT_IN_STRNCMP:
796 case BUILT_IN_STRNCASECMP:
797 cmp = true;
798 /* FALLTHRU */
799 case BUILT_IN_STRNCPY:
800 case BUILT_IN_STRNCPY_CHK:
801 case BUILT_IN_STRNCAT:
802 case BUILT_IN_STRNCAT_CHK:
803 case BUILT_IN_STPNCPY:
804 case BUILT_IN_STPNCPY_CHK:
805 strop = true;
806 /* FALLTHRU */
807 case BUILT_IN_MEMCPY:
808 case BUILT_IN_MEMCPY_CHK:
809 case BUILT_IN_MEMMOVE:
810 case BUILT_IN_MEMMOVE_CHK:
811 if (params->length () < 3)
812 return;
813 src = (*params)[1];
814 dest = (*params)[0];
815 idx = 2;
816 break;
817 case BUILT_IN_BCOPY:
818 if (params->length () < 3)
819 return;
820 src = (*params)[0];
821 dest = (*params)[1];
822 idx = 2;
823 break;
824 case BUILT_IN_MEMCMP:
825 case BUILT_IN_BCMP:
826 if (params->length () < 3)
827 return;
828 src = (*params)[1];
829 dest = (*params)[0];
830 idx = 2;
831 cmp = true;
832 break;
833 case BUILT_IN_MEMSET:
834 case BUILT_IN_MEMSET_CHK:
835 if (params->length () < 3)
836 return;
837 dest = (*params)[0];
838 idx = 2;
839 break;
840 case BUILT_IN_BZERO:
841 dest = (*params)[0];
842 idx = 1;
843 break;
844 case BUILT_IN_STRNDUP:
845 src = (*params)[0];
846 strop = true;
847 idx = 1;
848 break;
849 case BUILT_IN_MEMCHR:
850 if (params->length () < 3)
851 return;
852 src = (*params)[0];
853 idx = 2;
854 break;
855 case BUILT_IN_SNPRINTF:
856 case BUILT_IN_SNPRINTF_CHK:
857 case BUILT_IN_VSNPRINTF:
858 case BUILT_IN_VSNPRINTF_CHK:
859 dest = (*params)[0];
860 idx = 1;
861 strop = true;
862 break;
863 default:
864 break;
865 }
866
867 if (idx >= 3)
868 return;
869
870 /* Use error_operand_p to detect non-error arguments with an error
871 type that the C++ front-end constructs. */
872 if (error_operand_p (src)
873 || error_operand_p (dest)
874 || !sizeof_arg[idx]
875 || error_operand_p (sizeof_arg[idx]))
876 return;
877
878 type = TYPE_P (sizeof_arg[idx])
879 ? sizeof_arg[idx] : TREE_TYPE (sizeof_arg[idx]);
880
881 if (!POINTER_TYPE_P (type))
882 {
883 /* The argument type may be an array. Diagnose bounded string
884 copy functions that specify the bound in terms of the source
885 argument rather than the destination unless they are equal
886 to one another. Handle constant sizes and also try to handle
887 sizeof expressions involving VLAs. */
888 if (strop && !cmp && fncode != BUILT_IN_STRNDUP && src)
889 {
890 tem = tree_strip_nop_conversions (src);
891 if (TREE_CODE (tem) == ADDR_EXPR)
892 tem = TREE_OPERAND (tem, 0);
893
894 /* Avoid diagnosing sizeof SRC when SRC is declared with
895 attribute nonstring. */
896 tree dummy;
897 if (get_attr_nonstring_decl (tem, &dummy))
898 return;
899
900 tree d = tree_strip_nop_conversions (dest);
901 if (TREE_CODE (d) == ADDR_EXPR)
902 d = TREE_OPERAND (d, 0);
903
904 tree dstsz = TYPE_SIZE_UNIT (TREE_TYPE (d));
905 tree srcsz = TYPE_SIZE_UNIT (TREE_TYPE (tem));
906
907 if ((!dstsz
908 || !srcsz
909 || !operand_equal_p (dstsz, srcsz, OEP_LEXICOGRAPHIC))
910 && operand_equal_p (tem, sizeof_arg[idx], OEP_ADDRESS_OF))
911 warning_at (sizeof_arg_loc[idx], OPT_Wsizeof_pointer_memaccess,
912 "argument to %<sizeof%> in %qD call is the same "
913 "expression as the source; did you mean to use "
914 "the size of the destination?",
915 callee);
916 }
917
918 return;
919 }
920
921 if (dest
922 && (tem = tree_strip_nop_conversions (dest))
923 && POINTER_TYPE_P (TREE_TYPE (tem))
924 && comp_types (TREE_TYPE (TREE_TYPE (tem)), type))
925 return;
926
927 if (src
928 && (tem = tree_strip_nop_conversions (src))
929 && POINTER_TYPE_P (TREE_TYPE (tem))
930 && comp_types (TREE_TYPE (TREE_TYPE (tem)), type))
931 return;
932
933 loc = sizeof_arg_loc[idx];
934
935 if (dest && !cmp)
936 {
937 if (!TYPE_P (sizeof_arg[idx])
938 && operand_equal_p (dest, sizeof_arg[idx], 0)
939 && comp_types (TREE_TYPE (dest), type))
940 {
941 if (TREE_CODE (sizeof_arg[idx]) == ADDR_EXPR && !strop)
942 warning_at (loc, OPT_Wsizeof_pointer_memaccess,
943 "argument to %<sizeof%> in %qD call is the same "
944 "expression as the destination; did you mean to "
945 "remove the addressof?", callee);
946 else if ((TYPE_PRECISION (TREE_TYPE (type))
947 == TYPE_PRECISION (char_type_node))
948 || strop)
949 warning_at (loc, OPT_Wsizeof_pointer_memaccess,
950 "argument to %<sizeof%> in %qD call is the same "
951 "expression as the destination; did you mean to "
952 "provide an explicit length?", callee);
953 else
954 warning_at (loc, OPT_Wsizeof_pointer_memaccess,
955 "argument to %<sizeof%> in %qD call is the same "
956 "expression as the destination; did you mean to "
957 "dereference it?", callee);
958 return;
959 }
960
961 if (POINTER_TYPE_P (TREE_TYPE (dest))
962 && !strop
963 && comp_types (TREE_TYPE (dest), type)
964 && !VOID_TYPE_P (TREE_TYPE (type)))
965 {
966 warning_at (loc, OPT_Wsizeof_pointer_memaccess,
967 "argument to %<sizeof%> in %qD call is the same "
968 "pointer type %qT as the destination; expected %qT "
969 "or an explicit length", callee, TREE_TYPE (dest),
970 TREE_TYPE (TREE_TYPE (dest)));
971 return;
972 }
973 }
974
975 if (src && !cmp)
976 {
977 if (!TYPE_P (sizeof_arg[idx])
978 && operand_equal_p (src, sizeof_arg[idx], 0)
979 && comp_types (TREE_TYPE (src), type))
980 {
981 if (TREE_CODE (sizeof_arg[idx]) == ADDR_EXPR && !strop)
982 warning_at (loc, OPT_Wsizeof_pointer_memaccess,
983 "argument to %<sizeof%> in %qD call is the same "
984 "expression as the source; did you mean to "
985 "remove the addressof?", callee);
986 else if ((TYPE_PRECISION (TREE_TYPE (type))
987 == TYPE_PRECISION (char_type_node))
988 || strop)
989 warning_at (loc, OPT_Wsizeof_pointer_memaccess,
990 "argument to %<sizeof%> in %qD call is the same "
991 "expression as the source; did you mean to "
992 "provide an explicit length?", callee);
993 else
994 warning_at (loc, OPT_Wsizeof_pointer_memaccess,
995 "argument to %<sizeof%> in %qD call is the same "
996 "expression as the source; did you mean to "
997 "dereference it?", callee);
998 return;
999 }
1000
1001 if (POINTER_TYPE_P (TREE_TYPE (src))
1002 && !strop
1003 && comp_types (TREE_TYPE (src), type)
1004 && !VOID_TYPE_P (TREE_TYPE (type)))
1005 {
1006 warning_at (loc, OPT_Wsizeof_pointer_memaccess,
1007 "argument to %<sizeof%> in %qD call is the same "
1008 "pointer type %qT as the source; expected %qT "
1009 "or an explicit length", callee, TREE_TYPE (src),
1010 TREE_TYPE (TREE_TYPE (src)));
1011 return;
1012 }
1013 }
1014
1015 if (dest)
1016 {
1017 if (!TYPE_P (sizeof_arg[idx])
1018 && operand_equal_p (dest, sizeof_arg[idx], 0)
1019 && comp_types (TREE_TYPE (dest), type))
1020 {
1021 if (TREE_CODE (sizeof_arg[idx]) == ADDR_EXPR && !strop)
1022 warning_at (loc, OPT_Wsizeof_pointer_memaccess,
1023 "argument to %<sizeof%> in %qD call is the same "
1024 "expression as the first source; did you mean to "
1025 "remove the addressof?", callee);
1026 else if ((TYPE_PRECISION (TREE_TYPE (type))
1027 == TYPE_PRECISION (char_type_node))
1028 || strop)
1029 warning_at (loc, OPT_Wsizeof_pointer_memaccess,
1030 "argument to %<sizeof%> in %qD call is the same "
1031 "expression as the first source; did you mean to "
1032 "provide an explicit length?", callee);
1033 else
1034 warning_at (loc, OPT_Wsizeof_pointer_memaccess,
1035 "argument to %<sizeof%> in %qD call is the same "
1036 "expression as the first source; did you mean to "
1037 "dereference it?", callee);
1038 return;
1039 }
1040
1041 if (POINTER_TYPE_P (TREE_TYPE (dest))
1042 && !strop
1043 && comp_types (TREE_TYPE (dest), type)
1044 && !VOID_TYPE_P (TREE_TYPE (type)))
1045 {
1046 warning_at (loc, OPT_Wsizeof_pointer_memaccess,
1047 "argument to %<sizeof%> in %qD call is the same "
1048 "pointer type %qT as the first source; expected %qT "
1049 "or an explicit length", callee, TREE_TYPE (dest),
1050 TREE_TYPE (TREE_TYPE (dest)));
1051 return;
1052 }
1053 }
1054
1055 if (src)
1056 {
1057 if (!TYPE_P (sizeof_arg[idx])
1058 && operand_equal_p (src, sizeof_arg[idx], 0)
1059 && comp_types (TREE_TYPE (src), type))
1060 {
1061 if (TREE_CODE (sizeof_arg[idx]) == ADDR_EXPR && !strop)
1062 warning_at (loc, OPT_Wsizeof_pointer_memaccess,
1063 "argument to %<sizeof%> in %qD call is the same "
1064 "expression as the second source; did you mean to "
1065 "remove the addressof?", callee);
1066 else if ((TYPE_PRECISION (TREE_TYPE (type))
1067 == TYPE_PRECISION (char_type_node))
1068 || strop)
1069 warning_at (loc, OPT_Wsizeof_pointer_memaccess,
1070 "argument to %<sizeof%> in %qD call is the same "
1071 "expression as the second source; did you mean to "
1072 "provide an explicit length?", callee);
1073 else
1074 warning_at (loc, OPT_Wsizeof_pointer_memaccess,
1075 "argument to %<sizeof%> in %qD call is the same "
1076 "expression as the second source; did you mean to "
1077 "dereference it?", callee);
1078 return;
1079 }
1080
1081 if (POINTER_TYPE_P (TREE_TYPE (src))
1082 && !strop
1083 && comp_types (TREE_TYPE (src), type)
1084 && !VOID_TYPE_P (TREE_TYPE (type)))
1085 {
1086 warning_at (loc, OPT_Wsizeof_pointer_memaccess,
1087 "argument to %<sizeof%> in %qD call is the same "
1088 "pointer type %qT as the second source; expected %qT "
1089 "or an explicit length", callee, TREE_TYPE (src),
1090 TREE_TYPE (TREE_TYPE (src)));
1091 return;
1092 }
1093 }
1094
1095 }
1096
1097 /* Warn for unlikely, improbable, or stupid DECL declarations
1098 of `main'. */
1099
1100 void
check_main_parameter_types(tree decl)1101 check_main_parameter_types (tree decl)
1102 {
1103 function_args_iterator iter;
1104 tree type;
1105 int argct = 0;
1106
1107 FOREACH_FUNCTION_ARGS (TREE_TYPE (decl), type, iter)
1108 {
1109 /* XXX void_type_node belies the abstraction. */
1110 if (type == void_type_node || type == error_mark_node)
1111 break;
1112
1113 tree t = type;
1114 if (TYPE_ATOMIC (t))
1115 pedwarn (input_location, OPT_Wmain,
1116 "%<_Atomic%>-qualified parameter type %qT of %q+D",
1117 type, decl);
1118 while (POINTER_TYPE_P (t))
1119 {
1120 t = TREE_TYPE (t);
1121 if (TYPE_ATOMIC (t))
1122 pedwarn (input_location, OPT_Wmain,
1123 "%<_Atomic%>-qualified parameter type %qT of %q+D",
1124 type, decl);
1125 }
1126
1127 ++argct;
1128 switch (argct)
1129 {
1130 case 1:
1131 if (TYPE_MAIN_VARIANT (type) != integer_type_node)
1132 pedwarn (input_location, OPT_Wmain,
1133 "first argument of %q+D should be %<int%>", decl);
1134 break;
1135
1136 case 2:
1137 if (TREE_CODE (type) != POINTER_TYPE
1138 || TREE_CODE (TREE_TYPE (type)) != POINTER_TYPE
1139 || (TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (type)))
1140 != char_type_node))
1141 pedwarn (input_location, OPT_Wmain,
1142 "second argument of %q+D should be %<char **%>", decl);
1143 break;
1144
1145 case 3:
1146 if (TREE_CODE (type) != POINTER_TYPE
1147 || TREE_CODE (TREE_TYPE (type)) != POINTER_TYPE
1148 || (TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (type)))
1149 != char_type_node))
1150 pedwarn (input_location, OPT_Wmain,
1151 "third argument of %q+D should probably be "
1152 "%<char **%>", decl);
1153 break;
1154 }
1155 }
1156
1157 /* It is intentional that this message does not mention the third
1158 argument because it's only mentioned in an appendix of the
1159 standard. */
1160 if (argct > 0 && (argct < 2 || argct > 3))
1161 pedwarn (input_location, OPT_Wmain,
1162 "%q+D takes only zero or two arguments", decl);
1163
1164 if (stdarg_p (TREE_TYPE (decl)))
1165 pedwarn (input_location, OPT_Wmain,
1166 "%q+D declared as variadic function", decl);
1167 }
1168
1169 /* Warns and returns true if the conversion of EXPR to TYPE may alter a value.
1170 This is a helper function for warnings_for_convert_and_check. */
1171
1172 static bool
conversion_warning(location_t loc,tree type,tree expr,tree result)1173 conversion_warning (location_t loc, tree type, tree expr, tree result)
1174 {
1175 tree expr_type = TREE_TYPE (expr);
1176 enum conversion_safety conversion_kind;
1177 int arith_ops = 0;
1178
1179 if (!warn_conversion && !warn_sign_conversion && !warn_float_conversion)
1180 return false;
1181
1182 /* This may happen, because for LHS op= RHS we preevaluate
1183 RHS and create C_MAYBE_CONST_EXPR <SAVE_EXPR <RHS>>, which
1184 means we could no longer see the code of the EXPR. */
1185 if (TREE_CODE (expr) == C_MAYBE_CONST_EXPR)
1186 expr = C_MAYBE_CONST_EXPR_EXPR (expr);
1187 if (TREE_CODE (expr) == SAVE_EXPR)
1188 expr = TREE_OPERAND (expr, 0);
1189
1190 switch (TREE_CODE (expr))
1191 {
1192 case EQ_EXPR:
1193 case NE_EXPR:
1194 case LE_EXPR:
1195 case GE_EXPR:
1196 case LT_EXPR:
1197 case GT_EXPR:
1198 case TRUTH_ANDIF_EXPR:
1199 case TRUTH_ORIF_EXPR:
1200 case TRUTH_AND_EXPR:
1201 case TRUTH_OR_EXPR:
1202 case TRUTH_XOR_EXPR:
1203 case TRUTH_NOT_EXPR:
1204 /* Conversion from boolean to a signed:1 bit-field (which only
1205 can hold the values 0 and -1) doesn't lose information - but
1206 it does change the value. */
1207 if (TYPE_PRECISION (type) == 1 && !TYPE_UNSIGNED (type))
1208 warning_at (loc, OPT_Wconversion,
1209 "conversion to %qT from boolean expression", type);
1210 return true;
1211
1212 case REAL_CST:
1213 case INTEGER_CST:
1214 case COMPLEX_CST:
1215 {
1216 conversion_kind = unsafe_conversion_p (type, expr, result, true);
1217 int warnopt;
1218 if (conversion_kind == UNSAFE_REAL)
1219 warnopt = OPT_Wfloat_conversion;
1220 else if (conversion_kind)
1221 warnopt = OPT_Wconversion;
1222 else
1223 break;
1224
1225 if (conversion_kind == UNSAFE_SIGN)
1226 {
1227 bool cstresult
1228 = (result
1229 && TREE_CODE_CLASS (TREE_CODE (result)) == tcc_constant);
1230 if (TYPE_UNSIGNED (type))
1231 {
1232 if (cstresult)
1233 warning_at (loc, OPT_Wsign_conversion,
1234 "unsigned conversion from %qT to %qT "
1235 "changes value from %qE to %qE",
1236 expr_type, type, expr, result);
1237 else
1238 warning_at (loc, OPT_Wsign_conversion,
1239 "unsigned conversion from %qT to %qT "
1240 "changes the value of %qE",
1241 expr_type, type, expr);
1242 }
1243 else
1244 {
1245 if (cstresult)
1246 warning_at (loc, OPT_Wsign_conversion,
1247 "signed conversion from %qT to %qT changes "
1248 "value from %qE to %qE",
1249 expr_type, type, expr, result);
1250 else
1251 warning_at (loc, OPT_Wsign_conversion,
1252 "signed conversion from %qT to %qT changes "
1253 "the value of %qE",
1254 expr_type, type, expr);
1255 }
1256 }
1257 else if (TREE_CODE_CLASS (TREE_CODE (result)) == tcc_constant)
1258 warning_at (loc, warnopt,
1259 "conversion from %qT to %qT changes value from %qE to %qE",
1260 expr_type, type, expr, result);
1261 else
1262 warning_at (loc, warnopt,
1263 "conversion from %qT to %qT changes the value of %qE",
1264 expr_type, type, expr);
1265 return true;
1266 }
1267
1268 case PLUS_EXPR:
1269 case MINUS_EXPR:
1270 case MULT_EXPR:
1271 case MAX_EXPR:
1272 case MIN_EXPR:
1273 case TRUNC_MOD_EXPR:
1274 case FLOOR_MOD_EXPR:
1275 case TRUNC_DIV_EXPR:
1276 case FLOOR_DIV_EXPR:
1277 case CEIL_DIV_EXPR:
1278 case EXACT_DIV_EXPR:
1279 case RDIV_EXPR:
1280 arith_ops = 2;
1281 goto default_;
1282
1283 case PREDECREMENT_EXPR:
1284 case PREINCREMENT_EXPR:
1285 case POSTDECREMENT_EXPR:
1286 case POSTINCREMENT_EXPR:
1287 case LSHIFT_EXPR:
1288 case RSHIFT_EXPR:
1289 case FIX_TRUNC_EXPR:
1290 case NON_LVALUE_EXPR:
1291 case NEGATE_EXPR:
1292 case BIT_NOT_EXPR:
1293 arith_ops = 1;
1294 goto default_;
1295
1296 case COND_EXPR:
1297 {
1298 /* In case of COND_EXPR, we do not care about the type of
1299 COND_EXPR, only about the conversion of each operand. */
1300 tree op1 = TREE_OPERAND (expr, 1);
1301 tree op2 = TREE_OPERAND (expr, 2);
1302
1303 return (conversion_warning (loc, type, op1, result)
1304 || conversion_warning (loc, type, op2, result));
1305 }
1306
1307 default_:
1308 default:
1309 conversion_kind = unsafe_conversion_p (type, expr, result, true);
1310 {
1311 int warnopt;
1312 if (conversion_kind == UNSAFE_REAL)
1313 warnopt = OPT_Wfloat_conversion;
1314 else if (conversion_kind == UNSAFE_SIGN)
1315 warnopt = OPT_Wsign_conversion;
1316 else if (conversion_kind)
1317 warnopt = OPT_Wconversion;
1318 else
1319 break;
1320
1321 if (arith_ops
1322 && global_dc->option_enabled (warnopt,
1323 global_dc->lang_mask,
1324 global_dc->option_state))
1325 {
1326 for (int i = 0; i < arith_ops; ++i)
1327 {
1328 tree op = TREE_OPERAND (expr, i);
1329 /* Avoid -Wsign-conversion for (unsigned)(x + (-1)). */
1330 if (TREE_CODE (expr) == PLUS_EXPR && i == 1
1331 && INTEGRAL_TYPE_P (type) && TYPE_UNSIGNED (type)
1332 && TREE_CODE (op) == INTEGER_CST
1333 && tree_int_cst_sgn (op) < 0)
1334 op = fold_build1 (NEGATE_EXPR, TREE_TYPE (op), op);
1335 tree opr = convert (type, op);
1336 if (unsafe_conversion_p (type, op, opr, true))
1337 goto op_unsafe;
1338 }
1339 /* The operands seem safe, we might still want to warn if
1340 -Warith-conversion. */
1341 warnopt = OPT_Warith_conversion;
1342 op_unsafe:;
1343 }
1344
1345 if (conversion_kind == UNSAFE_SIGN)
1346 warning_at (loc, warnopt, "conversion to %qT from %qT "
1347 "may change the sign of the result",
1348 type, expr_type);
1349 else if (conversion_kind == UNSAFE_IMAGINARY)
1350 warning_at (loc, warnopt,
1351 "conversion from %qT to %qT discards imaginary component",
1352 expr_type, type);
1353 else
1354 warning_at (loc, warnopt,
1355 "conversion from %qT to %qT may change value",
1356 expr_type, type);
1357 return true;
1358 }
1359 }
1360 return false;
1361 }
1362
1363 /* Produce warnings after a conversion. RESULT is the result of
1364 converting EXPR to TYPE. This is a helper function for
1365 convert_and_check and cp_convert_and_check. */
1366
1367 void
warnings_for_convert_and_check(location_t loc,tree type,tree expr,tree result)1368 warnings_for_convert_and_check (location_t loc, tree type, tree expr,
1369 tree result)
1370 {
1371 loc = expansion_point_location_if_in_system_header (loc);
1372
1373 while (TREE_CODE (expr) == COMPOUND_EXPR)
1374 expr = TREE_OPERAND (expr, 1);
1375 while (TREE_CODE (result) == COMPOUND_EXPR)
1376 result = TREE_OPERAND (result, 1);
1377
1378 bool cst = TREE_CODE_CLASS (TREE_CODE (result)) == tcc_constant;
1379
1380 tree exprtype = TREE_TYPE (expr);
1381
1382 if (TREE_CODE (expr) == INTEGER_CST
1383 && (TREE_CODE (type) == INTEGER_TYPE
1384 || TREE_CODE (type) == ENUMERAL_TYPE)
1385 && !int_fits_type_p (expr, type))
1386 {
1387 /* Do not diagnose overflow in a constant expression merely
1388 because a conversion overflowed. */
1389 if (TREE_OVERFLOW (result))
1390 TREE_OVERFLOW (result) = TREE_OVERFLOW (expr);
1391
1392 if (TYPE_UNSIGNED (type))
1393 {
1394 /* This detects cases like converting -129 or 256 to
1395 unsigned char. */
1396 if (!int_fits_type_p (expr, c_common_signed_type (type)))
1397 {
1398 if (cst)
1399 warning_at (loc, OPT_Woverflow,
1400 (TYPE_UNSIGNED (exprtype)
1401 ? G_("conversion from %qT to %qT "
1402 "changes value from %qE to %qE")
1403 : G_("unsigned conversion from %qT to %qT "
1404 "changes value from %qE to %qE")),
1405 exprtype, type, expr, result);
1406 else
1407 warning_at (loc, OPT_Woverflow,
1408 (TYPE_UNSIGNED (exprtype)
1409 ? G_("conversion from %qT to %qT "
1410 "changes the value of %qE")
1411 : G_("unsigned conversion from %qT to %qT "
1412 "changes the value of %qE")),
1413 exprtype, type, expr);
1414 }
1415 else
1416 conversion_warning (loc, type, expr, result);
1417 }
1418 else if (!int_fits_type_p (expr, c_common_unsigned_type (type)))
1419 {
1420 if (cst)
1421 warning_at (loc, OPT_Woverflow,
1422 "overflow in conversion from %qT to %qT "
1423 "changes value from %qE to %qE",
1424 exprtype, type, expr, result);
1425 else
1426 warning_at (loc, OPT_Woverflow,
1427 "overflow in conversion from %qT to %qT "
1428 "changes the value of %qE",
1429 exprtype, type, expr);
1430 }
1431 /* No warning for converting 0x80000000 to int. */
1432 else if (pedantic
1433 && (TREE_CODE (exprtype) != INTEGER_TYPE
1434 || TYPE_PRECISION (exprtype)
1435 != TYPE_PRECISION (type)))
1436 {
1437 if (cst)
1438 warning_at (loc, OPT_Woverflow,
1439 "overflow in conversion from %qT to %qT "
1440 "changes value from %qE to %qE",
1441 exprtype, type, expr, result);
1442 else
1443 warning_at (loc, OPT_Woverflow,
1444 "overflow in conversion from %qT to %qT "
1445 "changes the value of %qE",
1446 exprtype, type, expr);
1447 }
1448 else
1449 conversion_warning (loc, type, expr, result);
1450 }
1451 else if ((TREE_CODE (result) == INTEGER_CST
1452 || TREE_CODE (result) == FIXED_CST) && TREE_OVERFLOW (result))
1453 {
1454 if (cst)
1455 warning_at (loc, OPT_Woverflow,
1456 "overflow in conversion from %qT to %qT "
1457 "changes value from %qE to %qE",
1458 exprtype, type, expr, result);
1459 else
1460 warning_at (loc, OPT_Woverflow,
1461 "overflow in conversion from %qT to %qT "
1462 "changes the value of %qE",
1463 exprtype, type, expr);
1464 }
1465 else
1466 conversion_warning (loc, type, expr, result);
1467 }
1468
1469 /* Subroutines of c_do_switch_warnings, called via splay_tree_foreach.
1470 Used to verify that case values match up with enumerator values. */
1471
1472 static void
match_case_to_enum_1(tree key,tree type,tree label)1473 match_case_to_enum_1 (tree key, tree type, tree label)
1474 {
1475 /* Avoid warning about enums that have no enumerators. */
1476 if (TYPE_VALUES (type) == NULL_TREE)
1477 return;
1478
1479 char buf[WIDE_INT_PRINT_BUFFER_SIZE];
1480
1481 if (tree_fits_uhwi_p (key))
1482 print_dec (wi::to_wide (key), buf, UNSIGNED);
1483 else if (tree_fits_shwi_p (key))
1484 print_dec (wi::to_wide (key), buf, SIGNED);
1485 else
1486 print_hex (wi::to_wide (key), buf);
1487
1488 if (TYPE_NAME (type) == NULL_TREE)
1489 warning_at (DECL_SOURCE_LOCATION (CASE_LABEL (label)),
1490 warn_switch ? OPT_Wswitch : OPT_Wswitch_enum,
1491 "case value %qs not in enumerated type",
1492 buf);
1493 else
1494 warning_at (DECL_SOURCE_LOCATION (CASE_LABEL (label)),
1495 warn_switch ? OPT_Wswitch : OPT_Wswitch_enum,
1496 "case value %qs not in enumerated type %qT",
1497 buf, type);
1498 }
1499
1500 /* Subroutine of c_do_switch_warnings, called via splay_tree_foreach.
1501 Used to verify that case values match up with enumerator values. */
1502
1503 static int
match_case_to_enum(splay_tree_node node,void * data)1504 match_case_to_enum (splay_tree_node node, void *data)
1505 {
1506 tree label = (tree) node->value;
1507 tree type = (tree) data;
1508
1509 /* Skip default case. */
1510 if (!CASE_LOW (label))
1511 return 0;
1512
1513 /* If CASE_LOW_SEEN is not set, that means CASE_LOW did not appear
1514 when we did our enum->case scan. Reset our scratch bit after. */
1515 if (!CASE_LOW_SEEN (label))
1516 match_case_to_enum_1 (CASE_LOW (label), type, label);
1517 else
1518 CASE_LOW_SEEN (label) = 0;
1519
1520 /* If CASE_HIGH is non-null, we have a range. If CASE_HIGH_SEEN is
1521 not set, that means that CASE_HIGH did not appear when we did our
1522 enum->case scan. Reset our scratch bit after. */
1523 if (CASE_HIGH (label))
1524 {
1525 if (!CASE_HIGH_SEEN (label))
1526 match_case_to_enum_1 (CASE_HIGH (label), type, label);
1527 else
1528 CASE_HIGH_SEEN (label) = 0;
1529 }
1530
1531 return 0;
1532 }
1533
1534 /* Handle -Wswitch*. Called from the front end after parsing the
1535 switch construct. */
1536 /* ??? Should probably be somewhere generic, since other languages
1537 besides C and C++ would want this. At the moment, however, C/C++
1538 are the only tree-ssa languages that support enumerations at all,
1539 so the point is moot. */
1540
1541 void
c_do_switch_warnings(splay_tree cases,location_t switch_location,tree type,tree cond,bool bool_cond_p)1542 c_do_switch_warnings (splay_tree cases, location_t switch_location,
1543 tree type, tree cond, bool bool_cond_p)
1544 {
1545 splay_tree_node default_node;
1546 splay_tree_node node;
1547 tree chain;
1548 bool outside_range_p = false;
1549
1550 if (type != error_mark_node
1551 && type != TREE_TYPE (cond)
1552 && INTEGRAL_TYPE_P (type)
1553 && INTEGRAL_TYPE_P (TREE_TYPE (cond))
1554 && (!tree_int_cst_equal (TYPE_MIN_VALUE (type),
1555 TYPE_MIN_VALUE (TREE_TYPE (cond)))
1556 || !tree_int_cst_equal (TYPE_MAX_VALUE (type),
1557 TYPE_MAX_VALUE (TREE_TYPE (cond)))))
1558 {
1559 tree min_value = TYPE_MIN_VALUE (type);
1560 tree max_value = TYPE_MAX_VALUE (type);
1561
1562 node = splay_tree_predecessor (cases, (splay_tree_key) min_value);
1563 if (node && node->key)
1564 {
1565 outside_range_p = true;
1566 /* There is at least one case smaller than TYPE's minimum value.
1567 NODE itself could be still a range overlapping the valid values,
1568 but any predecessors thereof except the default case will be
1569 completely outside of range. */
1570 if (CASE_HIGH ((tree) node->value)
1571 && tree_int_cst_compare (CASE_HIGH ((tree) node->value),
1572 min_value) >= 0)
1573 {
1574 location_t loc = EXPR_LOCATION ((tree) node->value);
1575 warning_at (loc, OPT_Wswitch_outside_range,
1576 "lower value in case label range less than minimum"
1577 " value for type");
1578 CASE_LOW ((tree) node->value) = convert (TREE_TYPE (cond),
1579 min_value);
1580 node->key = (splay_tree_key) CASE_LOW ((tree) node->value);
1581 }
1582 /* All the following ones are completely outside of range. */
1583 do
1584 {
1585 node = splay_tree_predecessor (cases,
1586 (splay_tree_key) min_value);
1587 if (node == NULL || !node->key)
1588 break;
1589 location_t loc = EXPR_LOCATION ((tree) node->value);
1590 warning_at (loc, OPT_Wswitch_outside_range, "case label value is"
1591 " less than minimum value for type");
1592 splay_tree_remove (cases, node->key);
1593 }
1594 while (1);
1595 }
1596 node = splay_tree_lookup (cases, (splay_tree_key) max_value);
1597 if (node == NULL)
1598 node = splay_tree_predecessor (cases, (splay_tree_key) max_value);
1599 /* Handle a single node that might partially overlap the range. */
1600 if (node
1601 && node->key
1602 && CASE_HIGH ((tree) node->value)
1603 && tree_int_cst_compare (CASE_HIGH ((tree) node->value),
1604 max_value) > 0)
1605 {
1606 location_t loc = EXPR_LOCATION ((tree) node->value);
1607 warning_at (loc, OPT_Wswitch_outside_range, "upper value in case"
1608 " label range exceeds maximum value for type");
1609 CASE_HIGH ((tree) node->value)
1610 = convert (TREE_TYPE (cond), max_value);
1611 outside_range_p = true;
1612 }
1613 /* And any nodes that are completely outside of the range. */
1614 while ((node = splay_tree_successor (cases,
1615 (splay_tree_key) max_value))
1616 != NULL)
1617 {
1618 location_t loc = EXPR_LOCATION ((tree) node->value);
1619 warning_at (loc, OPT_Wswitch_outside_range,
1620 "case label value exceeds maximum value for type");
1621 splay_tree_remove (cases, node->key);
1622 outside_range_p = true;
1623 }
1624 }
1625
1626 if (!warn_switch && !warn_switch_enum && !warn_switch_default
1627 && !warn_switch_bool)
1628 return;
1629
1630 default_node = splay_tree_lookup (cases, (splay_tree_key) NULL);
1631 if (!default_node)
1632 warning_at (switch_location, OPT_Wswitch_default,
1633 "switch missing default case");
1634
1635 /* There are certain cases where -Wswitch-bool warnings aren't
1636 desirable, such as
1637 switch (boolean)
1638 {
1639 case true: ...
1640 case false: ...
1641 }
1642 so be careful here. */
1643 if (warn_switch_bool && bool_cond_p)
1644 {
1645 splay_tree_node min_node;
1646 /* If there's a default node, it's also the value with the minimal
1647 key. So look at the penultimate key (if any). */
1648 if (default_node)
1649 min_node = splay_tree_successor (cases, (splay_tree_key) NULL);
1650 else
1651 min_node = splay_tree_min (cases);
1652 tree min = min_node ? (tree) min_node->key : NULL_TREE;
1653
1654 splay_tree_node max_node = splay_tree_max (cases);
1655 /* This might be a case range, so look at the value with the
1656 maximal key and then check CASE_HIGH. */
1657 tree max = max_node ? (tree) max_node->value : NULL_TREE;
1658 if (max)
1659 max = CASE_HIGH (max) ? CASE_HIGH (max) : CASE_LOW (max);
1660
1661 /* If there's a case value > 1 or < 0, that is outside bool
1662 range, warn. */
1663 if (outside_range_p
1664 || (max && wi::gts_p (wi::to_wide (max), 1))
1665 || (min && wi::lts_p (wi::to_wide (min), 0))
1666 /* And handle the
1667 switch (boolean)
1668 {
1669 case true: ...
1670 case false: ...
1671 default: ...
1672 }
1673 case, where we want to warn. */
1674 || (default_node
1675 && max && wi::to_wide (max) == 1
1676 && min && wi::to_wide (min) == 0))
1677 warning_at (switch_location, OPT_Wswitch_bool,
1678 "switch condition has boolean value");
1679 }
1680
1681 /* From here on, we only care about enumerated types. */
1682 if (!type || TREE_CODE (type) != ENUMERAL_TYPE)
1683 return;
1684
1685 /* From here on, we only care about -Wswitch and -Wswitch-enum. */
1686 if (!warn_switch_enum && !warn_switch)
1687 return;
1688
1689 /* Check the cases. Warn about case values which are not members of
1690 the enumerated type. For -Wswitch-enum, or for -Wswitch when
1691 there is no default case, check that exactly all enumeration
1692 literals are covered by the cases. */
1693
1694 /* Clearing COND if it is not an integer constant simplifies
1695 the tests inside the loop below. */
1696 if (TREE_CODE (cond) != INTEGER_CST)
1697 cond = NULL_TREE;
1698
1699 /* The time complexity here is O(N*lg(N)) worst case, but for the
1700 common case of monotonically increasing enumerators, it is
1701 O(N), since the nature of the splay tree will keep the next
1702 element adjacent to the root at all times. */
1703
1704 for (chain = TYPE_VALUES (type); chain; chain = TREE_CHAIN (chain))
1705 {
1706 tree value = TREE_VALUE (chain);
1707 if (TREE_CODE (value) == CONST_DECL)
1708 value = DECL_INITIAL (value);
1709 node = splay_tree_lookup (cases, (splay_tree_key) value);
1710 if (node)
1711 {
1712 /* Mark the CASE_LOW part of the case entry as seen. */
1713 tree label = (tree) node->value;
1714 CASE_LOW_SEEN (label) = 1;
1715 continue;
1716 }
1717
1718 /* Even though there wasn't an exact match, there might be a
1719 case range which includes the enumerator's value. */
1720 node = splay_tree_predecessor (cases, (splay_tree_key) value);
1721 if (node && CASE_HIGH ((tree) node->value))
1722 {
1723 tree label = (tree) node->value;
1724 int cmp = tree_int_cst_compare (CASE_HIGH (label), value);
1725 if (cmp >= 0)
1726 {
1727 /* If we match the upper bound exactly, mark the CASE_HIGH
1728 part of the case entry as seen. */
1729 if (cmp == 0)
1730 CASE_HIGH_SEEN (label) = 1;
1731 continue;
1732 }
1733 }
1734
1735 /* We've now determined that this enumerated literal isn't
1736 handled by the case labels of the switch statement. */
1737
1738 /* If the switch expression is a constant, we only really care
1739 about whether that constant is handled by the switch. */
1740 if (cond && tree_int_cst_compare (cond, value))
1741 continue;
1742
1743 /* If the enumerator is defined in a system header and uses a reserved
1744 name, then we continue to avoid throwing a warning. */
1745 location_t loc = DECL_SOURCE_LOCATION
1746 (TYPE_STUB_DECL (TYPE_MAIN_VARIANT (type)));
1747 if (in_system_header_at (loc)
1748 && name_reserved_for_implementation_p
1749 (IDENTIFIER_POINTER (TREE_PURPOSE (chain))))
1750 continue;
1751
1752 /* If there is a default_node, the only relevant option is
1753 Wswitch-enum. Otherwise, if both are enabled then we prefer
1754 to warn using -Wswitch because -Wswitch is enabled by -Wall
1755 while -Wswitch-enum is explicit. */
1756 warning_at (switch_location,
1757 (default_node || !warn_switch
1758 ? OPT_Wswitch_enum
1759 : OPT_Wswitch),
1760 "enumeration value %qE not handled in switch",
1761 TREE_PURPOSE (chain));
1762 }
1763
1764 /* Warn if there are case expressions that don't correspond to
1765 enumerators. This can occur since C and C++ don't enforce
1766 type-checking of assignments to enumeration variables.
1767
1768 The time complexity here is now always O(N) worst case, since
1769 we should have marked both the lower bound and upper bound of
1770 every disjoint case label, with CASE_LOW_SEEN and CASE_HIGH_SEEN
1771 above. This scan also resets those fields. */
1772
1773 splay_tree_foreach (cases, match_case_to_enum, type);
1774 }
1775
1776 /* Warn for A ?: C expressions (with B omitted) where A is a boolean
1777 expression, because B will always be true. */
1778
1779 void
warn_for_omitted_condop(location_t location,tree cond)1780 warn_for_omitted_condop (location_t location, tree cond)
1781 {
1782 /* In C++ template declarations it can happen that the type is dependent
1783 and not yet known, thus TREE_TYPE (cond) == NULL_TREE. */
1784 if (truth_value_p (TREE_CODE (cond))
1785 || (TREE_TYPE (cond) != NULL_TREE
1786 && TREE_CODE (TREE_TYPE (cond)) == BOOLEAN_TYPE))
1787 warning_at (location, OPT_Wparentheses,
1788 "the omitted middle operand in %<?:%> will always be %<true%>, "
1789 "suggest explicit middle operand");
1790 }
1791
1792 /* Give an error for storing into ARG, which is 'const'. USE indicates
1793 how ARG was being used. */
1794
1795 void
readonly_error(location_t loc,tree arg,enum lvalue_use use)1796 readonly_error (location_t loc, tree arg, enum lvalue_use use)
1797 {
1798 gcc_assert (use == lv_assign || use == lv_increment || use == lv_decrement
1799 || use == lv_asm);
1800 STRIP_ANY_LOCATION_WRAPPER (arg);
1801 /* Using this macro rather than (for example) arrays of messages
1802 ensures that all the format strings are checked at compile
1803 time. */
1804 #define READONLY_MSG(A, I, D, AS) (use == lv_assign ? (A) \
1805 : (use == lv_increment ? (I) \
1806 : (use == lv_decrement ? (D) : (AS))))
1807 if (TREE_CODE (arg) == COMPONENT_REF)
1808 {
1809 if (TYPE_READONLY (TREE_TYPE (TREE_OPERAND (arg, 0))))
1810 error_at (loc, READONLY_MSG (G_("assignment of member "
1811 "%qD in read-only object"),
1812 G_("increment of member "
1813 "%qD in read-only object"),
1814 G_("decrement of member "
1815 "%qD in read-only object"),
1816 G_("member %qD in read-only object "
1817 "used as %<asm%> output")),
1818 TREE_OPERAND (arg, 1));
1819 else
1820 error_at (loc, READONLY_MSG (G_("assignment of read-only member %qD"),
1821 G_("increment of read-only member %qD"),
1822 G_("decrement of read-only member %qD"),
1823 G_("read-only member %qD used as %<asm%> output")),
1824 TREE_OPERAND (arg, 1));
1825 }
1826 else if (VAR_P (arg))
1827 error_at (loc, READONLY_MSG (G_("assignment of read-only variable %qD"),
1828 G_("increment of read-only variable %qD"),
1829 G_("decrement of read-only variable %qD"),
1830 G_("read-only variable %qD used as %<asm%> output")),
1831 arg);
1832 else if (TREE_CODE (arg) == PARM_DECL)
1833 error_at (loc, READONLY_MSG (G_("assignment of read-only parameter %qD"),
1834 G_("increment of read-only parameter %qD"),
1835 G_("decrement of read-only parameter %qD"),
1836 G_("read-only parameter %qD use as %<asm%> output")),
1837 arg);
1838 else if (TREE_CODE (arg) == RESULT_DECL)
1839 {
1840 gcc_assert (c_dialect_cxx ());
1841 error_at (loc, READONLY_MSG (G_("assignment of "
1842 "read-only named return value %qD"),
1843 G_("increment of "
1844 "read-only named return value %qD"),
1845 G_("decrement of "
1846 "read-only named return value %qD"),
1847 G_("read-only named return value %qD "
1848 "used as %<asm%>output")),
1849 arg);
1850 }
1851 else if (TREE_CODE (arg) == FUNCTION_DECL)
1852 error_at (loc, READONLY_MSG (G_("assignment of function %qD"),
1853 G_("increment of function %qD"),
1854 G_("decrement of function %qD"),
1855 G_("function %qD used as %<asm%> output")),
1856 arg);
1857 else
1858 error_at (loc, READONLY_MSG (G_("assignment of read-only location %qE"),
1859 G_("increment of read-only location %qE"),
1860 G_("decrement of read-only location %qE"),
1861 G_("read-only location %qE used as %<asm%> output")),
1862 arg);
1863 }
1864
1865 /* Print an error message for an invalid lvalue. USE says
1866 how the lvalue is being used and so selects the error message. LOC
1867 is the location for the error. */
1868
1869 void
lvalue_error(location_t loc,enum lvalue_use use)1870 lvalue_error (location_t loc, enum lvalue_use use)
1871 {
1872 switch (use)
1873 {
1874 case lv_assign:
1875 error_at (loc, "lvalue required as left operand of assignment");
1876 break;
1877 case lv_increment:
1878 error_at (loc, "lvalue required as increment operand");
1879 break;
1880 case lv_decrement:
1881 error_at (loc, "lvalue required as decrement operand");
1882 break;
1883 case lv_addressof:
1884 error_at (loc, "lvalue required as unary %<&%> operand");
1885 break;
1886 case lv_asm:
1887 error_at (loc, "lvalue required in %<asm%> statement");
1888 break;
1889 default:
1890 gcc_unreachable ();
1891 }
1892 }
1893
1894 /* Print an error message for an invalid indirection of type TYPE.
1895 ERRSTRING is the name of the operator for the indirection. */
1896
1897 void
invalid_indirection_error(location_t loc,tree type,ref_operator errstring)1898 invalid_indirection_error (location_t loc, tree type, ref_operator errstring)
1899 {
1900 switch (errstring)
1901 {
1902 case RO_NULL:
1903 gcc_assert (c_dialect_cxx ());
1904 error_at (loc, "invalid type argument (have %qT)", type);
1905 break;
1906 case RO_ARRAY_INDEXING:
1907 error_at (loc,
1908 "invalid type argument of array indexing (have %qT)",
1909 type);
1910 break;
1911 case RO_UNARY_STAR:
1912 error_at (loc,
1913 "invalid type argument of unary %<*%> (have %qT)",
1914 type);
1915 break;
1916 case RO_ARROW:
1917 error_at (loc,
1918 "invalid type argument of %<->%> (have %qT)",
1919 type);
1920 break;
1921 case RO_ARROW_STAR:
1922 error_at (loc,
1923 "invalid type argument of %<->*%> (have %qT)",
1924 type);
1925 break;
1926 case RO_IMPLICIT_CONVERSION:
1927 error_at (loc,
1928 "invalid type argument of implicit conversion (have %qT)",
1929 type);
1930 break;
1931 default:
1932 gcc_unreachable ();
1933 }
1934 }
1935
1936 /* Subscripting with type char is likely to lose on a machine where
1937 chars are signed. So warn on any machine, but optionally. Don't
1938 warn for unsigned char since that type is safe. Don't warn for
1939 signed char because anyone who uses that must have done so
1940 deliberately. Furthermore, we reduce the false positive load by
1941 warning only for non-constant value of type char.
1942 LOC is the location of the subscripting expression. */
1943
1944 void
warn_array_subscript_with_type_char(location_t loc,tree index)1945 warn_array_subscript_with_type_char (location_t loc, tree index)
1946 {
1947 if (TYPE_MAIN_VARIANT (TREE_TYPE (index)) == char_type_node)
1948 {
1949 /* If INDEX has a location, use it; otherwise use LOC (the location
1950 of the subscripting expression as a whole). */
1951 loc = EXPR_LOC_OR_LOC (index, loc);
1952 STRIP_ANY_LOCATION_WRAPPER (index);
1953 if (TREE_CODE (index) != INTEGER_CST)
1954 warning_at (loc, OPT_Wchar_subscripts,
1955 "array subscript has type %<char%>");
1956 }
1957 }
1958
1959 /* Implement -Wparentheses for the unexpected C precedence rules, to
1960 cover cases like x + y << z which readers are likely to
1961 misinterpret. We have seen an expression in which CODE is a binary
1962 operator used to combine expressions ARG_LEFT and ARG_RIGHT, which
1963 before folding had CODE_LEFT and CODE_RIGHT. CODE_LEFT and
1964 CODE_RIGHT may be ERROR_MARK, which means that that side of the
1965 expression was not formed using a binary or unary operator, or it
1966 was enclosed in parentheses. */
1967
1968 void
warn_about_parentheses(location_t loc,enum tree_code code,enum tree_code code_left,tree arg_left,enum tree_code code_right,tree arg_right)1969 warn_about_parentheses (location_t loc, enum tree_code code,
1970 enum tree_code code_left, tree arg_left,
1971 enum tree_code code_right, tree arg_right)
1972 {
1973 if (!warn_parentheses)
1974 return;
1975
1976 /* This macro tests that the expression ARG with original tree code
1977 CODE appears to be a boolean expression. or the result of folding a
1978 boolean expression. */
1979 #define APPEARS_TO_BE_BOOLEAN_EXPR_P(CODE, ARG) \
1980 (truth_value_p (TREE_CODE (ARG)) \
1981 || TREE_CODE (TREE_TYPE (ARG)) == BOOLEAN_TYPE \
1982 /* Folding may create 0 or 1 integers from other expressions. */ \
1983 || ((CODE) != INTEGER_CST \
1984 && (integer_onep (ARG) || integer_zerop (ARG))))
1985
1986 switch (code)
1987 {
1988 case LSHIFT_EXPR:
1989 if (code_left == PLUS_EXPR)
1990 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
1991 "suggest parentheses around %<+%> inside %<<<%>");
1992 else if (code_right == PLUS_EXPR)
1993 warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
1994 "suggest parentheses around %<+%> inside %<<<%>");
1995 else if (code_left == MINUS_EXPR)
1996 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
1997 "suggest parentheses around %<-%> inside %<<<%>");
1998 else if (code_right == MINUS_EXPR)
1999 warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
2000 "suggest parentheses around %<-%> inside %<<<%>");
2001 return;
2002
2003 case RSHIFT_EXPR:
2004 if (code_left == PLUS_EXPR)
2005 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
2006 "suggest parentheses around %<+%> inside %<>>%>");
2007 else if (code_right == PLUS_EXPR)
2008 warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
2009 "suggest parentheses around %<+%> inside %<>>%>");
2010 else if (code_left == MINUS_EXPR)
2011 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
2012 "suggest parentheses around %<-%> inside %<>>%>");
2013 else if (code_right == MINUS_EXPR)
2014 warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
2015 "suggest parentheses around %<-%> inside %<>>%>");
2016 return;
2017
2018 case TRUTH_ORIF_EXPR:
2019 if (code_left == TRUTH_ANDIF_EXPR)
2020 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
2021 "suggest parentheses around %<&&%> within %<||%>");
2022 else if (code_right == TRUTH_ANDIF_EXPR)
2023 warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
2024 "suggest parentheses around %<&&%> within %<||%>");
2025 return;
2026
2027 case BIT_IOR_EXPR:
2028 if (code_left == BIT_AND_EXPR || code_left == BIT_XOR_EXPR
2029 || code_left == PLUS_EXPR || code_left == MINUS_EXPR)
2030 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
2031 "suggest parentheses around arithmetic in operand of %<|%>");
2032 else if (code_right == BIT_AND_EXPR || code_right == BIT_XOR_EXPR
2033 || code_right == PLUS_EXPR || code_right == MINUS_EXPR)
2034 warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
2035 "suggest parentheses around arithmetic in operand of %<|%>");
2036 /* Check cases like x|y==z */
2037 else if (TREE_CODE_CLASS (code_left) == tcc_comparison)
2038 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
2039 "suggest parentheses around comparison in operand of %<|%>");
2040 else if (TREE_CODE_CLASS (code_right) == tcc_comparison)
2041 warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
2042 "suggest parentheses around comparison in operand of %<|%>");
2043 /* Check cases like !x | y */
2044 else if (code_left == TRUTH_NOT_EXPR
2045 && !APPEARS_TO_BE_BOOLEAN_EXPR_P (code_right, arg_right))
2046 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
2047 "suggest parentheses around operand of "
2048 "%<!%> or change %<|%> to %<||%> or %<!%> to %<~%>");
2049 return;
2050
2051 case BIT_XOR_EXPR:
2052 if (code_left == BIT_AND_EXPR
2053 || code_left == PLUS_EXPR || code_left == MINUS_EXPR)
2054 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
2055 "suggest parentheses around arithmetic in operand of %<^%>");
2056 else if (code_right == BIT_AND_EXPR
2057 || code_right == PLUS_EXPR || code_right == MINUS_EXPR)
2058 warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
2059 "suggest parentheses around arithmetic in operand of %<^%>");
2060 /* Check cases like x^y==z */
2061 else if (TREE_CODE_CLASS (code_left) == tcc_comparison)
2062 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
2063 "suggest parentheses around comparison in operand of %<^%>");
2064 else if (TREE_CODE_CLASS (code_right) == tcc_comparison)
2065 warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
2066 "suggest parentheses around comparison in operand of %<^%>");
2067 return;
2068
2069 case BIT_AND_EXPR:
2070 if (code_left == PLUS_EXPR)
2071 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
2072 "suggest parentheses around %<+%> in operand of %<&%>");
2073 else if (code_right == PLUS_EXPR)
2074 warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
2075 "suggest parentheses around %<+%> in operand of %<&%>");
2076 else if (code_left == MINUS_EXPR)
2077 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
2078 "suggest parentheses around %<-%> in operand of %<&%>");
2079 else if (code_right == MINUS_EXPR)
2080 warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
2081 "suggest parentheses around %<-%> in operand of %<&%>");
2082 /* Check cases like x&y==z */
2083 else if (TREE_CODE_CLASS (code_left) == tcc_comparison)
2084 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
2085 "suggest parentheses around comparison in operand of %<&%>");
2086 else if (TREE_CODE_CLASS (code_right) == tcc_comparison)
2087 warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
2088 "suggest parentheses around comparison in operand of %<&%>");
2089 /* Check cases like !x & y */
2090 else if (code_left == TRUTH_NOT_EXPR
2091 && !APPEARS_TO_BE_BOOLEAN_EXPR_P (code_right, arg_right))
2092 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
2093 "suggest parentheses around operand of "
2094 "%<!%> or change %<&%> to %<&&%> or %<!%> to %<~%>");
2095 return;
2096
2097 case EQ_EXPR:
2098 if (TREE_CODE_CLASS (code_left) == tcc_comparison)
2099 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
2100 "suggest parentheses around comparison in operand of %<==%>");
2101 else if (TREE_CODE_CLASS (code_right) == tcc_comparison)
2102 warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
2103 "suggest parentheses around comparison in operand of %<==%>");
2104 return;
2105 case NE_EXPR:
2106 if (TREE_CODE_CLASS (code_left) == tcc_comparison)
2107 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
2108 "suggest parentheses around comparison in operand of %<!=%>");
2109 else if (TREE_CODE_CLASS (code_right) == tcc_comparison)
2110 warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
2111 "suggest parentheses around comparison in operand of %<!=%>");
2112 return;
2113
2114 default:
2115 if (TREE_CODE_CLASS (code) == tcc_comparison)
2116 {
2117 if (TREE_CODE_CLASS (code_left) == tcc_comparison
2118 && code_left != NE_EXPR && code_left != EQ_EXPR
2119 && INTEGRAL_TYPE_P (TREE_TYPE (arg_left)))
2120 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
2121 "comparisons like %<X<=Y<=Z%> do not "
2122 "have their mathematical meaning");
2123 else if (TREE_CODE_CLASS (code_right) == tcc_comparison
2124 && code_right != NE_EXPR && code_right != EQ_EXPR
2125 && INTEGRAL_TYPE_P (TREE_TYPE (arg_right)))
2126 warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
2127 "comparisons like %<X<=Y<=Z%> do not "
2128 "have their mathematical meaning");
2129 }
2130 return;
2131 }
2132 #undef NOT_A_BOOLEAN_EXPR_P
2133 }
2134
2135 /* If LABEL (a LABEL_DECL) has not been used, issue a warning. */
2136
2137 void
warn_for_unused_label(tree label)2138 warn_for_unused_label (tree label)
2139 {
2140 if (!TREE_USED (label))
2141 {
2142 if (DECL_INITIAL (label))
2143 warning (OPT_Wunused_label, "label %q+D defined but not used", label);
2144 else
2145 warning (OPT_Wunused_label, "label %q+D declared but not defined", label);
2146 }
2147 else if (asan_sanitize_use_after_scope ())
2148 {
2149 if (asan_used_labels == NULL)
2150 asan_used_labels = new hash_set<tree> (16);
2151
2152 asan_used_labels->add (label);
2153 }
2154 }
2155
2156 /* Warn for division by zero according to the value of DIVISOR. LOC
2157 is the location of the division operator. */
2158
2159 void
warn_for_div_by_zero(location_t loc,tree divisor)2160 warn_for_div_by_zero (location_t loc, tree divisor)
2161 {
2162 /* If DIVISOR is zero, and has integral or fixed-point type, issue a warning
2163 about division by zero. Do not issue a warning if DIVISOR has a
2164 floating-point type, since we consider 0.0/0.0 a valid way of
2165 generating a NaN. */
2166 if (c_inhibit_evaluation_warnings == 0
2167 && (integer_zerop (divisor) || fixed_zerop (divisor)))
2168 warning_at (loc, OPT_Wdiv_by_zero, "division by zero");
2169 }
2170
2171 /* Warn for patterns where memset appears to be used incorrectly. The
2172 warning location should be LOC. ARG0, and ARG2 are the first and
2173 last arguments to the call, while LITERAL_ZERO_MASK has a 1 bit for
2174 each argument that was a literal zero. */
2175
2176 void
warn_for_memset(location_t loc,tree arg0,tree arg2,int literal_zero_mask)2177 warn_for_memset (location_t loc, tree arg0, tree arg2,
2178 int literal_zero_mask)
2179 {
2180 arg0 = fold_for_warn (arg0);
2181 arg2 = fold_for_warn (arg2);
2182
2183 if (warn_memset_transposed_args
2184 && integer_zerop (arg2)
2185 && (literal_zero_mask & (1 << 2)) != 0
2186 && (literal_zero_mask & (1 << 1)) == 0)
2187 warning_at (loc, OPT_Wmemset_transposed_args,
2188 "%<memset%> used with constant zero length "
2189 "parameter; this could be due to transposed "
2190 "parameters");
2191
2192 if (warn_memset_elt_size && TREE_CODE (arg2) == INTEGER_CST)
2193 {
2194 STRIP_NOPS (arg0);
2195 if (TREE_CODE (arg0) == ADDR_EXPR)
2196 arg0 = TREE_OPERAND (arg0, 0);
2197 tree type = TREE_TYPE (arg0);
2198 if (type != NULL_TREE && TREE_CODE (type) == ARRAY_TYPE)
2199 {
2200 tree elt_type = TREE_TYPE (type);
2201 tree domain = TYPE_DOMAIN (type);
2202 if (COMPLETE_TYPE_P (elt_type)
2203 && !integer_onep (TYPE_SIZE_UNIT (elt_type))
2204 && domain != NULL_TREE
2205 && TYPE_MAX_VALUE (domain)
2206 && TYPE_MIN_VALUE (domain)
2207 && integer_zerop (TYPE_MIN_VALUE (domain))
2208 && integer_onep (fold_build2 (MINUS_EXPR, domain,
2209 arg2,
2210 TYPE_MAX_VALUE (domain))))
2211 warning_at (loc, OPT_Wmemset_elt_size,
2212 "%<memset%> used with length equal to "
2213 "number of elements without multiplication "
2214 "by element size");
2215 }
2216 }
2217 }
2218
2219 /* Subroutine of build_binary_op. Give warnings for comparisons
2220 between signed and unsigned quantities that may fail. Do the
2221 checking based on the original operand trees ORIG_OP0 and ORIG_OP1,
2222 so that casts will be considered, but default promotions won't
2223 be.
2224
2225 LOCATION is the location of the comparison operator.
2226
2227 The arguments of this function map directly to local variables
2228 of build_binary_op. */
2229
2230 void
warn_for_sign_compare(location_t location,tree orig_op0,tree orig_op1,tree op0,tree op1,tree result_type,enum tree_code resultcode)2231 warn_for_sign_compare (location_t location,
2232 tree orig_op0, tree orig_op1,
2233 tree op0, tree op1,
2234 tree result_type, enum tree_code resultcode)
2235 {
2236 if (error_operand_p (orig_op0) || error_operand_p (orig_op1))
2237 return;
2238
2239 int op0_signed = !TYPE_UNSIGNED (TREE_TYPE (orig_op0));
2240 int op1_signed = !TYPE_UNSIGNED (TREE_TYPE (orig_op1));
2241 int unsignedp0, unsignedp1;
2242
2243 /* Do not warn if the comparison is being done in a signed type,
2244 since the signed type will only be chosen if it can represent
2245 all the values of the unsigned type. */
2246 if (!TYPE_UNSIGNED (result_type))
2247 /* OK */;
2248 /* Do not warn if both operands are unsigned. */
2249 else if (op0_signed == op1_signed)
2250 /* OK */;
2251 else
2252 {
2253 tree sop, uop, base_type;
2254 bool ovf;
2255
2256 if (op0_signed)
2257 sop = orig_op0, uop = orig_op1;
2258 else
2259 sop = orig_op1, uop = orig_op0;
2260
2261 sop = fold_for_warn (sop);
2262 uop = fold_for_warn (uop);
2263
2264 STRIP_TYPE_NOPS (sop);
2265 STRIP_TYPE_NOPS (uop);
2266 base_type = (TREE_CODE (result_type) == COMPLEX_TYPE
2267 ? TREE_TYPE (result_type) : result_type);
2268
2269 /* Do not warn if the signed quantity is an unsuffixed integer
2270 literal (or some static constant expression involving such
2271 literals or a conditional expression involving such literals)
2272 and it is non-negative. */
2273 if (tree_expr_nonnegative_warnv_p (sop, &ovf))
2274 /* OK */;
2275 /* Do not warn if the comparison is an equality operation, the
2276 unsigned quantity is an integral constant, and it would fit
2277 in the result if the result were signed. */
2278 else if (TREE_CODE (uop) == INTEGER_CST
2279 && (resultcode == EQ_EXPR || resultcode == NE_EXPR)
2280 && int_fits_type_p (uop, c_common_signed_type (base_type)))
2281 /* OK */;
2282 /* In C, do not warn if the unsigned quantity is an enumeration
2283 constant and its maximum value would fit in the result if the
2284 result were signed. */
2285 else if (!c_dialect_cxx() && TREE_CODE (uop) == INTEGER_CST
2286 && TREE_CODE (TREE_TYPE (uop)) == ENUMERAL_TYPE
2287 && int_fits_type_p (TYPE_MAX_VALUE (TREE_TYPE (uop)),
2288 c_common_signed_type (base_type)))
2289 /* OK */;
2290 else
2291 warning_at (location, OPT_Wsign_compare,
2292 "comparison of integer expressions of different "
2293 "signedness: %qT and %qT", TREE_TYPE (orig_op0),
2294 TREE_TYPE (orig_op1));
2295 }
2296
2297 /* Warn if two unsigned values are being compared in a size larger
2298 than their original size, and one (and only one) is the result of
2299 a `~' operator. This comparison will always fail.
2300
2301 Also warn if one operand is a constant, and the constant does not
2302 have all bits set that are set in the ~ operand when it is
2303 extended. */
2304
2305 op0 = c_common_get_narrower (op0, &unsignedp0);
2306 op1 = c_common_get_narrower (op1, &unsignedp1);
2307
2308 if ((TREE_CODE (op0) == BIT_NOT_EXPR)
2309 ^ (TREE_CODE (op1) == BIT_NOT_EXPR))
2310 {
2311 if (TREE_CODE (op0) == BIT_NOT_EXPR)
2312 op0 = c_common_get_narrower (TREE_OPERAND (op0, 0), &unsignedp0);
2313 if (TREE_CODE (op1) == BIT_NOT_EXPR)
2314 op1 = c_common_get_narrower (TREE_OPERAND (op1, 0), &unsignedp1);
2315
2316 if (tree_fits_shwi_p (op0) || tree_fits_shwi_p (op1))
2317 {
2318 tree primop;
2319 HOST_WIDE_INT constant, mask;
2320 int unsignedp;
2321 unsigned int bits;
2322
2323 if (tree_fits_shwi_p (op0))
2324 {
2325 primop = op1;
2326 unsignedp = unsignedp1;
2327 constant = tree_to_shwi (op0);
2328 }
2329 else
2330 {
2331 primop = op0;
2332 unsignedp = unsignedp0;
2333 constant = tree_to_shwi (op1);
2334 }
2335
2336 bits = TYPE_PRECISION (TREE_TYPE (primop));
2337 if (bits < TYPE_PRECISION (result_type)
2338 && bits < HOST_BITS_PER_LONG && unsignedp)
2339 {
2340 mask = HOST_WIDE_INT_M1U << bits;
2341 if ((mask & constant) != mask)
2342 {
2343 if (constant == 0)
2344 warning_at (location, OPT_Wsign_compare,
2345 "promoted bitwise complement of an unsigned "
2346 "value is always nonzero");
2347 else
2348 warning_at (location, OPT_Wsign_compare,
2349 "comparison of promoted bitwise complement "
2350 "of an unsigned value with constant");
2351 }
2352 }
2353 }
2354 else if (unsignedp0 && unsignedp1
2355 && (TYPE_PRECISION (TREE_TYPE (op0))
2356 < TYPE_PRECISION (result_type))
2357 && (TYPE_PRECISION (TREE_TYPE (op1))
2358 < TYPE_PRECISION (result_type)))
2359 warning_at (location, OPT_Wsign_compare,
2360 "comparison of promoted bitwise complement "
2361 "of an unsigned value with unsigned");
2362 }
2363 }
2364
2365 /* RESULT_TYPE is the result of converting TYPE1 and TYPE2 to a common
2366 type via c_common_type. If -Wdouble-promotion is in use, and the
2367 conditions for warning have been met, issue a warning. GMSGID is
2368 the warning message. It must have two %T specifiers for the type
2369 that was converted (generally "float") and the type to which it was
2370 converted (generally "double), respectively. LOC is the location
2371 to which the warning should refer. */
2372
2373 void
do_warn_double_promotion(tree result_type,tree type1,tree type2,const char * gmsgid,location_t loc)2374 do_warn_double_promotion (tree result_type, tree type1, tree type2,
2375 const char *gmsgid, location_t loc)
2376 {
2377 tree source_type;
2378
2379 if (!warn_double_promotion)
2380 return;
2381 /* If the conversion will not occur at run-time, there is no need to
2382 warn about it. */
2383 if (c_inhibit_evaluation_warnings)
2384 return;
2385 /* If an invalid conversion has occurred, don't warn. */
2386 if (result_type == error_mark_node)
2387 return;
2388 if (TYPE_MAIN_VARIANT (result_type) != double_type_node
2389 && TYPE_MAIN_VARIANT (result_type) != complex_double_type_node)
2390 return;
2391 if (TYPE_MAIN_VARIANT (type1) == float_type_node
2392 || TYPE_MAIN_VARIANT (type1) == complex_float_type_node)
2393 source_type = type1;
2394 else if (TYPE_MAIN_VARIANT (type2) == float_type_node
2395 || TYPE_MAIN_VARIANT (type2) == complex_float_type_node)
2396 source_type = type2;
2397 else
2398 return;
2399 warning_at (loc, OPT_Wdouble_promotion, gmsgid, source_type, result_type);
2400 }
2401
2402 /* Possibly warn about unused parameters. */
2403
2404 void
do_warn_unused_parameter(tree fn)2405 do_warn_unused_parameter (tree fn)
2406 {
2407 tree decl;
2408
2409 for (decl = DECL_ARGUMENTS (fn);
2410 decl; decl = DECL_CHAIN (decl))
2411 if (!TREE_USED (decl) && TREE_CODE (decl) == PARM_DECL
2412 && DECL_NAME (decl) && !DECL_ARTIFICIAL (decl)
2413 && !warning_suppressed_p (decl, OPT_Wunused_parameter))
2414 warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wunused_parameter,
2415 "unused parameter %qD", decl);
2416 }
2417
2418 /* If DECL is a typedef that is declared in the current function,
2419 record it for the purpose of -Wunused-local-typedefs. */
2420
2421 void
record_locally_defined_typedef(tree decl)2422 record_locally_defined_typedef (tree decl)
2423 {
2424 struct c_language_function *l;
2425
2426 if (!warn_unused_local_typedefs
2427 || cfun == NULL
2428 /* if this is not a locally defined typedef then we are not
2429 interested. */
2430 || !is_typedef_decl (decl)
2431 || !decl_function_context (decl))
2432 return;
2433
2434 l = (struct c_language_function *) cfun->language;
2435 vec_safe_push (l->local_typedefs, decl);
2436 }
2437
2438 /* If T is a TYPE_DECL declared locally, mark it as used. */
2439
2440 void
maybe_record_typedef_use(tree t)2441 maybe_record_typedef_use (tree t)
2442 {
2443 if (!is_typedef_decl (t))
2444 return;
2445
2446 TREE_USED (t) = true;
2447 }
2448
2449 /* Warn if there are some unused locally defined typedefs in the
2450 current function. */
2451
2452 void
maybe_warn_unused_local_typedefs(void)2453 maybe_warn_unused_local_typedefs (void)
2454 {
2455 int i;
2456 tree decl;
2457 /* The number of times we have emitted -Wunused-local-typedefs
2458 warnings. If this is different from errorcount, that means some
2459 unrelated errors have been issued. In which case, we'll avoid
2460 emitting "unused-local-typedefs" warnings. */
2461 static int unused_local_typedefs_warn_count;
2462 struct c_language_function *l;
2463
2464 if (cfun == NULL)
2465 return;
2466
2467 if ((l = (struct c_language_function *) cfun->language) == NULL)
2468 return;
2469
2470 if (warn_unused_local_typedefs
2471 && errorcount == unused_local_typedefs_warn_count)
2472 {
2473 FOR_EACH_VEC_SAFE_ELT (l->local_typedefs, i, decl)
2474 if (!TREE_USED (decl))
2475 warning_at (DECL_SOURCE_LOCATION (decl),
2476 OPT_Wunused_local_typedefs,
2477 "typedef %qD locally defined but not used", decl);
2478 unused_local_typedefs_warn_count = errorcount;
2479 }
2480
2481 vec_free (l->local_typedefs);
2482 }
2483
2484 /* If we're creating an if-else-if condition chain, first see if we
2485 already have this COND in the CHAIN. If so, warn and don't add COND
2486 into the vector, otherwise add the COND there. LOC is the location
2487 of COND. */
2488
2489 void
warn_duplicated_cond_add_or_warn(location_t loc,tree cond,vec<tree> ** chain)2490 warn_duplicated_cond_add_or_warn (location_t loc, tree cond, vec<tree> **chain)
2491 {
2492 /* No chain has been created yet. Do nothing. */
2493 if (*chain == NULL)
2494 return;
2495
2496 if (TREE_SIDE_EFFECTS (cond))
2497 {
2498 /* Uh-oh! This condition has a side-effect, thus invalidates
2499 the whole chain. */
2500 delete *chain;
2501 *chain = NULL;
2502 return;
2503 }
2504
2505 unsigned int ix;
2506 tree t;
2507 bool found = false;
2508 FOR_EACH_VEC_ELT (**chain, ix, t)
2509 if (operand_equal_p (cond, t, 0))
2510 {
2511 auto_diagnostic_group d;
2512 if (warning_at (loc, OPT_Wduplicated_cond,
2513 "duplicated %<if%> condition"))
2514 inform (EXPR_LOCATION (t), "previously used here");
2515 found = true;
2516 break;
2517 }
2518
2519 if (!found
2520 && !CONSTANT_CLASS_P (cond)
2521 /* Don't infinitely grow the chain. */
2522 && (*chain)->length () < 512)
2523 (*chain)->safe_push (cond);
2524 }
2525
2526 /* Check and possibly warn if two declarations have contradictory
2527 attributes, such as always_inline vs. noinline. */
2528
2529 bool
diagnose_mismatched_attributes(tree olddecl,tree newdecl)2530 diagnose_mismatched_attributes (tree olddecl, tree newdecl)
2531 {
2532 bool warned = false;
2533
2534 tree a1 = lookup_attribute ("optimize", DECL_ATTRIBUTES (olddecl));
2535 tree a2 = lookup_attribute ("optimize", DECL_ATTRIBUTES (newdecl));
2536 /* An optimization attribute applied on a declaration after the
2537 definition is likely not what the user wanted. */
2538 if (a2 != NULL_TREE
2539 && DECL_SAVED_TREE (olddecl) != NULL_TREE
2540 && (a1 == NULL_TREE || !attribute_list_equal (a1, a2)))
2541 warned |= warning (OPT_Wattributes,
2542 "optimization attribute on %qD follows "
2543 "definition but the attribute doesn%'t match",
2544 newdecl);
2545
2546 /* Diagnose inline __attribute__ ((noinline)) which is silly. */
2547 if (DECL_DECLARED_INLINE_P (newdecl)
2548 && DECL_UNINLINABLE (olddecl)
2549 && lookup_attribute ("noinline", DECL_ATTRIBUTES (olddecl)))
2550 warned |= warning (OPT_Wattributes, "inline declaration of %qD follows "
2551 "declaration with attribute %<noinline%>", newdecl);
2552 else if (DECL_DECLARED_INLINE_P (olddecl)
2553 && DECL_UNINLINABLE (newdecl)
2554 && lookup_attribute ("noinline", DECL_ATTRIBUTES (newdecl)))
2555 warned |= warning (OPT_Wattributes, "declaration of %q+D with attribute "
2556 "%<noinline%> follows inline declaration", newdecl);
2557
2558 return warned;
2559 }
2560
2561 /* Warn if signed left shift overflows. We don't warn
2562 about left-shifting 1 into the sign bit in C++14; cf.
2563 <http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3367.html#1457>
2564 and don't warn for C++20 at all, as signed left shifts never
2565 overflow.
2566 LOC is a location of the shift; OP0 and OP1 are the operands.
2567 Return true if an overflow is detected, false otherwise. */
2568
2569 bool
maybe_warn_shift_overflow(location_t loc,tree op0,tree op1)2570 maybe_warn_shift_overflow (location_t loc, tree op0, tree op1)
2571 {
2572 if (TREE_CODE (op0) != INTEGER_CST
2573 || TREE_CODE (op1) != INTEGER_CST)
2574 return false;
2575
2576 tree type0 = TREE_TYPE (op0);
2577 unsigned int prec0 = TYPE_PRECISION (type0);
2578
2579 /* Left-hand operand must be signed. */
2580 if (TYPE_UNSIGNED (type0) || cxx_dialect >= cxx20)
2581 return false;
2582
2583 unsigned int min_prec = (wi::min_precision (wi::to_wide (op0), SIGNED)
2584 + TREE_INT_CST_LOW (op1));
2585 /* Handle the case of left-shifting 1 into the sign bit.
2586 * However, shifting 1 _out_ of the sign bit, as in
2587 * INT_MIN << 1, is considered an overflow.
2588 */
2589 if (!tree_int_cst_sign_bit (op0) && min_prec == prec0 + 1)
2590 {
2591 /* Never warn for C++14 onwards. */
2592 if (cxx_dialect >= cxx14)
2593 return false;
2594 /* Otherwise only if -Wshift-overflow=2. But return
2595 true to signal an overflow for the sake of integer
2596 constant expressions. */
2597 if (warn_shift_overflow < 2)
2598 return true;
2599 }
2600
2601 bool overflowed = min_prec > prec0;
2602 if (overflowed && c_inhibit_evaluation_warnings == 0)
2603 warning_at (loc, OPT_Wshift_overflow_,
2604 "result of %qE requires %u bits to represent, "
2605 "but %qT only has %u bits",
2606 build2_loc (loc, LSHIFT_EXPR, type0, op0, op1),
2607 min_prec, type0, prec0);
2608
2609 return overflowed;
2610 }
2611
2612 /* Warn about boolean expression compared with an integer value different
2613 from true/false. Warns also e.g. about "(i1 == i2) == 2".
2614 LOC is the location of the comparison, CODE is its code, OP0 and OP1
2615 are the operands of the comparison. The caller must ensure that
2616 either operand is a boolean expression. */
2617
2618 void
maybe_warn_bool_compare(location_t loc,enum tree_code code,tree op0,tree op1)2619 maybe_warn_bool_compare (location_t loc, enum tree_code code, tree op0,
2620 tree op1)
2621 {
2622 if (TREE_CODE_CLASS (code) != tcc_comparison)
2623 return;
2624
2625 tree f, cst;
2626 if (f = fold_for_warn (op0),
2627 TREE_CODE (f) == INTEGER_CST)
2628 cst = op0 = f;
2629 else if (f = fold_for_warn (op1),
2630 TREE_CODE (f) == INTEGER_CST)
2631 cst = op1 = f;
2632 else
2633 return;
2634
2635 if (!integer_zerop (cst) && !integer_onep (cst))
2636 {
2637 int sign = (TREE_CODE (op0) == INTEGER_CST
2638 ? tree_int_cst_sgn (cst) : -tree_int_cst_sgn (cst));
2639 if (code == EQ_EXPR
2640 || ((code == GT_EXPR || code == GE_EXPR) && sign < 0)
2641 || ((code == LT_EXPR || code == LE_EXPR) && sign > 0))
2642 warning_at (loc, OPT_Wbool_compare, "comparison of constant %qE "
2643 "with boolean expression is always false", cst);
2644 else
2645 warning_at (loc, OPT_Wbool_compare, "comparison of constant %qE "
2646 "with boolean expression is always true", cst);
2647 }
2648 else if (integer_zerop (cst) || integer_onep (cst))
2649 {
2650 /* If the non-constant operand isn't of a boolean type, we
2651 don't want to warn here. */
2652 tree noncst = TREE_CODE (op0) == INTEGER_CST ? op1 : op0;
2653 /* Handle booleans promoted to integers. */
2654 if (bool_promoted_to_int_p (noncst))
2655 /* Warn. */;
2656 else if (TREE_CODE (TREE_TYPE (noncst)) != BOOLEAN_TYPE
2657 && !truth_value_p (TREE_CODE (noncst)))
2658 return;
2659 /* Do some magic to get the right diagnostics. */
2660 bool flag = TREE_CODE (op0) == INTEGER_CST;
2661 flag = integer_zerop (cst) ? flag : !flag;
2662 if ((code == GE_EXPR && !flag) || (code == LE_EXPR && flag))
2663 warning_at (loc, OPT_Wbool_compare, "comparison of constant %qE "
2664 "with boolean expression is always true", cst);
2665 else if ((code == LT_EXPR && !flag) || (code == GT_EXPR && flag))
2666 warning_at (loc, OPT_Wbool_compare, "comparison of constant %qE "
2667 "with boolean expression is always false", cst);
2668 }
2669 }
2670
2671 /* Warn if an argument at position param_pos is passed to a
2672 restrict-qualified param, and it aliases with another argument.
2673 Return true if a warning has been issued. */
2674
2675 bool
warn_for_restrict(unsigned param_pos,tree * argarray,unsigned nargs)2676 warn_for_restrict (unsigned param_pos, tree *argarray, unsigned nargs)
2677 {
2678 tree arg = argarray[param_pos];
2679 if (TREE_VISITED (arg) || integer_zerop (arg))
2680 return false;
2681
2682 location_t loc = EXPR_LOC_OR_LOC (arg, input_location);
2683 gcc_rich_location richloc (loc);
2684
2685 unsigned i;
2686 auto_vec<int, 16> arg_positions;
2687
2688 for (i = 0; i < nargs; i++)
2689 {
2690 if (i == param_pos)
2691 continue;
2692
2693 tree current_arg = argarray[i];
2694 if (operand_equal_p (arg, current_arg, 0))
2695 {
2696 TREE_VISITED (current_arg) = 1;
2697 arg_positions.safe_push (i + 1);
2698 }
2699 }
2700
2701 if (arg_positions.is_empty ())
2702 return false;
2703
2704 int pos;
2705 FOR_EACH_VEC_ELT (arg_positions, i, pos)
2706 {
2707 arg = argarray[pos - 1];
2708 if (EXPR_HAS_LOCATION (arg))
2709 richloc.add_range (EXPR_LOCATION (arg));
2710 }
2711
2712 return warning_n (&richloc, OPT_Wrestrict, arg_positions.length (),
2713 "passing argument %i to %qs-qualified parameter"
2714 " aliases with argument %Z",
2715 "passing argument %i to %qs-qualified parameter"
2716 " aliases with arguments %Z",
2717 param_pos + 1, "restrict", arg_positions.address (),
2718 arg_positions.length ());
2719 }
2720
2721 /* Callback function to determine whether an expression TP or one of its
2722 subexpressions comes from macro expansion. Used to suppress bogus
2723 warnings. */
2724
2725 static tree
expr_from_macro_expansion_r(tree * tp,int *,void *)2726 expr_from_macro_expansion_r (tree *tp, int *, void *)
2727 {
2728 if (CAN_HAVE_LOCATION_P (*tp)
2729 && from_macro_expansion_at (EXPR_LOCATION (*tp)))
2730 return integer_zero_node;
2731
2732 return NULL_TREE;
2733 }
2734
2735 /* Possibly warn when an if-else has identical branches. */
2736
2737 static void
do_warn_duplicated_branches(tree expr)2738 do_warn_duplicated_branches (tree expr)
2739 {
2740 tree thenb = COND_EXPR_THEN (expr);
2741 tree elseb = COND_EXPR_ELSE (expr);
2742
2743 /* Don't bother if any of the branches is missing. */
2744 if (thenb == NULL_TREE || elseb == NULL_TREE)
2745 return;
2746
2747 /* And don't warn for empty statements. */
2748 if (TREE_CODE (thenb) == NOP_EXPR
2749 && TREE_TYPE (thenb) == void_type_node
2750 && TREE_OPERAND (thenb, 0) == size_zero_node)
2751 return;
2752
2753 /* ... or empty branches. */
2754 if (TREE_CODE (thenb) == STATEMENT_LIST
2755 && STATEMENT_LIST_HEAD (thenb) == NULL)
2756 return;
2757
2758 /* Compute the hash of the then branch. */
2759 inchash::hash hstate0 (0);
2760 inchash::add_expr (thenb, hstate0);
2761 hashval_t h0 = hstate0.end ();
2762
2763 /* Compute the hash of the else branch. */
2764 inchash::hash hstate1 (0);
2765 inchash::add_expr (elseb, hstate1);
2766 hashval_t h1 = hstate1.end ();
2767
2768 /* Compare the hashes. */
2769 if (h0 == h1
2770 && operand_equal_p (thenb, elseb, OEP_LEXICOGRAPHIC
2771 | OEP_ADDRESS_OF_SAME_FIELD)
2772 /* Don't warn if any of the branches or their subexpressions comes
2773 from a macro. */
2774 && !walk_tree_without_duplicates (&thenb, expr_from_macro_expansion_r,
2775 NULL)
2776 && !walk_tree_without_duplicates (&elseb, expr_from_macro_expansion_r,
2777 NULL))
2778 warning_at (EXPR_LOCATION (expr), OPT_Wduplicated_branches,
2779 "this condition has identical branches");
2780 }
2781
2782 /* Callback for c_genericize to implement -Wduplicated-branches. */
2783
2784 tree
do_warn_duplicated_branches_r(tree * tp,int *,void *)2785 do_warn_duplicated_branches_r (tree *tp, int *, void *)
2786 {
2787 if (TREE_CODE (*tp) == COND_EXPR)
2788 do_warn_duplicated_branches (*tp);
2789 return NULL_TREE;
2790 }
2791
2792 /* Implementation of -Wmultistatement-macros. This warning warns about
2793 cases when a macro expands to multiple statements not wrapped in
2794 do {} while (0) or ({ }) and is used as a body of if/else/for/while
2795 conditionals. For example,
2796
2797 #define DOIT x++; y++
2798
2799 if (c)
2800 DOIT;
2801
2802 will increment y unconditionally.
2803
2804 BODY_LOC is the location of the first token in the body after labels
2805 have been parsed, NEXT_LOC is the location of the next token after the
2806 body of the conditional has been parsed, and GUARD_LOC is the location
2807 of the conditional. */
2808
2809 void
warn_for_multistatement_macros(location_t body_loc,location_t next_loc,location_t guard_loc,enum rid keyword)2810 warn_for_multistatement_macros (location_t body_loc, location_t next_loc,
2811 location_t guard_loc, enum rid keyword)
2812 {
2813 if (!warn_multistatement_macros)
2814 return;
2815
2816 /* Ain't got time to waste. We only care about macros here. */
2817 if (!from_macro_expansion_at (body_loc)
2818 || !from_macro_expansion_at (next_loc))
2819 return;
2820
2821 /* Let's skip macros defined in system headers. */
2822 if (in_system_header_at (body_loc)
2823 || in_system_header_at (next_loc))
2824 return;
2825
2826 /* Find the actual tokens in the macro definition. BODY_LOC and
2827 NEXT_LOC have to come from the same spelling location, but they
2828 will resolve to different locations in the context of the macro
2829 definition. */
2830 location_t body_loc_exp
2831 = linemap_resolve_location (line_table, body_loc,
2832 LRK_MACRO_DEFINITION_LOCATION, NULL);
2833 location_t next_loc_exp
2834 = linemap_resolve_location (line_table, next_loc,
2835 LRK_MACRO_DEFINITION_LOCATION, NULL);
2836 location_t guard_loc_exp
2837 = linemap_resolve_location (line_table, guard_loc,
2838 LRK_MACRO_DEFINITION_LOCATION, NULL);
2839
2840 /* These are some funky cases we don't want to warn about. */
2841 if (body_loc_exp == guard_loc_exp
2842 || next_loc_exp == guard_loc_exp
2843 || body_loc_exp == next_loc_exp)
2844 return;
2845
2846 /* Find the macro maps for the macro expansions. */
2847 const line_map *body_map = linemap_lookup (line_table, body_loc);
2848 const line_map *next_map = linemap_lookup (line_table, next_loc);
2849 const line_map *guard_map = linemap_lookup (line_table, guard_loc);
2850
2851 /* Now see if the following token (after the body) is coming from the
2852 same macro expansion. If it is, it might be a problem. */
2853 if (body_map != next_map)
2854 return;
2855
2856 /* The conditional itself must not come from the same expansion, because
2857 we don't want to warn about
2858 #define IF if (x) x++; y++
2859 and similar. */
2860 if (guard_map == body_map)
2861 return;
2862
2863 /* Handle the case where NEXT and BODY come from the same expansion while
2864 GUARD doesn't, yet we shouldn't warn. E.g.
2865
2866 #define GUARD if (...)
2867 #define GUARD2 GUARD
2868
2869 and in the definition of another macro:
2870
2871 GUARD2
2872 foo ();
2873 return 1;
2874 */
2875 while (linemap_macro_expansion_map_p (guard_map))
2876 {
2877 const line_map_macro *mm = linemap_check_macro (guard_map);
2878 guard_loc_exp = MACRO_MAP_EXPANSION_POINT_LOCATION (mm);
2879 guard_map = linemap_lookup (line_table, guard_loc_exp);
2880 if (guard_map == body_map)
2881 return;
2882 }
2883
2884 auto_diagnostic_group d;
2885 if (warning_at (body_loc, OPT_Wmultistatement_macros,
2886 "macro expands to multiple statements"))
2887 inform (guard_loc, "some parts of macro expansion are not guarded by "
2888 "this %qs clause", guard_tinfo_to_string (keyword));
2889 }
2890
2891 /* Return struct or union type if the alignment of data member, FIELD,
2892 is less than the alignment of TYPE. Otherwise, return NULL_TREE.
2893 If RVALUE is true, only arrays evaluate to pointers. */
2894
2895 static tree
check_alignment_of_packed_member(tree type,tree field,bool rvalue)2896 check_alignment_of_packed_member (tree type, tree field, bool rvalue)
2897 {
2898 /* Check alignment of the data member. */
2899 if (TREE_CODE (field) == FIELD_DECL
2900 && (DECL_PACKED (field) || TYPE_PACKED (TREE_TYPE (field)))
2901 /* Ignore FIELDs not laid out yet. */
2902 && DECL_FIELD_OFFSET (field)
2903 && (!rvalue || TREE_CODE (TREE_TYPE (field)) == ARRAY_TYPE))
2904 {
2905 /* Check the expected alignment against the field alignment. */
2906 unsigned int type_align = min_align_of_type (type);
2907 tree context = DECL_CONTEXT (field);
2908 unsigned int record_align = min_align_of_type (context);
2909 if (record_align < type_align)
2910 return context;
2911 tree field_off = byte_position (field);
2912 if (!multiple_of_p (TREE_TYPE (field_off), field_off,
2913 size_int (type_align)))
2914 return context;
2915 }
2916
2917 return NULL_TREE;
2918 }
2919
2920 /* Return struct or union type if the right hand value, RHS:
2921 1. Is a pointer value which isn't aligned to a pointer type TYPE.
2922 2. Is an address which takes the unaligned address of packed member
2923 of struct or union when assigning to TYPE.
2924 Otherwise, return NULL_TREE. */
2925
2926 static tree
check_address_or_pointer_of_packed_member(tree type,tree rhs)2927 check_address_or_pointer_of_packed_member (tree type, tree rhs)
2928 {
2929 bool rvalue = true;
2930 bool indirect = false;
2931
2932 if (INDIRECT_REF_P (rhs))
2933 {
2934 rhs = TREE_OPERAND (rhs, 0);
2935 STRIP_NOPS (rhs);
2936 indirect = true;
2937 }
2938
2939 if (TREE_CODE (rhs) == ADDR_EXPR)
2940 {
2941 rhs = TREE_OPERAND (rhs, 0);
2942 rvalue = indirect;
2943 }
2944
2945 if (!POINTER_TYPE_P (type))
2946 return NULL_TREE;
2947
2948 type = TREE_TYPE (type);
2949
2950 if (TREE_CODE (rhs) == PARM_DECL
2951 || VAR_P (rhs)
2952 || TREE_CODE (rhs) == CALL_EXPR)
2953 {
2954 tree rhstype = TREE_TYPE (rhs);
2955 if (TREE_CODE (rhs) == CALL_EXPR)
2956 {
2957 rhs = CALL_EXPR_FN (rhs); /* Pointer expression. */
2958 if (rhs == NULL_TREE)
2959 return NULL_TREE;
2960 rhs = TREE_TYPE (rhs); /* Pointer type. */
2961 rhs = TREE_TYPE (rhs); /* Function type. */
2962 rhstype = TREE_TYPE (rhs);
2963 if (!rhstype || !POINTER_TYPE_P (rhstype))
2964 return NULL_TREE;
2965 rvalue = true;
2966 }
2967 if (rvalue && POINTER_TYPE_P (rhstype))
2968 rhstype = TREE_TYPE (rhstype);
2969 while (TREE_CODE (rhstype) == ARRAY_TYPE)
2970 rhstype = TREE_TYPE (rhstype);
2971 if (TYPE_PACKED (rhstype))
2972 {
2973 unsigned int type_align = min_align_of_type (type);
2974 unsigned int rhs_align = min_align_of_type (rhstype);
2975 if (rhs_align < type_align)
2976 {
2977 auto_diagnostic_group d;
2978 location_t location = EXPR_LOC_OR_LOC (rhs, input_location);
2979 if (warning_at (location, OPT_Waddress_of_packed_member,
2980 "converting a packed %qT pointer (alignment %d) "
2981 "to a %qT pointer (alignment %d) may result in "
2982 "an unaligned pointer value",
2983 rhstype, rhs_align, type, type_align))
2984 {
2985 tree decl = TYPE_STUB_DECL (rhstype);
2986 if (decl)
2987 inform (DECL_SOURCE_LOCATION (decl), "defined here");
2988 decl = TYPE_STUB_DECL (type);
2989 if (decl)
2990 inform (DECL_SOURCE_LOCATION (decl), "defined here");
2991 }
2992 }
2993 }
2994 return NULL_TREE;
2995 }
2996
2997 tree context = NULL_TREE;
2998
2999 /* Check alignment of the object. */
3000 while (handled_component_p (rhs))
3001 {
3002 if (TREE_CODE (rhs) == COMPONENT_REF)
3003 {
3004 tree field = TREE_OPERAND (rhs, 1);
3005 context = check_alignment_of_packed_member (type, field, rvalue);
3006 if (context)
3007 break;
3008 }
3009 if (TREE_CODE (TREE_TYPE (rhs)) == ARRAY_TYPE)
3010 rvalue = false;
3011 if (rvalue)
3012 return NULL_TREE;
3013 rhs = TREE_OPERAND (rhs, 0);
3014 }
3015
3016 return context;
3017 }
3018
3019 /* Check and warn if the right hand value, RHS:
3020 1. Is a pointer value which isn't aligned to a pointer type TYPE.
3021 2. Is an address which takes the unaligned address of packed member
3022 of struct or union when assigning to TYPE.
3023 */
3024
3025 static void
check_and_warn_address_or_pointer_of_packed_member(tree type,tree rhs)3026 check_and_warn_address_or_pointer_of_packed_member (tree type, tree rhs)
3027 {
3028 bool nop_p = false;
3029 tree orig_rhs;
3030
3031 do
3032 {
3033 while (TREE_CODE (rhs) == COMPOUND_EXPR)
3034 rhs = TREE_OPERAND (rhs, 1);
3035 orig_rhs = rhs;
3036 STRIP_NOPS (rhs);
3037 nop_p |= orig_rhs != rhs;
3038 }
3039 while (orig_rhs != rhs);
3040
3041 if (TREE_CODE (rhs) == COND_EXPR)
3042 {
3043 /* Check the THEN path. */
3044 check_and_warn_address_or_pointer_of_packed_member
3045 (type, TREE_OPERAND (rhs, 1));
3046
3047 /* Check the ELSE path. */
3048 check_and_warn_address_or_pointer_of_packed_member
3049 (type, TREE_OPERAND (rhs, 2));
3050 }
3051 else
3052 {
3053 if (nop_p)
3054 {
3055 switch (TREE_CODE (rhs))
3056 {
3057 case ADDR_EXPR:
3058 /* Address is taken. */
3059 case PARM_DECL:
3060 case VAR_DECL:
3061 /* Pointer conversion. */
3062 break;
3063 case CALL_EXPR:
3064 /* Function call. */
3065 break;
3066 default:
3067 return;
3068 }
3069 }
3070
3071 tree context
3072 = check_address_or_pointer_of_packed_member (type, rhs);
3073 if (context)
3074 {
3075 location_t loc = EXPR_LOC_OR_LOC (rhs, input_location);
3076 warning_at (loc, OPT_Waddress_of_packed_member,
3077 "taking address of packed member of %qT may result "
3078 "in an unaligned pointer value",
3079 context);
3080 }
3081 }
3082 }
3083
3084 /* Warn if the right hand value, RHS:
3085 1. Is a pointer value which isn't aligned to a pointer type TYPE.
3086 2. Is an address which takes the unaligned address of packed member
3087 of struct or union when assigning to TYPE.
3088 */
3089
3090 void
warn_for_address_or_pointer_of_packed_member(tree type,tree rhs)3091 warn_for_address_or_pointer_of_packed_member (tree type, tree rhs)
3092 {
3093 if (!warn_address_of_packed_member)
3094 return;
3095
3096 /* Don't warn if we don't assign RHS to a pointer. */
3097 if (!POINTER_TYPE_P (type))
3098 return;
3099
3100 check_and_warn_address_or_pointer_of_packed_member (type, rhs);
3101 }
3102
3103 /* Return EXPR + 1. Convenience helper used below. */
3104
3105 static inline tree
plus_one(tree expr)3106 plus_one (tree expr)
3107 {
3108 tree type = TREE_TYPE (expr);
3109 return fold_build2 (PLUS_EXPR, type, expr, build_int_cst (type, 1));
3110 }
3111
3112 /* Try to strip the expressions from around a VLA bound added internally
3113 to make it fit the domain mold, including any casts, and return
3114 the result. The goal is to obtain the PARM_DECL the VLA bound may
3115 refer to. */
3116
3117 static tree
vla_bound_parm_decl(tree expr)3118 vla_bound_parm_decl (tree expr)
3119 {
3120 if (!expr)
3121 return NULL_TREE;
3122
3123 if (TREE_CODE (expr) == NOP_EXPR)
3124 expr = TREE_OPERAND (expr, 0);
3125 if (TREE_CODE (expr) == PLUS_EXPR
3126 && integer_all_onesp (TREE_OPERAND (expr, 1)))
3127 {
3128 expr = TREE_OPERAND (expr, 0);
3129 if (TREE_CODE (expr) == NOP_EXPR)
3130 expr = TREE_OPERAND (expr, 0);
3131 }
3132 if (TREE_CODE (expr) == SAVE_EXPR)
3133 {
3134 expr = TREE_OPERAND (expr, 0);
3135 if (TREE_CODE (expr) == NOP_EXPR)
3136 expr = TREE_OPERAND (expr, 0);
3137 }
3138 return expr;
3139 }
3140
3141 /* Diagnose mismatches in VLA bounds between function parameters NEWPARMS
3142 of pointer types on a redeclaration of a function previously declared
3143 with CURPARMS at ORIGLOC. */
3144
3145 static void
warn_parm_ptrarray_mismatch(location_t origloc,tree curparms,tree newparms)3146 warn_parm_ptrarray_mismatch (location_t origloc, tree curparms, tree newparms)
3147 {
3148 /* Maps each named integral parameter seen so far to its position
3149 in the argument list; used to associate VLA sizes with arguments. */
3150 hash_map<tree, unsigned> curparm2pos;
3151 hash_map<tree, unsigned> newparm2pos;
3152
3153 unsigned parmpos = 1;
3154 for (tree curp = curparms, newp = newparms; curp && newp;
3155 curp = TREE_CHAIN (curp), newp = TREE_CHAIN (newp), ++parmpos)
3156 {
3157 tree curtyp = TREE_TYPE (curp), newtyp = TREE_TYPE (newp);
3158 if (INTEGRAL_TYPE_P (curtyp))
3159 {
3160 /* Only add named parameters; unnamed ones cannot be referred
3161 to in VLA bounds. */
3162 if (DECL_NAME (curp))
3163 curparm2pos.put (curp, parmpos);
3164 if (DECL_NAME (newp))
3165 newparm2pos.put (newp, parmpos);
3166
3167 continue;
3168 }
3169
3170 /* The parameter types should match at this point so only test one. */
3171 if (TREE_CODE (curtyp) != POINTER_TYPE)
3172 continue;
3173
3174 do
3175 {
3176 curtyp = TREE_TYPE (curtyp);
3177 newtyp = TREE_TYPE (newtyp);
3178
3179 if (!newtyp)
3180 /* Bail on error. */
3181 return;
3182 }
3183 while (TREE_CODE (curtyp) == POINTER_TYPE
3184 && TREE_CODE (newtyp) == POINTER_TYPE);
3185
3186 if (TREE_CODE (curtyp) != ARRAY_TYPE
3187 || TREE_CODE (newtyp) != ARRAY_TYPE)
3188 {
3189 if (curtyp == error_mark_node
3190 || newtyp == error_mark_node)
3191 /* Bail on error. */
3192 return;
3193
3194 continue;
3195 }
3196
3197 tree curdom = TYPE_DOMAIN (curtyp), newdom = TYPE_DOMAIN (newtyp);
3198 tree curbnd = curdom ? TYPE_MAX_VALUE (curdom) : NULL_TREE;
3199 tree newbnd = newdom ? TYPE_MAX_VALUE (newdom) : NULL_TREE;
3200
3201 if (DECL_P (curp))
3202 origloc = DECL_SOURCE_LOCATION (curp);
3203 else if (EXPR_P (curp) && EXPR_HAS_LOCATION (curp))
3204 origloc = EXPR_LOCATION (curp);
3205
3206 /* The location of the parameter in the current redeclaration. */
3207 location_t newloc = DECL_SOURCE_LOCATION (newp);
3208 if (origloc == UNKNOWN_LOCATION)
3209 origloc = newloc;
3210
3211 /* Issue -Warray-parameter unless one or more mismatches involves
3212 a VLA bound; then issue -Wvla-parameter. */
3213 int opt = OPT_Warray_parameter_;
3214 /* Traverse the two array types looking for variable bounds and
3215 comparing the two in each pair for mismatches either in their
3216 positions in the function parameter list or lexicographically
3217 for others. Record the 1-based parameter position of each
3218 mismatch in BNDVEC, and the location of each parameter in
3219 the mismatch in WARNLOC (for the new parameter list) and
3220 NOTELOC (for the current parameter list). */
3221 unsigned bndpos = 1;
3222 auto_vec<int> bndvec;
3223 gcc_rich_location warnloc (newloc);
3224 gcc_rich_location noteloc (origloc);
3225 for ( ; curtyp || newtyp;
3226 ++bndpos,
3227 curbnd = curdom ? TYPE_MAX_VALUE (curdom) : NULL_TREE,
3228 newbnd = newdom ? TYPE_MAX_VALUE (newdom) : NULL_TREE)
3229 {
3230 /* Try to strip each bound down to the PARM_DECL if it does
3231 correspond to one. Either bound can be null if it's
3232 unspecified (i.e., has the [*] form). */
3233 curbnd = vla_bound_parm_decl (curbnd);
3234 newbnd = vla_bound_parm_decl (newbnd);
3235
3236 /* Peel the current bound off CURTYP and NEWTYP, skipping
3237 over any subsequent pointer types. */
3238 if (curtyp && TREE_CODE (curtyp) == ARRAY_TYPE)
3239 {
3240 do
3241 curtyp = TREE_TYPE (curtyp);
3242 while (TREE_CODE (curtyp) == POINTER_TYPE);
3243 if (TREE_CODE (curtyp) == ARRAY_TYPE)
3244 curdom = TYPE_DOMAIN (curtyp);
3245 else
3246 curdom = NULL_TREE;
3247 }
3248 else
3249 curtyp = NULL_TREE;
3250
3251 if (newtyp && TREE_CODE (newtyp) == ARRAY_TYPE)
3252 {
3253 do
3254 newtyp = TREE_TYPE (newtyp);
3255 while (TREE_CODE (newtyp) == POINTER_TYPE);
3256 if (TREE_CODE (newtyp) == ARRAY_TYPE)
3257 newdom = TYPE_DOMAIN (newtyp);
3258 else
3259 newdom = NULL_TREE;
3260 }
3261 else
3262 newtyp = NULL_TREE;
3263
3264 /* Move on to the next bound if this one is unspecified. */
3265 if (!curbnd && !newbnd)
3266 continue;
3267
3268 /* Try to find each bound in the parameter list. */
3269 const unsigned* const pcurbndpos = curparm2pos.get (curbnd);
3270 const unsigned* const pnewbndpos = newparm2pos.get (newbnd);
3271 /* Move on if both bounds refer to the same parameter. */
3272 if (pcurbndpos && pnewbndpos && *pcurbndpos == *pnewbndpos)
3273 continue;
3274
3275 /* Move on if the bounds look the same. */
3276 if (!pcurbndpos && !pnewbndpos
3277 && curbnd && newbnd
3278 && operand_equal_p (curbnd, newbnd,
3279 OEP_DECL_NAME | OEP_LEXICOGRAPHIC))
3280 continue;
3281
3282 if ((curbnd && TREE_CODE (curbnd) != INTEGER_CST)
3283 || (newbnd && TREE_CODE (newbnd) != INTEGER_CST))
3284 opt = OPT_Wvla_parameter;
3285
3286 /* Record the mismatch. */
3287 bndvec.safe_push (bndpos);
3288 /* Underline the bounding parameter in the declaration. */
3289 if (curbnd && TREE_CODE (curbnd) == PARM_DECL)
3290 noteloc.add_range (DECL_SOURCE_LOCATION (curbnd));
3291 if (newbnd && TREE_CODE (newbnd) == PARM_DECL)
3292 warnloc.add_range (DECL_SOURCE_LOCATION (newbnd));
3293 }
3294
3295 const unsigned nbnds = bndvec.length ();
3296 if (!nbnds)
3297 continue;
3298
3299 /* Use attr_access to format the parameter types. */
3300 attr_access spec = { };
3301 const std::string newparmstr = spec.array_as_string (TREE_TYPE (newp));
3302 const std::string curparmstr = spec.array_as_string (TREE_TYPE (curp));
3303
3304 if (warning_n (&warnloc, opt, nbnds,
3305 "mismatch in bound %Z of argument %u declared as %s",
3306 "mismatch in bounds %Z of argument %u declared as %s",
3307 bndvec.address (), nbnds, parmpos, newparmstr.c_str ()))
3308 inform (¬eloc, "previously declared as %s", curparmstr.c_str ());
3309 }
3310 }
3311
3312 /* Format EXPR if nonnull and return the formatted string. If EXPR is
3313 null return DFLT. */
3314
3315 static inline const char*
expr_to_str(pretty_printer & pp,tree expr,const char * dflt)3316 expr_to_str (pretty_printer &pp, tree expr, const char *dflt)
3317 {
3318 if (!expr)
3319 return dflt;
3320
3321 dump_generic_node (&pp, expr, 0, TDF_VOPS | TDF_MEMSYMS, false);
3322 return pp_formatted_text (&pp);
3323 }
3324
3325 /* Detect and diagnose a mismatch between an attribute access specification
3326 on the original declaration of FNDECL and that on the parameters NEWPARMS
3327 from its redeclaration. ORIGLOC is the location of the first declaration
3328 (FNDECL's is set to the location of the redeclaration). */
3329
3330 void
warn_parm_array_mismatch(location_t origloc,tree fndecl,tree newparms)3331 warn_parm_array_mismatch (location_t origloc, tree fndecl, tree newparms)
3332 {
3333 /* The original parameter list (copied from the original declaration
3334 into the current [re]declaration, FNDECL)). The two are equal if
3335 and only if FNDECL is the first declaration. */
3336 tree curparms = DECL_ARGUMENTS (fndecl);
3337 if (!curparms || !newparms || curparms == newparms)
3338 return;
3339
3340 if (TREE_CODE (curparms) != PARM_DECL
3341 || TREE_CODE (newparms) != PARM_DECL)
3342 return;
3343 /* Extract the (possibly empty) attribute access specification from
3344 the declaration and its type (it doesn't yet reflect those created
3345 in response to NEWPARMS). */
3346 rdwr_map cur_idx;
3347 tree fntype = TREE_TYPE (fndecl);
3348 init_attr_rdwr_indices (&cur_idx, TYPE_ATTRIBUTES (fntype));
3349
3350 /* Build a (possibly null) chain of access attributes corresponding
3351 to NEWPARMS. */
3352 const bool builtin = fndecl_built_in_p (fndecl);
3353 tree newattrs = build_attr_access_from_parms (newparms, builtin);
3354
3355 /* Extract the (possibly empty) attribute access specification from
3356 NEWATTRS. */
3357 rdwr_map new_idx;
3358 init_attr_rdwr_indices (&new_idx, newattrs);
3359
3360 if (cur_idx.is_empty () && new_idx.is_empty ())
3361 {
3362 /* If both specs are empty check pointers to VLAs for mismatches. */
3363 warn_parm_ptrarray_mismatch (origloc, curparms, newparms);
3364 return;
3365 }
3366 /* ...otherwise, if at least one spec isn't empty there may be mismatches,
3367 such as between f(T*) and f(T[1]), where the former mapping would be
3368 empty. */
3369
3370 /* Create an empty access specification and use it for pointers with
3371 no spec of their own. */
3372 attr_access ptr_spec = { };
3373
3374 /* Iterate over the two lists of function parameters, comparing their
3375 respective mappings and diagnosing mismatches. */
3376 unsigned parmpos = 0;
3377 for (tree curp = curparms, newp = newparms; curp;
3378 curp = TREE_CHAIN (curp), newp = TREE_CHAIN (newp), ++parmpos)
3379 {
3380 if (!newp)
3381 /* Bail on invalid redeclarations with fewer arguments. */
3382 return;
3383
3384 /* Only check pointers and C++ references. */
3385 tree curptype = TREE_TYPE (curp);
3386 tree newptype = TREE_TYPE (newp);
3387 if (!POINTER_TYPE_P (curptype) || !POINTER_TYPE_P (newptype))
3388 continue;
3389
3390 /* Skip mismatches in __builtin_va_list that is commonly
3391 an array but that in declarations of built-ins decays
3392 to a pointer. */
3393 if (builtin && TREE_TYPE (newptype) == TREE_TYPE (va_list_type_node))
3394 continue;
3395
3396 /* Access specs for the argument on the current (previous) and
3397 new (to replace the current) declarations. Either may be null,
3398 indicating the parameter is an ordinary pointer with no size
3399 associated with it. */
3400 attr_access *cura = cur_idx.get (parmpos);
3401 attr_access *newa = new_idx.get (parmpos);
3402
3403 if (!newa)
3404 {
3405 /* Continue of both parameters are pointers with no size
3406 associated with it. */
3407 if (!cura)
3408 continue;
3409
3410 /* Otherwise point at PTR_SPEC and set its parameter pointer
3411 and number. */
3412 newa = &ptr_spec;
3413 newa->ptr = newp;
3414 newa->ptrarg = parmpos;
3415 }
3416 else if (!cura)
3417 {
3418 cura = &ptr_spec;
3419 cura->ptr = curp;
3420 cura->ptrarg = parmpos;
3421 }
3422
3423 /* Set if the parameter is [re]declared as a VLA. */
3424 const bool cur_vla_p = cura->size || cura->minsize == HOST_WIDE_INT_M1U;
3425 const bool new_vla_p = newa->size || newa->minsize == HOST_WIDE_INT_M1U;
3426
3427 if (DECL_P (curp))
3428 origloc = DECL_SOURCE_LOCATION (curp);
3429 else if (EXPR_P (curp) && EXPR_HAS_LOCATION (curp))
3430 origloc = EXPR_LOCATION (curp);
3431
3432 /* The location of the parameter in the current redeclaration. */
3433 location_t newloc = DECL_SOURCE_LOCATION (newp);
3434 if (origloc == UNKNOWN_LOCATION)
3435 origloc = newloc;
3436
3437 const std::string newparmstr = newa->array_as_string (newptype);
3438 const std::string curparmstr = cura->array_as_string (curptype);
3439 if (new_vla_p && !cur_vla_p)
3440 {
3441 if (warning_at (newloc, OPT_Wvla_parameter,
3442 "argument %u of type %s declared as "
3443 "a variable length array",
3444 parmpos + 1, newparmstr.c_str ()))
3445 inform (origloc,
3446 (cura == &ptr_spec
3447 ? G_("previously declared as a pointer %s")
3448 : G_("previously declared as an ordinary array %s")),
3449 curparmstr.c_str ());
3450 continue;
3451 }
3452
3453 if (newa == &ptr_spec)
3454 {
3455 /* The new declaration uses the pointer form. Detect mismatches
3456 between the pointer and a previous array or VLA forms. */
3457 if (cura->minsize == HOST_WIDE_INT_M1U)
3458 {
3459 /* Diagnose a pointer/VLA mismatch. */
3460 if (warning_at (newloc, OPT_Wvla_parameter,
3461 "argument %u of type %s declared "
3462 "as a pointer",
3463 parmpos + 1, newparmstr.c_str ()))
3464 inform (origloc,
3465 "previously declared as a variable length array %s",
3466 curparmstr.c_str ());
3467 continue;
3468 }
3469
3470 if (cura->minsize && cura->minsize != HOST_WIDE_INT_M1U)
3471 {
3472 /* Diagnose mismatches between arrays with a constant
3473 bound and pointers. */
3474 if (warning_at (newloc, OPT_Warray_parameter_,
3475 "argument %u of type %s declared "
3476 "as a pointer",
3477 parmpos + 1, newparmstr.c_str ()))
3478 inform (origloc, "previously declared as an array %s",
3479 curparmstr.c_str ());
3480 continue;
3481 }
3482 }
3483
3484 if (!new_vla_p && cur_vla_p)
3485 {
3486 if (warning_at (newloc, OPT_Wvla_parameter,
3487 "argument %u of type %s declared "
3488 "as an ordinary array",
3489 parmpos + 1, newparmstr.c_str ()))
3490 inform (origloc,
3491 "previously declared as a variable length array %s",
3492 curparmstr.c_str ());
3493 continue;
3494 }
3495
3496 /* Move on to the next pair of parameters if both of the current
3497 pair are VLAs with a single variable bound that refers to
3498 a parameter at the same position. */
3499 if (newa->size && cura->size
3500 && newa->sizarg != UINT_MAX
3501 && newa->sizarg == cura->sizarg
3502 && newa->minsize == cura->minsize
3503 && !TREE_PURPOSE (newa->size) && !TREE_PURPOSE (cura->size))
3504 continue;
3505
3506 if (newa->size || cura->size)
3507 {
3508 unsigned newunspec, curunspec;
3509 unsigned newbnds = newa->vla_bounds (&newunspec) + newunspec;
3510 unsigned curbnds = cura->vla_bounds (&curunspec) + curunspec;
3511
3512 if (newbnds != curbnds)
3513 {
3514 if (warning_n (newloc, OPT_Wvla_parameter, newbnds,
3515 "argument %u of type %s declared with "
3516 "%u variable bound",
3517 "argument %u of type %s declared with "
3518 "%u variable bounds",
3519 parmpos + 1, newparmstr.c_str (),
3520 newbnds))
3521 inform_n (origloc, curbnds,
3522 "previously declared as %s with %u variable bound",
3523 "previously declared as %s with %u variable bounds",
3524 curparmstr.c_str (), curbnds);
3525 continue;
3526 }
3527
3528 if (newunspec != curunspec)
3529 {
3530 location_t warnloc = newloc, noteloc = origloc;
3531 const char *warnparmstr = newparmstr.c_str ();
3532 const char *noteparmstr = curparmstr.c_str ();
3533 unsigned warnunspec = newunspec, noteunspec = curunspec;
3534
3535 if (newunspec < curunspec)
3536 {
3537 /* If the new declaration has fewer unspecified bounds
3538 point the warning to the previous declaration to make
3539 it clear that that's the one to change. Otherwise,
3540 point it to the new decl. */
3541 std::swap (warnloc, noteloc);
3542 std::swap (warnparmstr, noteparmstr);
3543 std::swap (warnunspec, noteunspec);
3544 }
3545 if (warning_n (warnloc, OPT_Wvla_parameter, warnunspec,
3546 "argument %u of type %s declared with "
3547 "%u unspecified variable bound",
3548 "argument %u of type %s declared with "
3549 "%u unspecified variable bounds",
3550 parmpos + 1, warnparmstr, warnunspec))
3551 {
3552 if (warnloc == newloc)
3553 inform_n (noteloc, noteunspec,
3554 "previously declared as %s with %u unspecified "
3555 "variable bound",
3556 "previously declared as %s with %u unspecified "
3557 "variable bounds",
3558 noteparmstr, noteunspec);
3559 else
3560 inform_n (noteloc, noteunspec,
3561 "subsequently declared as %s with %u unspecified "
3562 "variable bound",
3563 "subsequently declared as %s with %u unspecified "
3564 "variable bounds",
3565 noteparmstr, noteunspec);
3566 }
3567 continue;
3568 }
3569 }
3570
3571 /* Iterate over the lists of VLA variable bounds, comparing each
3572 pair for equality, and diagnosing mismatches. The case of
3573 the lists having different lengths is handled above so at
3574 this point they do . */
3575 for (tree newvbl = newa->size, curvbl = cura->size; newvbl;
3576 newvbl = TREE_CHAIN (newvbl), curvbl = TREE_CHAIN (curvbl))
3577 {
3578 tree newpos = TREE_PURPOSE (newvbl);
3579 tree curpos = TREE_PURPOSE (curvbl);
3580
3581 tree newbnd = vla_bound_parm_decl (TREE_VALUE (newvbl));
3582 tree curbnd = vla_bound_parm_decl (TREE_VALUE (curvbl));
3583
3584 if (newpos == curpos && newbnd == curbnd)
3585 /* In the expected case when both bounds either refer to
3586 the same positional parameter or when neither does,
3587 and both are the same expression they are necessarily
3588 the same. */
3589 continue;
3590
3591 pretty_printer pp1, pp2;
3592 const char* const newbndstr = expr_to_str (pp1, newbnd, "*");
3593 const char* const curbndstr = expr_to_str (pp2, curbnd, "*");
3594
3595 if (!newpos != !curpos
3596 || (newpos && !tree_int_cst_equal (newpos, curpos)))
3597 {
3598 /* Diagnose a mismatch between a specified VLA bound and
3599 an unspecified one. This can only happen in the most
3600 significant bound.
3601
3602 Distinguish between the common case of bounds that are
3603 other function parameters such as in
3604 f (int n, int[n]);
3605 and others. */
3606
3607 gcc_rich_location richloc (newloc);
3608 bool warned;
3609 if (newpos)
3610 {
3611 /* Also underline the VLA bound argument. */
3612 richloc.add_range (DECL_SOURCE_LOCATION (newbnd));
3613 warned = warning_at (&richloc, OPT_Wvla_parameter,
3614 "argument %u of type %s declared "
3615 "with mismatched bound argument %E",
3616 parmpos + 1, newparmstr.c_str (),
3617 plus_one (newpos));
3618 }
3619 else
3620 warned = warning_at (&richloc, OPT_Wvla_parameter,
3621 "argument %u of type %s declared "
3622 "with mismatched bound %<%s%>",
3623 parmpos + 1, newparmstr.c_str (),
3624 newbndstr);
3625
3626 if (warned)
3627 {
3628 gcc_rich_location richloc (origloc);
3629 if (curpos)
3630 {
3631 /* Also underline the VLA bound argument. */
3632 richloc.add_range (DECL_SOURCE_LOCATION (curbnd));
3633 inform (&richloc, "previously declared as %s with "
3634 "bound argument %E",
3635 curparmstr.c_str (), plus_one (curpos));
3636 }
3637 else
3638 inform (&richloc, "previously declared as %s with bound "
3639 "%<%s%>", curparmstr.c_str (), curbndstr);
3640
3641 continue;
3642 }
3643 }
3644
3645 if (!newpos && newbnd && curbnd)
3646 {
3647 /* The VLA bounds don't refer to other function parameters.
3648 Compare them lexicographically to detect gross mismatches
3649 such as between T[foo()] and T[bar()]. */
3650 if (operand_equal_p (newbnd, curbnd,
3651 OEP_DECL_NAME | OEP_LEXICOGRAPHIC))
3652 continue;
3653
3654 if (warning_at (newloc, OPT_Wvla_parameter,
3655 "argument %u of type %s declared with "
3656 "mismatched bound %<%s%>",
3657 parmpos + 1, newparmstr.c_str (), newbndstr))
3658 inform (origloc, "previously declared as %s with bound %qs",
3659 curparmstr.c_str (), curbndstr);
3660 continue;
3661 }
3662 }
3663
3664 if (newa->minsize == cura->minsize
3665 || (((newa->minsize == 0 && newa->mode != access_deferred)
3666 || (cura->minsize == 0 && cura->mode != access_deferred))
3667 && newa != &ptr_spec
3668 && cura != &ptr_spec))
3669 continue;
3670
3671 if (!newa->static_p && !cura->static_p && warn_array_parameter < 2)
3672 /* Avoid warning about mismatches in ordinary (non-static) arrays
3673 at levels below 2. */
3674 continue;
3675
3676 if (warning_at (newloc, OPT_Warray_parameter_,
3677 "argument %u of type %s with mismatched bound",
3678 parmpos + 1, newparmstr.c_str ()))
3679 inform (origloc, "previously declared as %s", curparmstr.c_str ());
3680 }
3681 }
3682
3683 /* Warn about divisions of two sizeof operators when the first one is applied
3684 to an array and the divisor does not equal the size of the array element.
3685 For instance:
3686
3687 sizeof (ARR) / sizeof (OP)
3688
3689 ARR is the array argument of the first sizeof, ARR_TYPE is its ARRAY_TYPE.
3690 OP1 is the whole second SIZEOF_EXPR, or its argument; TYPE1 is the type
3691 of the second argument. */
3692
3693 void
maybe_warn_sizeof_array_div(location_t loc,tree arr,tree arr_type,tree op1,tree type1)3694 maybe_warn_sizeof_array_div (location_t loc, tree arr, tree arr_type,
3695 tree op1, tree type1)
3696 {
3697 tree elt_type = TREE_TYPE (arr_type);
3698
3699 if (!warn_sizeof_array_div
3700 /* Don't warn on multidimensional arrays. */
3701 || TREE_CODE (elt_type) == ARRAY_TYPE)
3702 return;
3703
3704 if (!tree_int_cst_equal (TYPE_SIZE (elt_type), TYPE_SIZE (type1)))
3705 {
3706 auto_diagnostic_group d;
3707 if (warning_at (loc, OPT_Wsizeof_array_div,
3708 "expression does not compute the number of "
3709 "elements in this array; element type is "
3710 "%qT, not %qT", elt_type, type1))
3711 {
3712 if (EXPR_HAS_LOCATION (op1))
3713 {
3714 location_t op1_loc = EXPR_LOCATION (op1);
3715 gcc_rich_location richloc (op1_loc);
3716 richloc.add_fixit_insert_before (op1_loc, "(");
3717 richloc.add_fixit_insert_after (op1_loc, ")");
3718 inform (&richloc, "add parentheses around %qE to "
3719 "silence this warning", op1);
3720 }
3721 else
3722 inform (loc, "add parentheses around the second %<sizeof%> "
3723 "to silence this warning");
3724 if (DECL_P (arr))
3725 inform (DECL_SOURCE_LOCATION (arr), "array %qD declared here", arr);
3726 }
3727 }
3728 }
3729
3730 /* Warn about C++20 [depr.array.comp] array comparisons: "Equality
3731 and relational comparisons between two operands of array type are
3732 deprecated." We also warn in C and earlier C++ standards. CODE is
3733 the code for this comparison, OP0 and OP1 are the operands. */
3734
3735 void
do_warn_array_compare(location_t location,tree_code code,tree op0,tree op1)3736 do_warn_array_compare (location_t location, tree_code code, tree op0, tree op1)
3737 {
3738 STRIP_NOPS (op0);
3739 STRIP_NOPS (op1);
3740 if (TREE_CODE (op0) == ADDR_EXPR)
3741 op0 = TREE_OPERAND (op0, 0);
3742 if (TREE_CODE (op1) == ADDR_EXPR)
3743 op1 = TREE_OPERAND (op1, 0);
3744
3745 auto_diagnostic_group d;
3746 if (warning_at (location, OPT_Warray_compare,
3747 (c_dialect_cxx () && cxx_dialect >= cxx20)
3748 ? G_("comparison between two arrays is deprecated in C++20")
3749 : G_("comparison between two arrays")))
3750 {
3751 /* C doesn't allow +arr. */
3752 if (c_dialect_cxx ())
3753 inform (location, "use unary %<+%> which decays operands to pointers "
3754 "or %<&%D[0] %s &%D[0]%> to compare the addresses",
3755 op0, op_symbol_code (code), op1);
3756 else
3757 inform (location, "use %<&%D[0] %s &%D[0]%> to compare the addresses",
3758 op0, op_symbol_code (code), op1);
3759 }
3760 }
3761