1 /* Diagnostic routines shared by all languages that are variants of C.
2 Copyright (C) 1992-2022 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 ((op1 && conversion_warning (loc, type, op1, result))
1304 || conversion_warning (loc, type, op2, result));
1305 }
1306
1307 case BIT_AND_EXPR:
1308 if (TREE_CODE (expr_type) == INTEGER_TYPE
1309 && TREE_CODE (type) == INTEGER_TYPE)
1310 for (int i = 0; i < 2; ++i)
1311 {
1312 tree op = TREE_OPERAND (expr, i);
1313 if (TREE_CODE (op) != INTEGER_CST)
1314 continue;
1315
1316 /* If one of the operands is a non-negative constant
1317 that fits in the target type, then the type of the
1318 other operand does not matter. */
1319 if (int_fits_type_p (op, c_common_signed_type (type))
1320 && int_fits_type_p (op, c_common_unsigned_type (type)))
1321 return false;
1322
1323 /* If constant is unsigned and fits in the target
1324 type, then the result will also fit. */
1325 if (TYPE_UNSIGNED (TREE_TYPE (op)) && int_fits_type_p (op, type))
1326 return false;
1327 }
1328 /* FALLTHRU */
1329 case BIT_IOR_EXPR:
1330 case BIT_XOR_EXPR:
1331 return (conversion_warning (loc, type, TREE_OPERAND (expr, 0), result)
1332 || conversion_warning (loc, type, TREE_OPERAND (expr, 1),
1333 result));
1334
1335 default_:
1336 default:
1337 conversion_kind = unsafe_conversion_p (type, expr, result, true);
1338 {
1339 int warnopt;
1340 if (conversion_kind == UNSAFE_REAL)
1341 warnopt = OPT_Wfloat_conversion;
1342 else if (conversion_kind == UNSAFE_SIGN)
1343 warnopt = OPT_Wsign_conversion;
1344 else if (conversion_kind)
1345 warnopt = OPT_Wconversion;
1346 else
1347 break;
1348
1349 if (arith_ops
1350 && global_dc->option_enabled (warnopt,
1351 global_dc->lang_mask,
1352 global_dc->option_state))
1353 {
1354 for (int i = 0; i < arith_ops; ++i)
1355 {
1356 tree op = TREE_OPERAND (expr, i);
1357 /* Avoid -Wsign-conversion for (unsigned)(x + (-1)). */
1358 if (TREE_CODE (expr) == PLUS_EXPR && i == 1
1359 && INTEGRAL_TYPE_P (type) && TYPE_UNSIGNED (type)
1360 && TREE_CODE (op) == INTEGER_CST
1361 && tree_int_cst_sgn (op) < 0)
1362 op = fold_build1 (NEGATE_EXPR, TREE_TYPE (op), op);
1363 tree opr = convert (type, op);
1364 if (unsafe_conversion_p (type, op, opr, true))
1365 goto op_unsafe;
1366 }
1367 /* The operands seem safe, we might still want to warn if
1368 -Warith-conversion. */
1369 warnopt = OPT_Warith_conversion;
1370 op_unsafe:;
1371 }
1372
1373 if (conversion_kind == UNSAFE_SIGN)
1374 warning_at (loc, warnopt, "conversion to %qT from %qT "
1375 "may change the sign of the result",
1376 type, expr_type);
1377 else if (conversion_kind == UNSAFE_IMAGINARY)
1378 warning_at (loc, warnopt,
1379 "conversion from %qT to %qT discards imaginary component",
1380 expr_type, type);
1381 else
1382 warning_at (loc, warnopt,
1383 "conversion from %qT to %qT may change value",
1384 expr_type, type);
1385 return true;
1386 }
1387 }
1388 return false;
1389 }
1390
1391 /* Produce warnings after a conversion. RESULT is the result of
1392 converting EXPR to TYPE. This is a helper function for
1393 convert_and_check and cp_convert_and_check. */
1394
1395 void
warnings_for_convert_and_check(location_t loc,tree type,tree expr,tree result)1396 warnings_for_convert_and_check (location_t loc, tree type, tree expr,
1397 tree result)
1398 {
1399 loc = expansion_point_location_if_in_system_header (loc);
1400
1401 while (TREE_CODE (expr) == COMPOUND_EXPR)
1402 expr = TREE_OPERAND (expr, 1);
1403 while (TREE_CODE (result) == COMPOUND_EXPR)
1404 result = TREE_OPERAND (result, 1);
1405
1406 bool cst = TREE_CODE_CLASS (TREE_CODE (result)) == tcc_constant;
1407
1408 tree exprtype = TREE_TYPE (expr);
1409
1410 if (TREE_CODE (expr) == INTEGER_CST
1411 && (TREE_CODE (type) == INTEGER_TYPE
1412 || TREE_CODE (type) == ENUMERAL_TYPE)
1413 && !int_fits_type_p (expr, type))
1414 {
1415 /* Do not diagnose overflow in a constant expression merely
1416 because a conversion overflowed. */
1417 if (TREE_OVERFLOW (result))
1418 TREE_OVERFLOW (result) = TREE_OVERFLOW (expr);
1419
1420 if (TYPE_UNSIGNED (type))
1421 {
1422 /* This detects cases like converting -129 or 256 to
1423 unsigned char. */
1424 if (!int_fits_type_p (expr, c_common_signed_type (type)))
1425 {
1426 if (cst)
1427 warning_at (loc, OPT_Woverflow,
1428 (TYPE_UNSIGNED (exprtype)
1429 ? G_("conversion from %qT to %qT "
1430 "changes value from %qE to %qE")
1431 : G_("unsigned conversion from %qT to %qT "
1432 "changes value from %qE to %qE")),
1433 exprtype, type, expr, result);
1434 else
1435 warning_at (loc, OPT_Woverflow,
1436 (TYPE_UNSIGNED (exprtype)
1437 ? G_("conversion from %qT to %qT "
1438 "changes the value of %qE")
1439 : G_("unsigned conversion from %qT to %qT "
1440 "changes the value of %qE")),
1441 exprtype, type, expr);
1442 }
1443 else
1444 conversion_warning (loc, type, expr, result);
1445 }
1446 else if (!int_fits_type_p (expr, c_common_unsigned_type (type)))
1447 {
1448 if (cst)
1449 warning_at (loc, OPT_Woverflow,
1450 "overflow in conversion from %qT to %qT "
1451 "changes value from %qE to %qE",
1452 exprtype, type, expr, result);
1453 else
1454 warning_at (loc, OPT_Woverflow,
1455 "overflow in conversion from %qT to %qT "
1456 "changes the value of %qE",
1457 exprtype, type, expr);
1458 }
1459 /* No warning for converting 0x80000000 to int. */
1460 else if (pedantic
1461 && (TREE_CODE (exprtype) != INTEGER_TYPE
1462 || TYPE_PRECISION (exprtype)
1463 != TYPE_PRECISION (type)))
1464 {
1465 if (cst)
1466 warning_at (loc, OPT_Woverflow,
1467 "overflow in conversion from %qT to %qT "
1468 "changes value from %qE to %qE",
1469 exprtype, type, expr, result);
1470 else
1471 warning_at (loc, OPT_Woverflow,
1472 "overflow in conversion from %qT to %qT "
1473 "changes the value of %qE",
1474 exprtype, type, expr);
1475 }
1476 else
1477 conversion_warning (loc, type, expr, result);
1478 }
1479 else if ((TREE_CODE (result) == INTEGER_CST
1480 || TREE_CODE (result) == FIXED_CST) && TREE_OVERFLOW (result))
1481 {
1482 if (cst)
1483 warning_at (loc, OPT_Woverflow,
1484 "overflow in conversion from %qT to %qT "
1485 "changes value from %qE to %qE",
1486 exprtype, type, expr, result);
1487 else
1488 warning_at (loc, OPT_Woverflow,
1489 "overflow in conversion from %qT to %qT "
1490 "changes the value of %qE",
1491 exprtype, type, expr);
1492 }
1493 else
1494 conversion_warning (loc, type, expr, result);
1495 }
1496
1497 /* Subroutines of c_do_switch_warnings, called via splay_tree_foreach.
1498 Used to verify that case values match up with enumerator values. */
1499
1500 static void
match_case_to_enum_1(tree key,tree type,tree label)1501 match_case_to_enum_1 (tree key, tree type, tree label)
1502 {
1503 /* Avoid warning about enums that have no enumerators. */
1504 if (TYPE_VALUES (type) == NULL_TREE)
1505 return;
1506
1507 char buf[WIDE_INT_PRINT_BUFFER_SIZE];
1508
1509 if (tree_fits_uhwi_p (key))
1510 print_dec (wi::to_wide (key), buf, UNSIGNED);
1511 else if (tree_fits_shwi_p (key))
1512 print_dec (wi::to_wide (key), buf, SIGNED);
1513 else
1514 print_hex (wi::to_wide (key), buf);
1515
1516 if (TYPE_NAME (type) == NULL_TREE)
1517 warning_at (DECL_SOURCE_LOCATION (CASE_LABEL (label)),
1518 warn_switch ? OPT_Wswitch : OPT_Wswitch_enum,
1519 "case value %qs not in enumerated type",
1520 buf);
1521 else
1522 warning_at (DECL_SOURCE_LOCATION (CASE_LABEL (label)),
1523 warn_switch ? OPT_Wswitch : OPT_Wswitch_enum,
1524 "case value %qs not in enumerated type %qT",
1525 buf, type);
1526 }
1527
1528 /* Subroutine of c_do_switch_warnings, called via splay_tree_foreach.
1529 Used to verify that case values match up with enumerator values. */
1530
1531 static int
match_case_to_enum(splay_tree_node node,void * data)1532 match_case_to_enum (splay_tree_node node, void *data)
1533 {
1534 tree label = (tree) node->value;
1535 tree type = (tree) data;
1536
1537 /* Skip default case. */
1538 if (!CASE_LOW (label))
1539 return 0;
1540
1541 /* If CASE_LOW_SEEN is not set, that means CASE_LOW did not appear
1542 when we did our enum->case scan. Reset our scratch bit after. */
1543 if (!CASE_LOW_SEEN (label))
1544 match_case_to_enum_1 (CASE_LOW (label), type, label);
1545 else
1546 CASE_LOW_SEEN (label) = 0;
1547
1548 /* If CASE_HIGH is non-null, we have a range. If CASE_HIGH_SEEN is
1549 not set, that means that CASE_HIGH did not appear when we did our
1550 enum->case scan. Reset our scratch bit after. */
1551 if (CASE_HIGH (label))
1552 {
1553 if (!CASE_HIGH_SEEN (label))
1554 match_case_to_enum_1 (CASE_HIGH (label), type, label);
1555 else
1556 CASE_HIGH_SEEN (label) = 0;
1557 }
1558
1559 return 0;
1560 }
1561
1562 /* Handle -Wswitch*. Called from the front end after parsing the
1563 switch construct. */
1564 /* ??? Should probably be somewhere generic, since other languages
1565 besides C and C++ would want this. At the moment, however, C/C++
1566 are the only tree-ssa languages that support enumerations at all,
1567 so the point is moot. */
1568
1569 void
c_do_switch_warnings(splay_tree cases,location_t switch_location,tree type,tree cond,bool bool_cond_p)1570 c_do_switch_warnings (splay_tree cases, location_t switch_location,
1571 tree type, tree cond, bool bool_cond_p)
1572 {
1573 splay_tree_node default_node;
1574 splay_tree_node node;
1575 tree chain;
1576 bool outside_range_p = false;
1577
1578 if (type != error_mark_node
1579 && type != TREE_TYPE (cond)
1580 && INTEGRAL_TYPE_P (type)
1581 && INTEGRAL_TYPE_P (TREE_TYPE (cond))
1582 && (!tree_int_cst_equal (TYPE_MIN_VALUE (type),
1583 TYPE_MIN_VALUE (TREE_TYPE (cond)))
1584 || !tree_int_cst_equal (TYPE_MAX_VALUE (type),
1585 TYPE_MAX_VALUE (TREE_TYPE (cond)))))
1586 {
1587 tree min_value = TYPE_MIN_VALUE (type);
1588 tree max_value = TYPE_MAX_VALUE (type);
1589
1590 node = splay_tree_predecessor (cases, (splay_tree_key) min_value);
1591 if (node && node->key)
1592 {
1593 outside_range_p = true;
1594 /* There is at least one case smaller than TYPE's minimum value.
1595 NODE itself could be still a range overlapping the valid values,
1596 but any predecessors thereof except the default case will be
1597 completely outside of range. */
1598 if (CASE_HIGH ((tree) node->value)
1599 && tree_int_cst_compare (CASE_HIGH ((tree) node->value),
1600 min_value) >= 0)
1601 {
1602 location_t loc = EXPR_LOCATION ((tree) node->value);
1603 warning_at (loc, OPT_Wswitch_outside_range,
1604 "lower value in case label range less than minimum"
1605 " value for type");
1606 CASE_LOW ((tree) node->value) = convert (TREE_TYPE (cond),
1607 min_value);
1608 node->key = (splay_tree_key) CASE_LOW ((tree) node->value);
1609 }
1610 /* All the following ones are completely outside of range. */
1611 do
1612 {
1613 node = splay_tree_predecessor (cases,
1614 (splay_tree_key) min_value);
1615 if (node == NULL || !node->key)
1616 break;
1617 location_t loc = EXPR_LOCATION ((tree) node->value);
1618 warning_at (loc, OPT_Wswitch_outside_range, "case label value is"
1619 " less than minimum value for type");
1620 splay_tree_remove (cases, node->key);
1621 }
1622 while (1);
1623 }
1624 node = splay_tree_lookup (cases, (splay_tree_key) max_value);
1625 if (node == NULL)
1626 node = splay_tree_predecessor (cases, (splay_tree_key) max_value);
1627 /* Handle a single node that might partially overlap the range. */
1628 if (node
1629 && node->key
1630 && CASE_HIGH ((tree) node->value)
1631 && tree_int_cst_compare (CASE_HIGH ((tree) node->value),
1632 max_value) > 0)
1633 {
1634 location_t loc = EXPR_LOCATION ((tree) node->value);
1635 warning_at (loc, OPT_Wswitch_outside_range, "upper value in case"
1636 " label range exceeds maximum value for type");
1637 CASE_HIGH ((tree) node->value)
1638 = convert (TREE_TYPE (cond), max_value);
1639 outside_range_p = true;
1640 }
1641 /* And any nodes that are completely outside of the range. */
1642 while ((node = splay_tree_successor (cases,
1643 (splay_tree_key) max_value))
1644 != NULL)
1645 {
1646 location_t loc = EXPR_LOCATION ((tree) node->value);
1647 warning_at (loc, OPT_Wswitch_outside_range,
1648 "case label value exceeds maximum value for type");
1649 splay_tree_remove (cases, node->key);
1650 outside_range_p = true;
1651 }
1652 }
1653
1654 if (!warn_switch && !warn_switch_enum && !warn_switch_default
1655 && !warn_switch_bool)
1656 return;
1657
1658 default_node = splay_tree_lookup (cases, (splay_tree_key) NULL);
1659 if (!default_node)
1660 warning_at (switch_location, OPT_Wswitch_default,
1661 "switch missing default case");
1662
1663 /* There are certain cases where -Wswitch-bool warnings aren't
1664 desirable, such as
1665 switch (boolean)
1666 {
1667 case true: ...
1668 case false: ...
1669 }
1670 so be careful here. */
1671 if (warn_switch_bool && bool_cond_p)
1672 {
1673 splay_tree_node min_node;
1674 /* If there's a default node, it's also the value with the minimal
1675 key. So look at the penultimate key (if any). */
1676 if (default_node)
1677 min_node = splay_tree_successor (cases, (splay_tree_key) NULL);
1678 else
1679 min_node = splay_tree_min (cases);
1680 tree min = min_node ? (tree) min_node->key : NULL_TREE;
1681
1682 splay_tree_node max_node = splay_tree_max (cases);
1683 /* This might be a case range, so look at the value with the
1684 maximal key and then check CASE_HIGH. */
1685 tree max = max_node ? (tree) max_node->value : NULL_TREE;
1686 if (max)
1687 max = CASE_HIGH (max) ? CASE_HIGH (max) : CASE_LOW (max);
1688
1689 /* If there's a case value > 1 or < 0, that is outside bool
1690 range, warn. */
1691 if (outside_range_p
1692 || (max && wi::gts_p (wi::to_wide (max), 1))
1693 || (min && wi::lts_p (wi::to_wide (min), 0))
1694 /* And handle the
1695 switch (boolean)
1696 {
1697 case true: ...
1698 case false: ...
1699 default: ...
1700 }
1701 case, where we want to warn. */
1702 || (default_node
1703 && max && wi::to_wide (max) == 1
1704 && min && wi::to_wide (min) == 0))
1705 warning_at (switch_location, OPT_Wswitch_bool,
1706 "switch condition has boolean value");
1707 }
1708
1709 /* From here on, we only care about enumerated types. */
1710 if (!type || TREE_CODE (type) != ENUMERAL_TYPE)
1711 return;
1712
1713 /* From here on, we only care about -Wswitch and -Wswitch-enum. */
1714 if (!warn_switch_enum && !warn_switch)
1715 return;
1716
1717 /* Check the cases. Warn about case values which are not members of
1718 the enumerated type. For -Wswitch-enum, or for -Wswitch when
1719 there is no default case, check that exactly all enumeration
1720 literals are covered by the cases. */
1721
1722 /* Clearing COND if it is not an integer constant simplifies
1723 the tests inside the loop below. */
1724 if (TREE_CODE (cond) != INTEGER_CST)
1725 cond = NULL_TREE;
1726
1727 /* The time complexity here is O(N*lg(N)) worst case, but for the
1728 common case of monotonically increasing enumerators, it is
1729 O(N), since the nature of the splay tree will keep the next
1730 element adjacent to the root at all times. */
1731
1732 for (chain = TYPE_VALUES (type); chain; chain = TREE_CHAIN (chain))
1733 {
1734 tree value = TREE_VALUE (chain);
1735 if (TREE_CODE (value) == CONST_DECL)
1736 value = DECL_INITIAL (value);
1737 node = splay_tree_lookup (cases, (splay_tree_key) value);
1738 if (node)
1739 {
1740 /* Mark the CASE_LOW part of the case entry as seen. */
1741 tree label = (tree) node->value;
1742 CASE_LOW_SEEN (label) = 1;
1743 continue;
1744 }
1745
1746 /* Even though there wasn't an exact match, there might be a
1747 case range which includes the enumerator's value. */
1748 node = splay_tree_predecessor (cases, (splay_tree_key) value);
1749 if (node && CASE_HIGH ((tree) node->value))
1750 {
1751 tree label = (tree) node->value;
1752 int cmp = tree_int_cst_compare (CASE_HIGH (label), value);
1753 if (cmp >= 0)
1754 {
1755 /* If we match the upper bound exactly, mark the CASE_HIGH
1756 part of the case entry as seen. */
1757 if (cmp == 0)
1758 CASE_HIGH_SEEN (label) = 1;
1759 continue;
1760 }
1761 }
1762
1763 /* We've now determined that this enumerated literal isn't
1764 handled by the case labels of the switch statement. */
1765
1766 /* If the switch expression is a constant, we only really care
1767 about whether that constant is handled by the switch. */
1768 if (cond && tree_int_cst_compare (cond, value))
1769 continue;
1770
1771 /* If the enumerator is defined in a system header and uses a reserved
1772 name, then we continue to avoid throwing a warning. */
1773 location_t loc = DECL_SOURCE_LOCATION
1774 (TYPE_STUB_DECL (TYPE_MAIN_VARIANT (type)));
1775 if (in_system_header_at (loc)
1776 && name_reserved_for_implementation_p
1777 (IDENTIFIER_POINTER (TREE_PURPOSE (chain))))
1778 continue;
1779
1780 /* If there is a default_node, the only relevant option is
1781 Wswitch-enum. Otherwise, if both are enabled then we prefer
1782 to warn using -Wswitch because -Wswitch is enabled by -Wall
1783 while -Wswitch-enum is explicit. */
1784 warning_at (switch_location,
1785 (default_node || !warn_switch
1786 ? OPT_Wswitch_enum
1787 : OPT_Wswitch),
1788 "enumeration value %qE not handled in switch",
1789 TREE_PURPOSE (chain));
1790 }
1791
1792 /* Warn if there are case expressions that don't correspond to
1793 enumerators. This can occur since C and C++ don't enforce
1794 type-checking of assignments to enumeration variables.
1795
1796 The time complexity here is now always O(N) worst case, since
1797 we should have marked both the lower bound and upper bound of
1798 every disjoint case label, with CASE_LOW_SEEN and CASE_HIGH_SEEN
1799 above. This scan also resets those fields. */
1800
1801 splay_tree_foreach (cases, match_case_to_enum, type);
1802 }
1803
1804 /* Warn for A ?: C expressions (with B omitted) where A is a boolean
1805 expression, because B will always be true. */
1806
1807 void
warn_for_omitted_condop(location_t location,tree cond)1808 warn_for_omitted_condop (location_t location, tree cond)
1809 {
1810 /* In C++ template declarations it can happen that the type is dependent
1811 and not yet known, thus TREE_TYPE (cond) == NULL_TREE. */
1812 if (truth_value_p (TREE_CODE (cond))
1813 || (TREE_TYPE (cond) != NULL_TREE
1814 && TREE_CODE (TREE_TYPE (cond)) == BOOLEAN_TYPE))
1815 warning_at (location, OPT_Wparentheses,
1816 "the omitted middle operand in %<?:%> will always be %<true%>, "
1817 "suggest explicit middle operand");
1818 }
1819
1820 /* Give an error for storing into ARG, which is 'const'. USE indicates
1821 how ARG was being used. */
1822
1823 void
readonly_error(location_t loc,tree arg,enum lvalue_use use)1824 readonly_error (location_t loc, tree arg, enum lvalue_use use)
1825 {
1826 gcc_assert (use == lv_assign || use == lv_increment || use == lv_decrement
1827 || use == lv_asm);
1828 STRIP_ANY_LOCATION_WRAPPER (arg);
1829 /* Using this macro rather than (for example) arrays of messages
1830 ensures that all the format strings are checked at compile
1831 time. */
1832 #define READONLY_MSG(A, I, D, AS) (use == lv_assign ? (A) \
1833 : (use == lv_increment ? (I) \
1834 : (use == lv_decrement ? (D) : (AS))))
1835 if (TREE_CODE (arg) == COMPONENT_REF)
1836 {
1837 if (TYPE_READONLY (TREE_TYPE (TREE_OPERAND (arg, 0))))
1838 error_at (loc, READONLY_MSG (G_("assignment of member "
1839 "%qD in read-only object"),
1840 G_("increment of member "
1841 "%qD in read-only object"),
1842 G_("decrement of member "
1843 "%qD in read-only object"),
1844 G_("member %qD in read-only object "
1845 "used as %<asm%> output")),
1846 TREE_OPERAND (arg, 1));
1847 else
1848 error_at (loc, READONLY_MSG (G_("assignment of read-only member %qD"),
1849 G_("increment of read-only member %qD"),
1850 G_("decrement of read-only member %qD"),
1851 G_("read-only member %qD used as %<asm%> output")),
1852 TREE_OPERAND (arg, 1));
1853 }
1854 else if (VAR_P (arg))
1855 error_at (loc, READONLY_MSG (G_("assignment of read-only variable %qD"),
1856 G_("increment of read-only variable %qD"),
1857 G_("decrement of read-only variable %qD"),
1858 G_("read-only variable %qD used as %<asm%> output")),
1859 arg);
1860 else if (TREE_CODE (arg) == PARM_DECL)
1861 error_at (loc, READONLY_MSG (G_("assignment of read-only parameter %qD"),
1862 G_("increment of read-only parameter %qD"),
1863 G_("decrement of read-only parameter %qD"),
1864 G_("read-only parameter %qD use as %<asm%> output")),
1865 arg);
1866 else if (TREE_CODE (arg) == RESULT_DECL)
1867 {
1868 gcc_assert (c_dialect_cxx ());
1869 error_at (loc, READONLY_MSG (G_("assignment of "
1870 "read-only named return value %qD"),
1871 G_("increment of "
1872 "read-only named return value %qD"),
1873 G_("decrement of "
1874 "read-only named return value %qD"),
1875 G_("read-only named return value %qD "
1876 "used as %<asm%>output")),
1877 arg);
1878 }
1879 else if (TREE_CODE (arg) == FUNCTION_DECL)
1880 error_at (loc, READONLY_MSG (G_("assignment of function %qD"),
1881 G_("increment of function %qD"),
1882 G_("decrement of function %qD"),
1883 G_("function %qD used as %<asm%> output")),
1884 arg);
1885 else
1886 error_at (loc, READONLY_MSG (G_("assignment of read-only location %qE"),
1887 G_("increment of read-only location %qE"),
1888 G_("decrement of read-only location %qE"),
1889 G_("read-only location %qE used as %<asm%> output")),
1890 arg);
1891 }
1892
1893 /* Print an error message for an invalid lvalue. USE says
1894 how the lvalue is being used and so selects the error message. LOC
1895 is the location for the error. */
1896
1897 void
lvalue_error(location_t loc,enum lvalue_use use)1898 lvalue_error (location_t loc, enum lvalue_use use)
1899 {
1900 switch (use)
1901 {
1902 case lv_assign:
1903 error_at (loc, "lvalue required as left operand of assignment");
1904 break;
1905 case lv_increment:
1906 error_at (loc, "lvalue required as increment operand");
1907 break;
1908 case lv_decrement:
1909 error_at (loc, "lvalue required as decrement operand");
1910 break;
1911 case lv_addressof:
1912 error_at (loc, "lvalue required as unary %<&%> operand");
1913 break;
1914 case lv_asm:
1915 error_at (loc, "lvalue required in %<asm%> statement");
1916 break;
1917 default:
1918 gcc_unreachable ();
1919 }
1920 }
1921
1922 /* Print an error message for an invalid indirection of type TYPE.
1923 ERRSTRING is the name of the operator for the indirection. */
1924
1925 void
invalid_indirection_error(location_t loc,tree type,ref_operator errstring)1926 invalid_indirection_error (location_t loc, tree type, ref_operator errstring)
1927 {
1928 switch (errstring)
1929 {
1930 case RO_NULL:
1931 gcc_assert (c_dialect_cxx ());
1932 error_at (loc, "invalid type argument (have %qT)", type);
1933 break;
1934 case RO_ARRAY_INDEXING:
1935 error_at (loc,
1936 "invalid type argument of array indexing (have %qT)",
1937 type);
1938 break;
1939 case RO_UNARY_STAR:
1940 error_at (loc,
1941 "invalid type argument of unary %<*%> (have %qT)",
1942 type);
1943 break;
1944 case RO_ARROW:
1945 error_at (loc,
1946 "invalid type argument of %<->%> (have %qT)",
1947 type);
1948 break;
1949 case RO_ARROW_STAR:
1950 error_at (loc,
1951 "invalid type argument of %<->*%> (have %qT)",
1952 type);
1953 break;
1954 case RO_IMPLICIT_CONVERSION:
1955 error_at (loc,
1956 "invalid type argument of implicit conversion (have %qT)",
1957 type);
1958 break;
1959 default:
1960 gcc_unreachable ();
1961 }
1962 }
1963
1964 /* Subscripting with type char is likely to lose on a machine where
1965 chars are signed. So warn on any machine, but optionally. Don't
1966 warn for unsigned char since that type is safe. Don't warn for
1967 signed char because anyone who uses that must have done so
1968 deliberately. Furthermore, we reduce the false positive load by
1969 warning only for non-constant value of type char.
1970 LOC is the location of the subscripting expression. */
1971
1972 void
warn_array_subscript_with_type_char(location_t loc,tree index)1973 warn_array_subscript_with_type_char (location_t loc, tree index)
1974 {
1975 if (TYPE_MAIN_VARIANT (TREE_TYPE (index)) == char_type_node)
1976 {
1977 /* If INDEX has a location, use it; otherwise use LOC (the location
1978 of the subscripting expression as a whole). */
1979 loc = EXPR_LOC_OR_LOC (index, loc);
1980 STRIP_ANY_LOCATION_WRAPPER (index);
1981 if (TREE_CODE (index) != INTEGER_CST)
1982 warning_at (loc, OPT_Wchar_subscripts,
1983 "array subscript has type %<char%>");
1984 }
1985 }
1986
1987 /* Implement -Wparentheses for the unexpected C precedence rules, to
1988 cover cases like x + y << z which readers are likely to
1989 misinterpret. We have seen an expression in which CODE is a binary
1990 operator used to combine expressions ARG_LEFT and ARG_RIGHT, which
1991 before folding had CODE_LEFT and CODE_RIGHT. CODE_LEFT and
1992 CODE_RIGHT may be ERROR_MARK, which means that that side of the
1993 expression was not formed using a binary or unary operator, or it
1994 was enclosed in parentheses. */
1995
1996 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)1997 warn_about_parentheses (location_t loc, enum tree_code code,
1998 enum tree_code code_left, tree arg_left,
1999 enum tree_code code_right, tree arg_right)
2000 {
2001 if (!warn_parentheses)
2002 return;
2003
2004 /* This macro tests that the expression ARG with original tree code
2005 CODE appears to be a boolean expression. or the result of folding a
2006 boolean expression. */
2007 #define APPEARS_TO_BE_BOOLEAN_EXPR_P(CODE, ARG) \
2008 (truth_value_p (TREE_CODE (ARG)) \
2009 || TREE_CODE (TREE_TYPE (ARG)) == BOOLEAN_TYPE \
2010 /* Folding may create 0 or 1 integers from other expressions. */ \
2011 || ((CODE) != INTEGER_CST \
2012 && (integer_onep (ARG) || integer_zerop (ARG))))
2013
2014 switch (code)
2015 {
2016 case LSHIFT_EXPR:
2017 if (code_left == PLUS_EXPR)
2018 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
2019 "suggest parentheses around %<+%> inside %<<<%>");
2020 else if (code_right == PLUS_EXPR)
2021 warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
2022 "suggest parentheses around %<+%> inside %<<<%>");
2023 else if (code_left == MINUS_EXPR)
2024 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
2025 "suggest parentheses around %<-%> inside %<<<%>");
2026 else if (code_right == MINUS_EXPR)
2027 warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
2028 "suggest parentheses around %<-%> inside %<<<%>");
2029 return;
2030
2031 case RSHIFT_EXPR:
2032 if (code_left == PLUS_EXPR)
2033 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
2034 "suggest parentheses around %<+%> inside %<>>%>");
2035 else if (code_right == PLUS_EXPR)
2036 warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
2037 "suggest parentheses around %<+%> inside %<>>%>");
2038 else if (code_left == MINUS_EXPR)
2039 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
2040 "suggest parentheses around %<-%> inside %<>>%>");
2041 else if (code_right == MINUS_EXPR)
2042 warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
2043 "suggest parentheses around %<-%> inside %<>>%>");
2044 return;
2045
2046 case TRUTH_ORIF_EXPR:
2047 if (code_left == TRUTH_ANDIF_EXPR)
2048 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
2049 "suggest parentheses around %<&&%> within %<||%>");
2050 else if (code_right == TRUTH_ANDIF_EXPR)
2051 warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
2052 "suggest parentheses around %<&&%> within %<||%>");
2053 return;
2054
2055 case BIT_IOR_EXPR:
2056 if (code_left == BIT_AND_EXPR || code_left == BIT_XOR_EXPR
2057 || code_left == PLUS_EXPR || code_left == MINUS_EXPR)
2058 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
2059 "suggest parentheses around arithmetic in operand of %<|%>");
2060 else if (code_right == BIT_AND_EXPR || code_right == BIT_XOR_EXPR
2061 || code_right == PLUS_EXPR || code_right == MINUS_EXPR)
2062 warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
2063 "suggest parentheses around arithmetic in operand of %<|%>");
2064 /* Check cases like x|y==z */
2065 else if (TREE_CODE_CLASS (code_left) == tcc_comparison)
2066 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
2067 "suggest parentheses around comparison in operand of %<|%>");
2068 else if (TREE_CODE_CLASS (code_right) == tcc_comparison)
2069 warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
2070 "suggest parentheses around comparison in operand of %<|%>");
2071 /* Check cases like !x | y */
2072 else if (code_left == TRUTH_NOT_EXPR
2073 && !APPEARS_TO_BE_BOOLEAN_EXPR_P (code_right, arg_right))
2074 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
2075 "suggest parentheses around operand of "
2076 "%<!%> or change %<|%> to %<||%> or %<!%> to %<~%>");
2077 return;
2078
2079 case BIT_XOR_EXPR:
2080 if (code_left == BIT_AND_EXPR
2081 || code_left == PLUS_EXPR || code_left == MINUS_EXPR)
2082 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
2083 "suggest parentheses around arithmetic in operand of %<^%>");
2084 else if (code_right == BIT_AND_EXPR
2085 || code_right == PLUS_EXPR || code_right == MINUS_EXPR)
2086 warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
2087 "suggest parentheses around arithmetic in operand of %<^%>");
2088 /* Check cases like x^y==z */
2089 else if (TREE_CODE_CLASS (code_left) == tcc_comparison)
2090 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
2091 "suggest parentheses around comparison in operand of %<^%>");
2092 else if (TREE_CODE_CLASS (code_right) == tcc_comparison)
2093 warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
2094 "suggest parentheses around comparison in operand of %<^%>");
2095 return;
2096
2097 case BIT_AND_EXPR:
2098 if (code_left == PLUS_EXPR)
2099 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
2100 "suggest parentheses around %<+%> in operand of %<&%>");
2101 else if (code_right == PLUS_EXPR)
2102 warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
2103 "suggest parentheses around %<+%> in operand of %<&%>");
2104 else if (code_left == MINUS_EXPR)
2105 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
2106 "suggest parentheses around %<-%> in operand of %<&%>");
2107 else if (code_right == MINUS_EXPR)
2108 warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
2109 "suggest parentheses around %<-%> in operand of %<&%>");
2110 /* Check cases like x&y==z */
2111 else if (TREE_CODE_CLASS (code_left) == tcc_comparison)
2112 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
2113 "suggest parentheses around comparison in operand of %<&%>");
2114 else if (TREE_CODE_CLASS (code_right) == tcc_comparison)
2115 warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
2116 "suggest parentheses around comparison in operand of %<&%>");
2117 /* Check cases like !x & y */
2118 else if (code_left == TRUTH_NOT_EXPR
2119 && !APPEARS_TO_BE_BOOLEAN_EXPR_P (code_right, arg_right))
2120 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
2121 "suggest parentheses around operand of "
2122 "%<!%> or change %<&%> to %<&&%> or %<!%> to %<~%>");
2123 return;
2124
2125 case EQ_EXPR:
2126 if (TREE_CODE_CLASS (code_left) == tcc_comparison)
2127 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
2128 "suggest parentheses around comparison in operand of %<==%>");
2129 else if (TREE_CODE_CLASS (code_right) == tcc_comparison)
2130 warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
2131 "suggest parentheses around comparison in operand of %<==%>");
2132 return;
2133 case NE_EXPR:
2134 if (TREE_CODE_CLASS (code_left) == tcc_comparison)
2135 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
2136 "suggest parentheses around comparison in operand of %<!=%>");
2137 else if (TREE_CODE_CLASS (code_right) == tcc_comparison)
2138 warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
2139 "suggest parentheses around comparison in operand of %<!=%>");
2140 return;
2141
2142 default:
2143 if (TREE_CODE_CLASS (code) == tcc_comparison)
2144 {
2145 if (TREE_CODE_CLASS (code_left) == tcc_comparison
2146 && code_left != NE_EXPR && code_left != EQ_EXPR
2147 && INTEGRAL_TYPE_P (TREE_TYPE (arg_left)))
2148 warning_at (EXPR_LOC_OR_LOC (arg_left, loc), OPT_Wparentheses,
2149 "comparisons like %<X<=Y<=Z%> do not "
2150 "have their mathematical meaning");
2151 else if (TREE_CODE_CLASS (code_right) == tcc_comparison
2152 && code_right != NE_EXPR && code_right != EQ_EXPR
2153 && INTEGRAL_TYPE_P (TREE_TYPE (arg_right)))
2154 warning_at (EXPR_LOC_OR_LOC (arg_right, loc), OPT_Wparentheses,
2155 "comparisons like %<X<=Y<=Z%> do not "
2156 "have their mathematical meaning");
2157 }
2158 return;
2159 }
2160 #undef NOT_A_BOOLEAN_EXPR_P
2161 }
2162
2163 /* If LABEL (a LABEL_DECL) has not been used, issue a warning. */
2164
2165 void
warn_for_unused_label(tree label)2166 warn_for_unused_label (tree label)
2167 {
2168 if (!TREE_USED (label))
2169 {
2170 if (DECL_INITIAL (label))
2171 warning (OPT_Wunused_label, "label %q+D defined but not used", label);
2172 else
2173 warning (OPT_Wunused_label, "label %q+D declared but not defined", label);
2174 }
2175 else if (asan_sanitize_use_after_scope ())
2176 {
2177 if (asan_used_labels == NULL)
2178 asan_used_labels = new hash_set<tree> (16);
2179
2180 asan_used_labels->add (label);
2181 }
2182 }
2183
2184 /* Warn for division by zero according to the value of DIVISOR. LOC
2185 is the location of the division operator. */
2186
2187 void
warn_for_div_by_zero(location_t loc,tree divisor)2188 warn_for_div_by_zero (location_t loc, tree divisor)
2189 {
2190 /* If DIVISOR is zero, and has integral or fixed-point type, issue a warning
2191 about division by zero. Do not issue a warning if DIVISOR has a
2192 floating-point type, since we consider 0.0/0.0 a valid way of
2193 generating a NaN. */
2194 if (c_inhibit_evaluation_warnings == 0
2195 && (integer_zerop (divisor) || fixed_zerop (divisor)))
2196 warning_at (loc, OPT_Wdiv_by_zero, "division by zero");
2197 }
2198
2199 /* Warn for patterns where memset appears to be used incorrectly. The
2200 warning location should be LOC. ARG0, and ARG2 are the first and
2201 last arguments to the call, while LITERAL_ZERO_MASK has a 1 bit for
2202 each argument that was a literal zero. */
2203
2204 void
warn_for_memset(location_t loc,tree arg0,tree arg2,int literal_zero_mask)2205 warn_for_memset (location_t loc, tree arg0, tree arg2,
2206 int literal_zero_mask)
2207 {
2208 arg0 = fold_for_warn (arg0);
2209 arg2 = fold_for_warn (arg2);
2210
2211 if (warn_memset_transposed_args
2212 && integer_zerop (arg2)
2213 && (literal_zero_mask & (1 << 2)) != 0
2214 && (literal_zero_mask & (1 << 1)) == 0)
2215 warning_at (loc, OPT_Wmemset_transposed_args,
2216 "%<memset%> used with constant zero length "
2217 "parameter; this could be due to transposed "
2218 "parameters");
2219
2220 if (warn_memset_elt_size && TREE_CODE (arg2) == INTEGER_CST)
2221 {
2222 STRIP_NOPS (arg0);
2223 if (TREE_CODE (arg0) == ADDR_EXPR)
2224 arg0 = TREE_OPERAND (arg0, 0);
2225 tree type = TREE_TYPE (arg0);
2226 if (type != NULL_TREE && TREE_CODE (type) == ARRAY_TYPE)
2227 {
2228 tree elt_type = TREE_TYPE (type);
2229 tree domain = TYPE_DOMAIN (type);
2230 if (COMPLETE_TYPE_P (elt_type)
2231 && !integer_onep (TYPE_SIZE_UNIT (elt_type))
2232 && domain != NULL_TREE
2233 && TYPE_MAX_VALUE (domain)
2234 && TYPE_MIN_VALUE (domain)
2235 && integer_zerop (TYPE_MIN_VALUE (domain))
2236 && integer_onep (fold_build2 (MINUS_EXPR, domain,
2237 arg2,
2238 TYPE_MAX_VALUE (domain))))
2239 warning_at (loc, OPT_Wmemset_elt_size,
2240 "%<memset%> used with length equal to "
2241 "number of elements without multiplication "
2242 "by element size");
2243 }
2244 }
2245 }
2246
2247 /* Subroutine of build_binary_op. Give warnings for comparisons
2248 between signed and unsigned quantities that may fail. Do the
2249 checking based on the original operand trees ORIG_OP0 and ORIG_OP1,
2250 so that casts will be considered, but default promotions won't
2251 be.
2252
2253 LOCATION is the location of the comparison operator.
2254
2255 The arguments of this function map directly to local variables
2256 of build_binary_op. */
2257
2258 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)2259 warn_for_sign_compare (location_t location,
2260 tree orig_op0, tree orig_op1,
2261 tree op0, tree op1,
2262 tree result_type, enum tree_code resultcode)
2263 {
2264 if (error_operand_p (orig_op0) || error_operand_p (orig_op1))
2265 return;
2266
2267 int op0_signed = !TYPE_UNSIGNED (TREE_TYPE (orig_op0));
2268 int op1_signed = !TYPE_UNSIGNED (TREE_TYPE (orig_op1));
2269 int unsignedp0, unsignedp1;
2270
2271 /* Do not warn if the comparison is being done in a signed type,
2272 since the signed type will only be chosen if it can represent
2273 all the values of the unsigned type. */
2274 if (!TYPE_UNSIGNED (result_type))
2275 /* OK */;
2276 /* Do not warn if both operands are unsigned. */
2277 else if (op0_signed == op1_signed)
2278 /* OK */;
2279 else
2280 {
2281 tree sop, uop, base_type;
2282 bool ovf;
2283
2284 if (op0_signed)
2285 sop = orig_op0, uop = orig_op1;
2286 else
2287 sop = orig_op1, uop = orig_op0;
2288
2289 sop = fold_for_warn (sop);
2290 uop = fold_for_warn (uop);
2291
2292 STRIP_TYPE_NOPS (sop);
2293 STRIP_TYPE_NOPS (uop);
2294 base_type = (TREE_CODE (result_type) == COMPLEX_TYPE
2295 ? TREE_TYPE (result_type) : result_type);
2296
2297 /* Do not warn if the signed quantity is an unsuffixed integer
2298 literal (or some static constant expression involving such
2299 literals or a conditional expression involving such literals)
2300 and it is non-negative. */
2301 if (tree_expr_nonnegative_warnv_p (sop, &ovf))
2302 /* OK */;
2303 /* Do not warn if the comparison is an equality operation, the
2304 unsigned quantity is an integral constant, and it would fit
2305 in the result if the result were signed. */
2306 else if (TREE_CODE (uop) == INTEGER_CST
2307 && (resultcode == EQ_EXPR || resultcode == NE_EXPR)
2308 && int_fits_type_p (uop, c_common_signed_type (base_type)))
2309 /* OK */;
2310 /* In C, do not warn if the unsigned quantity is an enumeration
2311 constant and its maximum value would fit in the result if the
2312 result were signed. */
2313 else if (!c_dialect_cxx() && TREE_CODE (uop) == INTEGER_CST
2314 && TREE_CODE (TREE_TYPE (uop)) == ENUMERAL_TYPE
2315 && int_fits_type_p (TYPE_MAX_VALUE (TREE_TYPE (uop)),
2316 c_common_signed_type (base_type)))
2317 /* OK */;
2318 else
2319 warning_at (location, OPT_Wsign_compare,
2320 "comparison of integer expressions of different "
2321 "signedness: %qT and %qT", TREE_TYPE (orig_op0),
2322 TREE_TYPE (orig_op1));
2323 }
2324
2325 /* Warn if two unsigned values are being compared in a size larger
2326 than their original size, and one (and only one) is the result of
2327 a `~' operator. This comparison will always fail.
2328
2329 Also warn if one operand is a constant, and the constant does not
2330 have all bits set that are set in the ~ operand when it is
2331 extended. */
2332
2333 /* bits0 is the bit index of op0 extended to result_type, which will
2334 be always 0 and so all bits above it. If there is a BIT_NOT_EXPR
2335 in that operand possibly sign or zero extended to op0 and then
2336 possibly further sign or zero extended to result_type, bits0 will
2337 be the precision of result type if all the extensions involved
2338 if any are sign extensions, and will be the place of the innermost
2339 zero extension otherwise. We warn only if BIT_NOT_EXPR's operand is
2340 zero extended from some even smaller precision, in that case after
2341 BIT_NOT_EXPR some bits below bits0 will be guaranteed to be set.
2342 Similarly for bits1. */
2343 int bits0 = TYPE_PRECISION (result_type);
2344 if (TYPE_UNSIGNED (TREE_TYPE (op0)))
2345 bits0 = TYPE_PRECISION (TREE_TYPE (op0));
2346 tree arg0 = c_common_get_narrower (op0, &unsignedp0);
2347 if (TYPE_PRECISION (TREE_TYPE (arg0)) == TYPE_PRECISION (TREE_TYPE (op0)))
2348 unsignedp0 = TYPE_UNSIGNED (TREE_TYPE (op0));
2349 else if (unsignedp0)
2350 bits0 = TYPE_PRECISION (TREE_TYPE (arg0));
2351 op0 = arg0;
2352 int bits1 = TYPE_PRECISION (result_type);
2353 if (TYPE_UNSIGNED (TREE_TYPE (op1)))
2354 bits1 = TYPE_PRECISION (TREE_TYPE (op1));
2355 tree arg1 = c_common_get_narrower (op1, &unsignedp1);
2356 if (TYPE_PRECISION (TREE_TYPE (arg1)) == TYPE_PRECISION (TREE_TYPE (op1)))
2357 unsignedp1 = TYPE_UNSIGNED (TREE_TYPE (op1));
2358 else if (unsignedp1)
2359 bits1 = TYPE_PRECISION (TREE_TYPE (arg1));
2360 op1 = arg1;
2361
2362 if ((TREE_CODE (op0) == BIT_NOT_EXPR)
2363 ^ (TREE_CODE (op1) == BIT_NOT_EXPR))
2364 {
2365 if (TREE_CODE (op1) == BIT_NOT_EXPR)
2366 {
2367 std::swap (op0, op1);
2368 std::swap (unsignedp0, unsignedp1);
2369 std::swap (bits0, bits1);
2370 }
2371
2372 int unsignedp;
2373 arg0 = c_common_get_narrower (TREE_OPERAND (op0, 0), &unsignedp);
2374
2375 /* For these warnings, we need BIT_NOT_EXPR operand to be
2376 zero extended from narrower type to BIT_NOT_EXPR's type.
2377 In that case, all those bits above the narrower's type
2378 are after BIT_NOT_EXPR set to 1. */
2379 if (tree_fits_shwi_p (op1))
2380 {
2381 HOST_WIDE_INT constant = tree_to_shwi (op1);
2382 unsigned int bits = TYPE_PRECISION (TREE_TYPE (arg0));
2383 if (unsignedp
2384 && bits < TYPE_PRECISION (TREE_TYPE (op0))
2385 && bits < HOST_BITS_PER_WIDE_INT)
2386 {
2387 HOST_WIDE_INT mask = HOST_WIDE_INT_M1U << bits;
2388 if (bits0 < HOST_BITS_PER_WIDE_INT)
2389 mask &= ~(HOST_WIDE_INT_M1U << bits0);
2390 if ((mask & constant) != mask)
2391 {
2392 if (constant == 0)
2393 warning_at (location, OPT_Wsign_compare,
2394 "promoted bitwise complement of an unsigned "
2395 "value is always nonzero");
2396 else
2397 warning_at (location, OPT_Wsign_compare,
2398 "comparison of promoted bitwise complement "
2399 "of an unsigned value with constant");
2400 }
2401 }
2402 }
2403 else if ((TYPE_PRECISION (TREE_TYPE (arg0))
2404 < TYPE_PRECISION (TREE_TYPE (op0)))
2405 && unsignedp
2406 && unsignedp1
2407 && TYPE_PRECISION (TREE_TYPE (op1)) < bits0)
2408 warning_at (location, OPT_Wsign_compare,
2409 "comparison of promoted bitwise complement "
2410 "of an unsigned value with unsigned");
2411 }
2412 }
2413
2414 /* RESULT_TYPE is the result of converting TYPE1 and TYPE2 to a common
2415 type via c_common_type. If -Wdouble-promotion is in use, and the
2416 conditions for warning have been met, issue a warning. GMSGID is
2417 the warning message. It must have two %T specifiers for the type
2418 that was converted (generally "float") and the type to which it was
2419 converted (generally "double), respectively. LOC is the location
2420 to which the warning should refer. */
2421
2422 void
do_warn_double_promotion(tree result_type,tree type1,tree type2,const char * gmsgid,location_t loc)2423 do_warn_double_promotion (tree result_type, tree type1, tree type2,
2424 const char *gmsgid, location_t loc)
2425 {
2426 tree source_type;
2427
2428 if (!warn_double_promotion)
2429 return;
2430 /* If the conversion will not occur at run-time, there is no need to
2431 warn about it. */
2432 if (c_inhibit_evaluation_warnings)
2433 return;
2434 /* If an invalid conversion has occurred, don't warn. */
2435 if (result_type == error_mark_node)
2436 return;
2437 if (TYPE_MAIN_VARIANT (result_type) != double_type_node
2438 && TYPE_MAIN_VARIANT (result_type) != complex_double_type_node)
2439 return;
2440 if (TYPE_MAIN_VARIANT (type1) == float_type_node
2441 || TYPE_MAIN_VARIANT (type1) == complex_float_type_node)
2442 source_type = type1;
2443 else if (TYPE_MAIN_VARIANT (type2) == float_type_node
2444 || TYPE_MAIN_VARIANT (type2) == complex_float_type_node)
2445 source_type = type2;
2446 else
2447 return;
2448 warning_at (loc, OPT_Wdouble_promotion, gmsgid, source_type, result_type);
2449 }
2450
2451 /* Possibly warn about unused parameters. */
2452
2453 void
do_warn_unused_parameter(tree fn)2454 do_warn_unused_parameter (tree fn)
2455 {
2456 tree decl;
2457
2458 for (decl = DECL_ARGUMENTS (fn);
2459 decl; decl = DECL_CHAIN (decl))
2460 if (!TREE_USED (decl) && TREE_CODE (decl) == PARM_DECL
2461 && DECL_NAME (decl) && !DECL_ARTIFICIAL (decl)
2462 && !warning_suppressed_p (decl, OPT_Wunused_parameter))
2463 warning_at (DECL_SOURCE_LOCATION (decl), OPT_Wunused_parameter,
2464 "unused parameter %qD", decl);
2465 }
2466
2467 /* If DECL is a typedef that is declared in the current function,
2468 record it for the purpose of -Wunused-local-typedefs. */
2469
2470 void
record_locally_defined_typedef(tree decl)2471 record_locally_defined_typedef (tree decl)
2472 {
2473 struct c_language_function *l;
2474
2475 if (!warn_unused_local_typedefs
2476 || cfun == NULL
2477 /* if this is not a locally defined typedef then we are not
2478 interested. */
2479 || !is_typedef_decl (decl)
2480 || !decl_function_context (decl))
2481 return;
2482
2483 l = (struct c_language_function *) cfun->language;
2484 vec_safe_push (l->local_typedefs, decl);
2485 }
2486
2487 /* If T is a TYPE_DECL declared locally, mark it as used. */
2488
2489 void
maybe_record_typedef_use(tree t)2490 maybe_record_typedef_use (tree t)
2491 {
2492 if (!is_typedef_decl (t))
2493 return;
2494
2495 TREE_USED (t) = true;
2496 }
2497
2498 /* Warn if there are some unused locally defined typedefs in the
2499 current function. */
2500
2501 void
maybe_warn_unused_local_typedefs(void)2502 maybe_warn_unused_local_typedefs (void)
2503 {
2504 int i;
2505 tree decl;
2506 /* The number of times we have emitted -Wunused-local-typedefs
2507 warnings. If this is different from errorcount, that means some
2508 unrelated errors have been issued. In which case, we'll avoid
2509 emitting "unused-local-typedefs" warnings. */
2510 static int unused_local_typedefs_warn_count;
2511 struct c_language_function *l;
2512
2513 if (cfun == NULL)
2514 return;
2515
2516 if ((l = (struct c_language_function *) cfun->language) == NULL)
2517 return;
2518
2519 if (warn_unused_local_typedefs
2520 && errorcount == unused_local_typedefs_warn_count)
2521 {
2522 FOR_EACH_VEC_SAFE_ELT (l->local_typedefs, i, decl)
2523 if (!TREE_USED (decl))
2524 warning_at (DECL_SOURCE_LOCATION (decl),
2525 OPT_Wunused_local_typedefs,
2526 "typedef %qD locally defined but not used", decl);
2527 unused_local_typedefs_warn_count = errorcount;
2528 }
2529
2530 vec_free (l->local_typedefs);
2531 }
2532
2533 /* If we're creating an if-else-if condition chain, first see if we
2534 already have this COND in the CHAIN. If so, warn and don't add COND
2535 into the vector, otherwise add the COND there. LOC is the location
2536 of COND. */
2537
2538 void
warn_duplicated_cond_add_or_warn(location_t loc,tree cond,vec<tree> ** chain)2539 warn_duplicated_cond_add_or_warn (location_t loc, tree cond, vec<tree> **chain)
2540 {
2541 /* No chain has been created yet. Do nothing. */
2542 if (*chain == NULL)
2543 return;
2544
2545 if (TREE_SIDE_EFFECTS (cond) || instantiation_dependent_expression_p (cond))
2546 {
2547 /* Uh-oh! This condition has a side-effect, thus invalidates
2548 the whole chain. */
2549 delete *chain;
2550 *chain = NULL;
2551 return;
2552 }
2553
2554 unsigned int ix;
2555 tree t;
2556 bool found = false;
2557 FOR_EACH_VEC_ELT (**chain, ix, t)
2558 if (operand_equal_p (cond, t, 0))
2559 {
2560 auto_diagnostic_group d;
2561 if (warning_at (loc, OPT_Wduplicated_cond,
2562 "duplicated %<if%> condition"))
2563 inform (EXPR_LOCATION (t), "previously used here");
2564 found = true;
2565 break;
2566 }
2567
2568 if (!found
2569 && !CONSTANT_CLASS_P (cond)
2570 /* Don't infinitely grow the chain. */
2571 && (*chain)->length () < 512)
2572 (*chain)->safe_push (cond);
2573 }
2574
2575 /* Check and possibly warn if two declarations have contradictory
2576 attributes, such as always_inline vs. noinline. */
2577
2578 bool
diagnose_mismatched_attributes(tree olddecl,tree newdecl)2579 diagnose_mismatched_attributes (tree olddecl, tree newdecl)
2580 {
2581 bool warned = false;
2582
2583 tree a1 = lookup_attribute ("optimize", DECL_ATTRIBUTES (olddecl));
2584 tree a2 = lookup_attribute ("optimize", DECL_ATTRIBUTES (newdecl));
2585 /* An optimization attribute applied on a declaration after the
2586 definition is likely not what the user wanted. */
2587 if (a2 != NULL_TREE
2588 && DECL_SAVED_TREE (olddecl) != NULL_TREE
2589 && (a1 == NULL_TREE || !attribute_list_equal (a1, a2)))
2590 warned |= warning (OPT_Wattributes,
2591 "optimization attribute on %qD follows "
2592 "definition but the attribute doesn%'t match",
2593 newdecl);
2594
2595 /* Diagnose inline __attribute__ ((noinline)) which is silly. */
2596 if (DECL_DECLARED_INLINE_P (newdecl)
2597 && DECL_UNINLINABLE (olddecl)
2598 && lookup_attribute ("noinline", DECL_ATTRIBUTES (olddecl)))
2599 warned |= warning (OPT_Wattributes, "inline declaration of %qD follows "
2600 "declaration with attribute %<noinline%>", newdecl);
2601 else if (DECL_DECLARED_INLINE_P (olddecl)
2602 && DECL_UNINLINABLE (newdecl)
2603 && lookup_attribute ("noinline", DECL_ATTRIBUTES (newdecl)))
2604 warned |= warning (OPT_Wattributes, "declaration of %q+D with attribute "
2605 "%<noinline%> follows inline declaration", newdecl);
2606
2607 return warned;
2608 }
2609
2610 /* Warn if signed left shift overflows. We don't warn
2611 about left-shifting 1 into the sign bit in C++14; cf.
2612 <http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3367.html#1457>
2613 and don't warn for C++20 at all, as signed left shifts never
2614 overflow.
2615 LOC is a location of the shift; OP0 and OP1 are the operands.
2616 Return true if an overflow is detected, false otherwise. */
2617
2618 bool
maybe_warn_shift_overflow(location_t loc,tree op0,tree op1)2619 maybe_warn_shift_overflow (location_t loc, tree op0, tree op1)
2620 {
2621 if (TREE_CODE (op0) != INTEGER_CST
2622 || TREE_CODE (op1) != INTEGER_CST)
2623 return false;
2624
2625 tree type0 = TREE_TYPE (op0);
2626 unsigned int prec0 = TYPE_PRECISION (type0);
2627
2628 /* Left-hand operand must be signed. */
2629 if (TYPE_OVERFLOW_WRAPS (type0) || cxx_dialect >= cxx20)
2630 return false;
2631
2632 unsigned int min_prec = (wi::min_precision (wi::to_wide (op0), SIGNED)
2633 + TREE_INT_CST_LOW (op1));
2634 /* Handle the case of left-shifting 1 into the sign bit.
2635 * However, shifting 1 _out_ of the sign bit, as in
2636 * INT_MIN << 1, is considered an overflow.
2637 */
2638 if (!tree_int_cst_sign_bit (op0) && min_prec == prec0 + 1)
2639 {
2640 /* Never warn for C++14 onwards. */
2641 if (cxx_dialect >= cxx14)
2642 return false;
2643 /* Otherwise only if -Wshift-overflow=2. But return
2644 true to signal an overflow for the sake of integer
2645 constant expressions. */
2646 if (warn_shift_overflow < 2)
2647 return true;
2648 }
2649
2650 bool overflowed = min_prec > prec0;
2651 if (overflowed && c_inhibit_evaluation_warnings == 0)
2652 warning_at (loc, OPT_Wshift_overflow_,
2653 "result of %qE requires %u bits to represent, "
2654 "but %qT only has %u bits",
2655 build2_loc (loc, LSHIFT_EXPR, type0, op0, op1),
2656 min_prec, type0, prec0);
2657
2658 return overflowed;
2659 }
2660
2661 /* Warn about boolean expression compared with an integer value different
2662 from true/false. Warns also e.g. about "(i1 == i2) == 2".
2663 LOC is the location of the comparison, CODE is its code, OP0 and OP1
2664 are the operands of the comparison. The caller must ensure that
2665 either operand is a boolean expression. */
2666
2667 void
maybe_warn_bool_compare(location_t loc,enum tree_code code,tree op0,tree op1)2668 maybe_warn_bool_compare (location_t loc, enum tree_code code, tree op0,
2669 tree op1)
2670 {
2671 if (TREE_CODE_CLASS (code) != tcc_comparison)
2672 return;
2673
2674 tree f, cst;
2675 if (f = fold_for_warn (op0),
2676 TREE_CODE (f) == INTEGER_CST)
2677 cst = op0 = f;
2678 else if (f = fold_for_warn (op1),
2679 TREE_CODE (f) == INTEGER_CST)
2680 cst = op1 = f;
2681 else
2682 return;
2683
2684 if (!integer_zerop (cst) && !integer_onep (cst))
2685 {
2686 int sign = (TREE_CODE (op0) == INTEGER_CST
2687 ? tree_int_cst_sgn (cst) : -tree_int_cst_sgn (cst));
2688 if (code == EQ_EXPR
2689 || ((code == GT_EXPR || code == GE_EXPR) && sign < 0)
2690 || ((code == LT_EXPR || code == LE_EXPR) && sign > 0))
2691 warning_at (loc, OPT_Wbool_compare, "comparison of constant %qE "
2692 "with boolean expression is always false", cst);
2693 else
2694 warning_at (loc, OPT_Wbool_compare, "comparison of constant %qE "
2695 "with boolean expression is always true", cst);
2696 }
2697 else if (integer_zerop (cst) || integer_onep (cst))
2698 {
2699 /* If the non-constant operand isn't of a boolean type, we
2700 don't want to warn here. */
2701 tree noncst = TREE_CODE (op0) == INTEGER_CST ? op1 : op0;
2702 /* Handle booleans promoted to integers. */
2703 if (bool_promoted_to_int_p (noncst))
2704 /* Warn. */;
2705 else if (TREE_CODE (TREE_TYPE (noncst)) != BOOLEAN_TYPE
2706 && !truth_value_p (TREE_CODE (noncst)))
2707 return;
2708 /* Do some magic to get the right diagnostics. */
2709 bool flag = TREE_CODE (op0) == INTEGER_CST;
2710 flag = integer_zerop (cst) ? flag : !flag;
2711 if ((code == GE_EXPR && !flag) || (code == LE_EXPR && flag))
2712 warning_at (loc, OPT_Wbool_compare, "comparison of constant %qE "
2713 "with boolean expression is always true", cst);
2714 else if ((code == LT_EXPR && !flag) || (code == GT_EXPR && flag))
2715 warning_at (loc, OPT_Wbool_compare, "comparison of constant %qE "
2716 "with boolean expression is always false", cst);
2717 }
2718 }
2719
2720 /* Warn if an argument at position param_pos is passed to a
2721 restrict-qualified param, and it aliases with another argument.
2722 Return true if a warning has been issued. */
2723
2724 bool
warn_for_restrict(unsigned param_pos,tree * argarray,unsigned nargs)2725 warn_for_restrict (unsigned param_pos, tree *argarray, unsigned nargs)
2726 {
2727 tree arg = argarray[param_pos];
2728 if (TREE_VISITED (arg) || integer_zerop (arg))
2729 return false;
2730
2731 location_t loc = EXPR_LOC_OR_LOC (arg, input_location);
2732 gcc_rich_location richloc (loc);
2733
2734 unsigned i;
2735 auto_vec<int, 16> arg_positions;
2736
2737 for (i = 0; i < nargs; i++)
2738 {
2739 if (i == param_pos)
2740 continue;
2741
2742 tree current_arg = argarray[i];
2743 if (operand_equal_p (arg, current_arg, 0))
2744 {
2745 TREE_VISITED (current_arg) = 1;
2746 arg_positions.safe_push (i + 1);
2747 }
2748 }
2749
2750 if (arg_positions.is_empty ())
2751 return false;
2752
2753 int pos;
2754 FOR_EACH_VEC_ELT (arg_positions, i, pos)
2755 {
2756 arg = argarray[pos - 1];
2757 if (EXPR_HAS_LOCATION (arg))
2758 richloc.add_range (EXPR_LOCATION (arg));
2759 }
2760
2761 return warning_n (&richloc, OPT_Wrestrict, arg_positions.length (),
2762 "passing argument %i to %qs-qualified parameter"
2763 " aliases with argument %Z",
2764 "passing argument %i to %qs-qualified parameter"
2765 " aliases with arguments %Z",
2766 param_pos + 1, "restrict", arg_positions.address (),
2767 arg_positions.length ());
2768 }
2769
2770 /* Callback function to determine whether an expression TP or one of its
2771 subexpressions comes from macro expansion. Used to suppress bogus
2772 warnings. */
2773
2774 static tree
expr_from_macro_expansion_r(tree * tp,int *,void *)2775 expr_from_macro_expansion_r (tree *tp, int *, void *)
2776 {
2777 if (CAN_HAVE_LOCATION_P (*tp)
2778 && from_macro_expansion_at (EXPR_LOCATION (*tp)))
2779 return integer_zero_node;
2780
2781 return NULL_TREE;
2782 }
2783
2784 /* Possibly warn when an if-else has identical branches. */
2785
2786 static void
do_warn_duplicated_branches(tree expr)2787 do_warn_duplicated_branches (tree expr)
2788 {
2789 tree thenb = COND_EXPR_THEN (expr);
2790 tree elseb = COND_EXPR_ELSE (expr);
2791
2792 /* Don't bother if any of the branches is missing. */
2793 if (thenb == NULL_TREE || elseb == NULL_TREE)
2794 return;
2795
2796 /* And don't warn for empty statements. */
2797 if (TREE_CODE (thenb) == NOP_EXPR
2798 && TREE_TYPE (thenb) == void_type_node
2799 && TREE_OPERAND (thenb, 0) == size_zero_node)
2800 return;
2801
2802 /* ... or empty branches. */
2803 if (TREE_CODE (thenb) == STATEMENT_LIST
2804 && STATEMENT_LIST_HEAD (thenb) == NULL)
2805 return;
2806
2807 /* Compute the hash of the then branch. */
2808 inchash::hash hstate0 (0);
2809 inchash::add_expr (thenb, hstate0);
2810 hashval_t h0 = hstate0.end ();
2811
2812 /* Compute the hash of the else branch. */
2813 inchash::hash hstate1 (0);
2814 inchash::add_expr (elseb, hstate1);
2815 hashval_t h1 = hstate1.end ();
2816
2817 /* Compare the hashes. */
2818 if (h0 == h1
2819 && operand_equal_p (thenb, elseb, OEP_LEXICOGRAPHIC
2820 | OEP_ADDRESS_OF_SAME_FIELD)
2821 /* Don't warn if any of the branches or their subexpressions comes
2822 from a macro. */
2823 && !walk_tree_without_duplicates (&thenb, expr_from_macro_expansion_r,
2824 NULL)
2825 && !walk_tree_without_duplicates (&elseb, expr_from_macro_expansion_r,
2826 NULL))
2827 warning_at (EXPR_LOCATION (expr), OPT_Wduplicated_branches,
2828 "this condition has identical branches");
2829 }
2830
2831 /* Callback for c_genericize to implement -Wduplicated-branches. */
2832
2833 tree
do_warn_duplicated_branches_r(tree * tp,int *,void *)2834 do_warn_duplicated_branches_r (tree *tp, int *, void *)
2835 {
2836 if (TREE_CODE (*tp) == COND_EXPR)
2837 do_warn_duplicated_branches (*tp);
2838 return NULL_TREE;
2839 }
2840
2841 /* Implementation of -Wmultistatement-macros. This warning warns about
2842 cases when a macro expands to multiple statements not wrapped in
2843 do {} while (0) or ({ }) and is used as a body of if/else/for/while
2844 conditionals. For example,
2845
2846 #define DOIT x++; y++
2847
2848 if (c)
2849 DOIT;
2850
2851 will increment y unconditionally.
2852
2853 BODY_LOC is the location of the first token in the body after labels
2854 have been parsed, NEXT_LOC is the location of the next token after the
2855 body of the conditional has been parsed, and GUARD_LOC is the location
2856 of the conditional. */
2857
2858 void
warn_for_multistatement_macros(location_t body_loc,location_t next_loc,location_t guard_loc,enum rid keyword)2859 warn_for_multistatement_macros (location_t body_loc, location_t next_loc,
2860 location_t guard_loc, enum rid keyword)
2861 {
2862 if (!warn_multistatement_macros)
2863 return;
2864
2865 /* Ain't got time to waste. We only care about macros here. */
2866 if (!from_macro_expansion_at (body_loc)
2867 || !from_macro_expansion_at (next_loc))
2868 return;
2869
2870 /* Let's skip macros defined in system headers. */
2871 if (in_system_header_at (body_loc)
2872 || in_system_header_at (next_loc))
2873 return;
2874
2875 /* Find the actual tokens in the macro definition. BODY_LOC and
2876 NEXT_LOC have to come from the same spelling location, but they
2877 will resolve to different locations in the context of the macro
2878 definition. */
2879 location_t body_loc_exp
2880 = linemap_resolve_location (line_table, body_loc,
2881 LRK_MACRO_DEFINITION_LOCATION, NULL);
2882 location_t next_loc_exp
2883 = linemap_resolve_location (line_table, next_loc,
2884 LRK_MACRO_DEFINITION_LOCATION, NULL);
2885 location_t guard_loc_exp
2886 = linemap_resolve_location (line_table, guard_loc,
2887 LRK_MACRO_DEFINITION_LOCATION, NULL);
2888
2889 /* These are some funky cases we don't want to warn about. */
2890 if (body_loc_exp == guard_loc_exp
2891 || next_loc_exp == guard_loc_exp
2892 || body_loc_exp == next_loc_exp)
2893 return;
2894
2895 /* Find the macro maps for the macro expansions. */
2896 const line_map *body_map = linemap_lookup (line_table, body_loc);
2897 const line_map *next_map = linemap_lookup (line_table, next_loc);
2898 const line_map *guard_map = linemap_lookup (line_table, guard_loc);
2899
2900 /* Now see if the following token (after the body) is coming from the
2901 same macro expansion. If it is, it might be a problem. */
2902 if (body_map != next_map)
2903 return;
2904
2905 /* The conditional itself must not come from the same expansion, because
2906 we don't want to warn about
2907 #define IF if (x) x++; y++
2908 and similar. */
2909 if (guard_map == body_map)
2910 return;
2911
2912 /* Handle the case where NEXT and BODY come from the same expansion while
2913 GUARD doesn't, yet we shouldn't warn. E.g.
2914
2915 #define GUARD if (...)
2916 #define GUARD2 GUARD
2917
2918 and in the definition of another macro:
2919
2920 GUARD2
2921 foo ();
2922 return 1;
2923 */
2924 while (linemap_macro_expansion_map_p (guard_map))
2925 {
2926 const line_map_macro *mm = linemap_check_macro (guard_map);
2927 guard_loc_exp = MACRO_MAP_EXPANSION_POINT_LOCATION (mm);
2928 guard_map = linemap_lookup (line_table, guard_loc_exp);
2929 if (guard_map == body_map)
2930 return;
2931 }
2932
2933 auto_diagnostic_group d;
2934 if (warning_at (body_loc, OPT_Wmultistatement_macros,
2935 "macro expands to multiple statements"))
2936 inform (guard_loc, "some parts of macro expansion are not guarded by "
2937 "this %qs clause", guard_tinfo_to_string (keyword));
2938 }
2939
2940 /* Return struct or union type if the alignment of data member, FIELD,
2941 is less than the alignment of TYPE. Otherwise, return NULL_TREE.
2942 If RVALUE is true, only arrays evaluate to pointers. */
2943
2944 static tree
check_alignment_of_packed_member(tree type,tree field,bool rvalue)2945 check_alignment_of_packed_member (tree type, tree field, bool rvalue)
2946 {
2947 /* Check alignment of the data member. */
2948 if (TREE_CODE (field) == FIELD_DECL
2949 && (DECL_PACKED (field) || TYPE_PACKED (TREE_TYPE (field)))
2950 /* Ignore FIELDs not laid out yet. */
2951 && DECL_FIELD_OFFSET (field)
2952 && (!rvalue || TREE_CODE (TREE_TYPE (field)) == ARRAY_TYPE))
2953 {
2954 /* Check the expected alignment against the field alignment. */
2955 unsigned int type_align = min_align_of_type (type);
2956 tree context = DECL_CONTEXT (field);
2957 unsigned int record_align = min_align_of_type (context);
2958 if (record_align < type_align)
2959 return context;
2960 tree field_off = byte_position (field);
2961 if (!multiple_of_p (TREE_TYPE (field_off), field_off,
2962 size_int (type_align)))
2963 return context;
2964 }
2965
2966 return NULL_TREE;
2967 }
2968
2969 /* Return struct or union type if the right hand value, RHS:
2970 1. Is a pointer value which isn't aligned to a pointer type TYPE.
2971 2. Is an address which takes the unaligned address of packed member
2972 of struct or union when assigning to TYPE.
2973 Otherwise, return NULL_TREE. */
2974
2975 static tree
check_address_or_pointer_of_packed_member(tree type,tree rhs)2976 check_address_or_pointer_of_packed_member (tree type, tree rhs)
2977 {
2978 bool rvalue = true;
2979 bool indirect = false;
2980
2981 if (INDIRECT_REF_P (rhs))
2982 {
2983 rhs = TREE_OPERAND (rhs, 0);
2984 STRIP_NOPS (rhs);
2985 indirect = true;
2986 }
2987
2988 if (TREE_CODE (rhs) == ADDR_EXPR)
2989 {
2990 rhs = TREE_OPERAND (rhs, 0);
2991 rvalue = indirect;
2992 }
2993
2994 if (!POINTER_TYPE_P (type))
2995 return NULL_TREE;
2996
2997 type = TREE_TYPE (type);
2998
2999 if (TREE_CODE (rhs) == PARM_DECL
3000 || VAR_P (rhs)
3001 || TREE_CODE (rhs) == CALL_EXPR)
3002 {
3003 tree rhstype = TREE_TYPE (rhs);
3004 if (TREE_CODE (rhs) == CALL_EXPR)
3005 {
3006 rhs = CALL_EXPR_FN (rhs); /* Pointer expression. */
3007 if (rhs == NULL_TREE)
3008 return NULL_TREE;
3009 rhs = TREE_TYPE (rhs); /* Pointer type. */
3010 /* We could be called while processing a template and RHS could be
3011 a functor. In that case it's a class, not a pointer. */
3012 if (!POINTER_TYPE_P (rhs))
3013 return NULL_TREE;
3014 rhs = TREE_TYPE (rhs); /* Function type. */
3015 rhstype = TREE_TYPE (rhs);
3016 if (!rhstype || !POINTER_TYPE_P (rhstype))
3017 return NULL_TREE;
3018 rvalue = true;
3019 }
3020 if (rvalue && POINTER_TYPE_P (rhstype))
3021 rhstype = TREE_TYPE (rhstype);
3022 while (TREE_CODE (rhstype) == ARRAY_TYPE)
3023 rhstype = TREE_TYPE (rhstype);
3024 if (TYPE_PACKED (rhstype))
3025 {
3026 unsigned int type_align = min_align_of_type (type);
3027 unsigned int rhs_align = min_align_of_type (rhstype);
3028 if (rhs_align < type_align)
3029 {
3030 auto_diagnostic_group d;
3031 location_t location = EXPR_LOC_OR_LOC (rhs, input_location);
3032 if (warning_at (location, OPT_Waddress_of_packed_member,
3033 "converting a packed %qT pointer (alignment %d) "
3034 "to a %qT pointer (alignment %d) may result in "
3035 "an unaligned pointer value",
3036 rhstype, rhs_align, type, type_align))
3037 {
3038 tree decl = TYPE_STUB_DECL (rhstype);
3039 if (decl)
3040 inform (DECL_SOURCE_LOCATION (decl), "defined here");
3041 decl = TYPE_STUB_DECL (type);
3042 if (decl)
3043 inform (DECL_SOURCE_LOCATION (decl), "defined here");
3044 }
3045 }
3046 }
3047 return NULL_TREE;
3048 }
3049
3050 tree context = NULL_TREE;
3051
3052 /* Check alignment of the object. */
3053 while (handled_component_p (rhs))
3054 {
3055 if (TREE_CODE (rhs) == COMPONENT_REF)
3056 {
3057 tree field = TREE_OPERAND (rhs, 1);
3058 context = check_alignment_of_packed_member (type, field, rvalue);
3059 if (context)
3060 break;
3061 }
3062 if (TREE_CODE (TREE_TYPE (rhs)) == ARRAY_TYPE)
3063 rvalue = false;
3064 if (rvalue)
3065 return NULL_TREE;
3066 rhs = TREE_OPERAND (rhs, 0);
3067 }
3068
3069 return context;
3070 }
3071
3072 /* Check and warn if the right hand value, RHS:
3073 1. Is a pointer value which isn't aligned to a pointer type TYPE.
3074 2. Is an address which takes the unaligned address of packed member
3075 of struct or union when assigning to TYPE.
3076 */
3077
3078 static void
check_and_warn_address_or_pointer_of_packed_member(tree type,tree rhs)3079 check_and_warn_address_or_pointer_of_packed_member (tree type, tree rhs)
3080 {
3081 bool nop_p = false;
3082 tree orig_rhs;
3083
3084 do
3085 {
3086 while (TREE_CODE (rhs) == COMPOUND_EXPR)
3087 rhs = TREE_OPERAND (rhs, 1);
3088 orig_rhs = rhs;
3089 STRIP_NOPS (rhs);
3090 nop_p |= orig_rhs != rhs;
3091 }
3092 while (orig_rhs != rhs);
3093
3094 if (TREE_CODE (rhs) == COND_EXPR)
3095 {
3096 /* Check the THEN path. */
3097 check_and_warn_address_or_pointer_of_packed_member
3098 (type, TREE_OPERAND (rhs, 1));
3099
3100 /* Check the ELSE path. */
3101 check_and_warn_address_or_pointer_of_packed_member
3102 (type, TREE_OPERAND (rhs, 2));
3103 }
3104 else
3105 {
3106 if (nop_p)
3107 {
3108 switch (TREE_CODE (rhs))
3109 {
3110 case ADDR_EXPR:
3111 /* Address is taken. */
3112 case PARM_DECL:
3113 case VAR_DECL:
3114 /* Pointer conversion. */
3115 break;
3116 case CALL_EXPR:
3117 /* Function call. */
3118 break;
3119 default:
3120 return;
3121 }
3122 }
3123
3124 tree context
3125 = check_address_or_pointer_of_packed_member (type, rhs);
3126 if (context)
3127 {
3128 location_t loc = EXPR_LOC_OR_LOC (rhs, input_location);
3129 warning_at (loc, OPT_Waddress_of_packed_member,
3130 "taking address of packed member of %qT may result "
3131 "in an unaligned pointer value",
3132 context);
3133 }
3134 }
3135 }
3136
3137 /* Warn if the right hand value, RHS:
3138 1. Is a pointer value which isn't aligned to a pointer type TYPE.
3139 2. Is an address which takes the unaligned address of packed member
3140 of struct or union when assigning to TYPE.
3141 */
3142
3143 void
warn_for_address_or_pointer_of_packed_member(tree type,tree rhs)3144 warn_for_address_or_pointer_of_packed_member (tree type, tree rhs)
3145 {
3146 if (!warn_address_of_packed_member)
3147 return;
3148
3149 /* Don't warn if we don't assign RHS to a pointer. */
3150 if (!POINTER_TYPE_P (type))
3151 return;
3152
3153 check_and_warn_address_or_pointer_of_packed_member (type, rhs);
3154 }
3155
3156 /* Return EXPR + 1. Convenience helper used below. */
3157
3158 static inline tree
plus_one(tree expr)3159 plus_one (tree expr)
3160 {
3161 tree type = TREE_TYPE (expr);
3162 return fold_build2 (PLUS_EXPR, type, expr, build_int_cst (type, 1));
3163 }
3164
3165 /* Try to strip the expressions from around a VLA bound added internally
3166 to make it fit the domain mold, including any casts, and return
3167 the result. The goal is to obtain the PARM_DECL the VLA bound may
3168 refer to. */
3169
3170 static tree
vla_bound_parm_decl(tree expr)3171 vla_bound_parm_decl (tree expr)
3172 {
3173 if (!expr)
3174 return NULL_TREE;
3175
3176 if (TREE_CODE (expr) == NOP_EXPR)
3177 expr = TREE_OPERAND (expr, 0);
3178 if (TREE_CODE (expr) == PLUS_EXPR
3179 && integer_all_onesp (TREE_OPERAND (expr, 1)))
3180 {
3181 expr = TREE_OPERAND (expr, 0);
3182 if (TREE_CODE (expr) == NOP_EXPR)
3183 expr = TREE_OPERAND (expr, 0);
3184 }
3185 if (TREE_CODE (expr) == SAVE_EXPR)
3186 {
3187 expr = TREE_OPERAND (expr, 0);
3188 if (TREE_CODE (expr) == NOP_EXPR)
3189 expr = TREE_OPERAND (expr, 0);
3190 }
3191 return expr;
3192 }
3193
3194 /* Diagnose mismatches in VLA bounds between function parameters NEWPARMS
3195 of pointer types on a redeclaration of a function previously declared
3196 with CURPARMS at ORIGLOC. */
3197
3198 static void
warn_parm_ptrarray_mismatch(location_t origloc,tree curparms,tree newparms)3199 warn_parm_ptrarray_mismatch (location_t origloc, tree curparms, tree newparms)
3200 {
3201 /* Maps each named integral parameter seen so far to its position
3202 in the argument list; used to associate VLA sizes with arguments. */
3203 hash_map<tree, unsigned> curparm2pos;
3204 hash_map<tree, unsigned> newparm2pos;
3205
3206 unsigned parmpos = 1;
3207 for (tree curp = curparms, newp = newparms; curp && newp;
3208 curp = TREE_CHAIN (curp), newp = TREE_CHAIN (newp), ++parmpos)
3209 {
3210 tree curtyp = TREE_TYPE (curp), newtyp = TREE_TYPE (newp);
3211 if (INTEGRAL_TYPE_P (curtyp))
3212 {
3213 /* Only add named parameters; unnamed ones cannot be referred
3214 to in VLA bounds. */
3215 if (DECL_NAME (curp))
3216 curparm2pos.put (curp, parmpos);
3217 if (DECL_NAME (newp))
3218 newparm2pos.put (newp, parmpos);
3219
3220 continue;
3221 }
3222
3223 /* The parameter types should match at this point so only test one. */
3224 if (TREE_CODE (curtyp) != POINTER_TYPE)
3225 continue;
3226
3227 do
3228 {
3229 curtyp = TREE_TYPE (curtyp);
3230 newtyp = TREE_TYPE (newtyp);
3231
3232 if (!newtyp)
3233 /* Bail on error. */
3234 return;
3235 }
3236 while (TREE_CODE (curtyp) == POINTER_TYPE
3237 && TREE_CODE (newtyp) == POINTER_TYPE);
3238
3239 if (TREE_CODE (curtyp) != ARRAY_TYPE
3240 || TREE_CODE (newtyp) != ARRAY_TYPE)
3241 {
3242 if (curtyp == error_mark_node
3243 || newtyp == error_mark_node)
3244 /* Bail on error. */
3245 return;
3246
3247 continue;
3248 }
3249
3250 tree curdom = TYPE_DOMAIN (curtyp), newdom = TYPE_DOMAIN (newtyp);
3251 tree curbnd = curdom ? TYPE_MAX_VALUE (curdom) : NULL_TREE;
3252 tree newbnd = newdom ? TYPE_MAX_VALUE (newdom) : NULL_TREE;
3253
3254 if (DECL_P (curp))
3255 origloc = DECL_SOURCE_LOCATION (curp);
3256 else if (EXPR_P (curp) && EXPR_HAS_LOCATION (curp))
3257 origloc = EXPR_LOCATION (curp);
3258
3259 /* The location of the parameter in the current redeclaration. */
3260 location_t newloc = DECL_SOURCE_LOCATION (newp);
3261 if (origloc == UNKNOWN_LOCATION)
3262 origloc = newloc;
3263
3264 /* Issue -Warray-parameter unless one or more mismatches involves
3265 a VLA bound; then issue -Wvla-parameter. */
3266 int opt = OPT_Warray_parameter_;
3267 /* Traverse the two array types looking for variable bounds and
3268 comparing the two in each pair for mismatches either in their
3269 positions in the function parameter list or lexicographically
3270 for others. Record the 1-based parameter position of each
3271 mismatch in BNDVEC, and the location of each parameter in
3272 the mismatch in WARNLOC (for the new parameter list) and
3273 NOTELOC (for the current parameter list). */
3274 unsigned bndpos = 1;
3275 auto_vec<int> bndvec;
3276 gcc_rich_location warnloc (newloc);
3277 gcc_rich_location noteloc (origloc);
3278 for ( ; curtyp || newtyp;
3279 ++bndpos,
3280 curbnd = curdom ? TYPE_MAX_VALUE (curdom) : NULL_TREE,
3281 newbnd = newdom ? TYPE_MAX_VALUE (newdom) : NULL_TREE)
3282 {
3283 /* Try to strip each bound down to the PARM_DECL if it does
3284 correspond to one. Either bound can be null if it's
3285 unspecified (i.e., has the [*] form). */
3286 curbnd = vla_bound_parm_decl (curbnd);
3287 newbnd = vla_bound_parm_decl (newbnd);
3288
3289 /* Peel the current bound off CURTYP and NEWTYP, skipping
3290 over any subsequent pointer types. */
3291 if (curtyp && TREE_CODE (curtyp) == ARRAY_TYPE)
3292 {
3293 do
3294 curtyp = TREE_TYPE (curtyp);
3295 while (TREE_CODE (curtyp) == POINTER_TYPE);
3296 if (TREE_CODE (curtyp) == ARRAY_TYPE)
3297 curdom = TYPE_DOMAIN (curtyp);
3298 else
3299 curdom = NULL_TREE;
3300 }
3301 else
3302 curtyp = NULL_TREE;
3303
3304 if (newtyp && TREE_CODE (newtyp) == ARRAY_TYPE)
3305 {
3306 do
3307 newtyp = TREE_TYPE (newtyp);
3308 while (TREE_CODE (newtyp) == POINTER_TYPE);
3309 if (TREE_CODE (newtyp) == ARRAY_TYPE)
3310 newdom = TYPE_DOMAIN (newtyp);
3311 else
3312 newdom = NULL_TREE;
3313 }
3314 else
3315 newtyp = NULL_TREE;
3316
3317 /* Move on to the next bound if this one is unspecified. */
3318 if (!curbnd && !newbnd)
3319 continue;
3320
3321 /* Try to find each bound in the parameter list. */
3322 const unsigned* const pcurbndpos = curparm2pos.get (curbnd);
3323 const unsigned* const pnewbndpos = newparm2pos.get (newbnd);
3324 /* Move on if both bounds refer to the same parameter. */
3325 if (pcurbndpos && pnewbndpos && *pcurbndpos == *pnewbndpos)
3326 continue;
3327
3328 /* Move on if the bounds look the same. */
3329 if (!pcurbndpos && !pnewbndpos
3330 && curbnd && newbnd
3331 && operand_equal_p (curbnd, newbnd,
3332 OEP_DECL_NAME | OEP_LEXICOGRAPHIC))
3333 continue;
3334
3335 if ((curbnd && TREE_CODE (curbnd) != INTEGER_CST)
3336 || (newbnd && TREE_CODE (newbnd) != INTEGER_CST))
3337 opt = OPT_Wvla_parameter;
3338
3339 /* Record the mismatch. */
3340 bndvec.safe_push (bndpos);
3341 /* Underline the bounding parameter in the declaration. */
3342 if (curbnd && TREE_CODE (curbnd) == PARM_DECL)
3343 noteloc.add_range (DECL_SOURCE_LOCATION (curbnd));
3344 if (newbnd && TREE_CODE (newbnd) == PARM_DECL)
3345 warnloc.add_range (DECL_SOURCE_LOCATION (newbnd));
3346 }
3347
3348 const unsigned nbnds = bndvec.length ();
3349 if (!nbnds)
3350 continue;
3351
3352 /* Use attr_access to format the parameter types. */
3353 attr_access spec = { };
3354 const std::string newparmstr = spec.array_as_string (TREE_TYPE (newp));
3355 const std::string curparmstr = spec.array_as_string (TREE_TYPE (curp));
3356
3357 if (warning_n (&warnloc, opt, nbnds,
3358 "mismatch in bound %Z of argument %u declared as %s",
3359 "mismatch in bounds %Z of argument %u declared as %s",
3360 bndvec.address (), nbnds, parmpos, newparmstr.c_str ()))
3361 inform (¬eloc, "previously declared as %s", curparmstr.c_str ());
3362 }
3363 }
3364
3365 /* Format EXPR if nonnull and return the formatted string. If EXPR is
3366 null return DFLT. */
3367
3368 static inline const char*
expr_to_str(pretty_printer & pp,tree expr,const char * dflt)3369 expr_to_str (pretty_printer &pp, tree expr, const char *dflt)
3370 {
3371 if (!expr)
3372 return dflt;
3373
3374 dump_generic_node (&pp, expr, 0, TDF_VOPS | TDF_MEMSYMS, false);
3375 return pp_formatted_text (&pp);
3376 }
3377
3378 /* Detect and diagnose a mismatch between an attribute access specification
3379 on the original declaration of FNDECL and that on the parameters NEWPARMS
3380 from its redeclaration. ORIGLOC is the location of the first declaration
3381 (FNDECL's is set to the location of the redeclaration). */
3382
3383 void
warn_parm_array_mismatch(location_t origloc,tree fndecl,tree newparms)3384 warn_parm_array_mismatch (location_t origloc, tree fndecl, tree newparms)
3385 {
3386 /* The original parameter list (copied from the original declaration
3387 into the current [re]declaration, FNDECL)). The two are equal if
3388 and only if FNDECL is the first declaration. */
3389 tree curparms = DECL_ARGUMENTS (fndecl);
3390 if (!curparms || !newparms || curparms == newparms)
3391 return;
3392
3393 if (TREE_CODE (curparms) != PARM_DECL
3394 || TREE_CODE (newparms) != PARM_DECL)
3395 return;
3396 /* Extract the (possibly empty) attribute access specification from
3397 the declaration and its type (it doesn't yet reflect those created
3398 in response to NEWPARMS). */
3399 rdwr_map cur_idx;
3400 tree fntype = TREE_TYPE (fndecl);
3401 init_attr_rdwr_indices (&cur_idx, TYPE_ATTRIBUTES (fntype));
3402
3403 /* Build a (possibly null) chain of access attributes corresponding
3404 to NEWPARMS. */
3405 const bool builtin = fndecl_built_in_p (fndecl);
3406 tree newattrs = build_attr_access_from_parms (newparms, builtin);
3407
3408 /* Extract the (possibly empty) attribute access specification from
3409 NEWATTRS. */
3410 rdwr_map new_idx;
3411 init_attr_rdwr_indices (&new_idx, newattrs);
3412
3413 if (cur_idx.is_empty () && new_idx.is_empty ())
3414 {
3415 /* If both specs are empty check pointers to VLAs for mismatches. */
3416 warn_parm_ptrarray_mismatch (origloc, curparms, newparms);
3417 return;
3418 }
3419 /* ...otherwise, if at least one spec isn't empty there may be mismatches,
3420 such as between f(T*) and f(T[1]), where the former mapping would be
3421 empty. */
3422
3423 /* Create an empty access specification and use it for pointers with
3424 no spec of their own. */
3425 attr_access ptr_spec = { };
3426
3427 /* Iterate over the two lists of function parameters, comparing their
3428 respective mappings and diagnosing mismatches. */
3429 unsigned parmpos = 0;
3430 for (tree curp = curparms, newp = newparms; curp;
3431 curp = TREE_CHAIN (curp), newp = TREE_CHAIN (newp), ++parmpos)
3432 {
3433 if (!newp)
3434 /* Bail on invalid redeclarations with fewer arguments. */
3435 return;
3436
3437 /* Only check pointers and C++ references. */
3438 tree curptype = TREE_TYPE (curp);
3439 tree newptype = TREE_TYPE (newp);
3440 if (!POINTER_TYPE_P (curptype) || !POINTER_TYPE_P (newptype))
3441 continue;
3442
3443 /* Skip mismatches in __builtin_va_list that is commonly
3444 an array but that in declarations of built-ins decays
3445 to a pointer. */
3446 if (builtin && TREE_TYPE (newptype) == TREE_TYPE (va_list_type_node))
3447 continue;
3448
3449 /* Access specs for the argument on the current (previous) and
3450 new (to replace the current) declarations. Either may be null,
3451 indicating the parameter is an ordinary pointer with no size
3452 associated with it. */
3453 attr_access *cura = cur_idx.get (parmpos);
3454 attr_access *newa = new_idx.get (parmpos);
3455
3456 if (!newa)
3457 {
3458 /* Continue of both parameters are pointers with no size
3459 associated with it. */
3460 if (!cura)
3461 continue;
3462
3463 /* Otherwise point at PTR_SPEC and set its parameter pointer
3464 and number. */
3465 newa = &ptr_spec;
3466 newa->ptr = newp;
3467 newa->ptrarg = parmpos;
3468 }
3469 else if (!cura)
3470 {
3471 cura = &ptr_spec;
3472 cura->ptr = curp;
3473 cura->ptrarg = parmpos;
3474 }
3475
3476 /* Set if the parameter is [re]declared as a VLA. */
3477 const bool cur_vla_p = cura->size || cura->minsize == HOST_WIDE_INT_M1U;
3478 const bool new_vla_p = newa->size || newa->minsize == HOST_WIDE_INT_M1U;
3479
3480 if (DECL_P (curp))
3481 origloc = DECL_SOURCE_LOCATION (curp);
3482 else if (EXPR_P (curp) && EXPR_HAS_LOCATION (curp))
3483 origloc = EXPR_LOCATION (curp);
3484
3485 /* The location of the parameter in the current redeclaration. */
3486 location_t newloc = DECL_SOURCE_LOCATION (newp);
3487 if (origloc == UNKNOWN_LOCATION)
3488 origloc = newloc;
3489
3490 const std::string newparmstr = newa->array_as_string (newptype);
3491 const std::string curparmstr = cura->array_as_string (curptype);
3492 if (new_vla_p && !cur_vla_p)
3493 {
3494 if (warning_at (newloc, OPT_Wvla_parameter,
3495 "argument %u of type %s declared as "
3496 "a variable length array",
3497 parmpos + 1, newparmstr.c_str ()))
3498 inform (origloc,
3499 (cura == &ptr_spec
3500 ? G_("previously declared as a pointer %s")
3501 : G_("previously declared as an ordinary array %s")),
3502 curparmstr.c_str ());
3503 continue;
3504 }
3505
3506 if (newa == &ptr_spec)
3507 {
3508 /* The new declaration uses the pointer form. Detect mismatches
3509 between the pointer and a previous array or VLA forms. */
3510 if (cura->minsize == HOST_WIDE_INT_M1U)
3511 {
3512 /* Diagnose a pointer/VLA mismatch. */
3513 if (warning_at (newloc, OPT_Wvla_parameter,
3514 "argument %u of type %s declared "
3515 "as a pointer",
3516 parmpos + 1, newparmstr.c_str ()))
3517 inform (origloc,
3518 "previously declared as a variable length array %s",
3519 curparmstr.c_str ());
3520 continue;
3521 }
3522
3523 if (cura->minsize && cura->minsize != HOST_WIDE_INT_M1U)
3524 {
3525 /* Diagnose mismatches between arrays with a constant
3526 bound and pointers. */
3527 if (warning_at (newloc, OPT_Warray_parameter_,
3528 "argument %u of type %s declared "
3529 "as a pointer",
3530 parmpos + 1, newparmstr.c_str ()))
3531 inform (origloc, "previously declared as an array %s",
3532 curparmstr.c_str ());
3533 continue;
3534 }
3535 }
3536
3537 if (!new_vla_p && cur_vla_p)
3538 {
3539 if (warning_at (newloc, OPT_Wvla_parameter,
3540 "argument %u of type %s declared "
3541 "as an ordinary array",
3542 parmpos + 1, newparmstr.c_str ()))
3543 inform (origloc,
3544 "previously declared as a variable length array %s",
3545 curparmstr.c_str ());
3546 continue;
3547 }
3548
3549 /* Move on to the next pair of parameters if both of the current
3550 pair are VLAs with a single variable bound that refers to
3551 a parameter at the same position. */
3552 if (newa->size && cura->size
3553 && newa->sizarg != UINT_MAX
3554 && newa->sizarg == cura->sizarg
3555 && newa->minsize == cura->minsize
3556 && !TREE_PURPOSE (newa->size) && !TREE_PURPOSE (cura->size))
3557 continue;
3558
3559 if (newa->size || cura->size)
3560 {
3561 unsigned newunspec, curunspec;
3562 unsigned newbnds = newa->vla_bounds (&newunspec) + newunspec;
3563 unsigned curbnds = cura->vla_bounds (&curunspec) + curunspec;
3564
3565 if (newbnds != curbnds)
3566 {
3567 if (warning_n (newloc, OPT_Wvla_parameter, newbnds,
3568 "argument %u of type %s declared with "
3569 "%u variable bound",
3570 "argument %u of type %s declared with "
3571 "%u variable bounds",
3572 parmpos + 1, newparmstr.c_str (),
3573 newbnds))
3574 inform_n (origloc, curbnds,
3575 "previously declared as %s with %u variable bound",
3576 "previously declared as %s with %u variable bounds",
3577 curparmstr.c_str (), curbnds);
3578 continue;
3579 }
3580
3581 if (newunspec != curunspec)
3582 {
3583 location_t warnloc = newloc, noteloc = origloc;
3584 const char *warnparmstr = newparmstr.c_str ();
3585 const char *noteparmstr = curparmstr.c_str ();
3586 unsigned warnunspec = newunspec, noteunspec = curunspec;
3587
3588 if (newunspec < curunspec)
3589 {
3590 /* If the new declaration has fewer unspecified bounds
3591 point the warning to the previous declaration to make
3592 it clear that that's the one to change. Otherwise,
3593 point it to the new decl. */
3594 std::swap (warnloc, noteloc);
3595 std::swap (warnparmstr, noteparmstr);
3596 std::swap (warnunspec, noteunspec);
3597 }
3598 if (warning_n (warnloc, OPT_Wvla_parameter, warnunspec,
3599 "argument %u of type %s declared with "
3600 "%u unspecified variable bound",
3601 "argument %u of type %s declared with "
3602 "%u unspecified variable bounds",
3603 parmpos + 1, warnparmstr, warnunspec))
3604 {
3605 if (warnloc == newloc)
3606 inform_n (noteloc, noteunspec,
3607 "previously declared as %s with %u unspecified "
3608 "variable bound",
3609 "previously declared as %s with %u unspecified "
3610 "variable bounds",
3611 noteparmstr, noteunspec);
3612 else
3613 inform_n (noteloc, noteunspec,
3614 "subsequently declared as %s with %u unspecified "
3615 "variable bound",
3616 "subsequently declared as %s with %u unspecified "
3617 "variable bounds",
3618 noteparmstr, noteunspec);
3619 }
3620 continue;
3621 }
3622 }
3623
3624 /* Iterate over the lists of VLA variable bounds, comparing each
3625 pair for equality, and diagnosing mismatches. The case of
3626 the lists having different lengths is handled above so at
3627 this point they do . */
3628 for (tree newvbl = newa->size, curvbl = cura->size; newvbl;
3629 newvbl = TREE_CHAIN (newvbl), curvbl = TREE_CHAIN (curvbl))
3630 {
3631 tree newpos = TREE_PURPOSE (newvbl);
3632 tree curpos = TREE_PURPOSE (curvbl);
3633
3634 tree newbnd = vla_bound_parm_decl (TREE_VALUE (newvbl));
3635 tree curbnd = vla_bound_parm_decl (TREE_VALUE (curvbl));
3636
3637 if (newpos == curpos && newbnd == curbnd)
3638 /* In the expected case when both bounds either refer to
3639 the same positional parameter or when neither does,
3640 and both are the same expression they are necessarily
3641 the same. */
3642 continue;
3643
3644 pretty_printer pp1, pp2;
3645 const char* const newbndstr = expr_to_str (pp1, newbnd, "*");
3646 const char* const curbndstr = expr_to_str (pp2, curbnd, "*");
3647
3648 if (!newpos != !curpos
3649 || (newpos && !tree_int_cst_equal (newpos, curpos)))
3650 {
3651 /* Diagnose a mismatch between a specified VLA bound and
3652 an unspecified one. This can only happen in the most
3653 significant bound.
3654
3655 Distinguish between the common case of bounds that are
3656 other function parameters such as in
3657 f (int n, int[n]);
3658 and others. */
3659
3660 gcc_rich_location richloc (newloc);
3661 bool warned;
3662 if (newpos)
3663 {
3664 /* Also underline the VLA bound argument. */
3665 richloc.add_range (DECL_SOURCE_LOCATION (newbnd));
3666 warned = warning_at (&richloc, OPT_Wvla_parameter,
3667 "argument %u of type %s declared "
3668 "with mismatched bound argument %E",
3669 parmpos + 1, newparmstr.c_str (),
3670 plus_one (newpos));
3671 }
3672 else
3673 warned = warning_at (&richloc, OPT_Wvla_parameter,
3674 "argument %u of type %s declared "
3675 "with mismatched bound %<%s%>",
3676 parmpos + 1, newparmstr.c_str (),
3677 newbndstr);
3678
3679 if (warned)
3680 {
3681 gcc_rich_location richloc (origloc);
3682 if (curpos)
3683 {
3684 /* Also underline the VLA bound argument. */
3685 richloc.add_range (DECL_SOURCE_LOCATION (curbnd));
3686 inform (&richloc, "previously declared as %s with "
3687 "bound argument %E",
3688 curparmstr.c_str (), plus_one (curpos));
3689 }
3690 else
3691 inform (&richloc, "previously declared as %s with bound "
3692 "%<%s%>", curparmstr.c_str (), curbndstr);
3693
3694 continue;
3695 }
3696 }
3697
3698 if (!newpos && newbnd && curbnd)
3699 {
3700 /* The VLA bounds don't refer to other function parameters.
3701 Compare them lexicographically to detect gross mismatches
3702 such as between T[foo()] and T[bar()]. */
3703 if (operand_equal_p (newbnd, curbnd,
3704 OEP_DECL_NAME | OEP_LEXICOGRAPHIC))
3705 continue;
3706
3707 if (warning_at (newloc, OPT_Wvla_parameter,
3708 "argument %u of type %s declared with "
3709 "mismatched bound %<%s%>",
3710 parmpos + 1, newparmstr.c_str (), newbndstr))
3711 inform (origloc, "previously declared as %s with bound %qs",
3712 curparmstr.c_str (), curbndstr);
3713 continue;
3714 }
3715 }
3716
3717 if (newa->minsize == cura->minsize
3718 || (((newa->minsize == 0 && newa->mode != access_deferred)
3719 || (cura->minsize == 0 && cura->mode != access_deferred))
3720 && newa != &ptr_spec
3721 && cura != &ptr_spec))
3722 continue;
3723
3724 if (!newa->static_p && !cura->static_p && warn_array_parameter < 2)
3725 /* Avoid warning about mismatches in ordinary (non-static) arrays
3726 at levels below 2. */
3727 continue;
3728
3729 if (warning_at (newloc, OPT_Warray_parameter_,
3730 "argument %u of type %s with mismatched bound",
3731 parmpos + 1, newparmstr.c_str ()))
3732 inform (origloc, "previously declared as %s", curparmstr.c_str ());
3733 }
3734 }
3735
3736 /* Warn about divisions of two sizeof operators when the first one is applied
3737 to an array and the divisor does not equal the size of the array element.
3738 For instance:
3739
3740 sizeof (ARR) / sizeof (OP)
3741
3742 ARR is the array argument of the first sizeof, ARR_TYPE is its ARRAY_TYPE.
3743 OP1 is the whole second SIZEOF_EXPR, or its argument; TYPE1 is the type
3744 of the second argument. */
3745
3746 void
maybe_warn_sizeof_array_div(location_t loc,tree arr,tree arr_type,tree op1,tree type1)3747 maybe_warn_sizeof_array_div (location_t loc, tree arr, tree arr_type,
3748 tree op1, tree type1)
3749 {
3750 tree elt_type = TREE_TYPE (arr_type);
3751
3752 if (!warn_sizeof_array_div
3753 /* Don't warn on multidimensional arrays. */
3754 || TREE_CODE (elt_type) == ARRAY_TYPE)
3755 return;
3756
3757 if (!tree_int_cst_equal (TYPE_SIZE (elt_type), TYPE_SIZE (type1)))
3758 {
3759 auto_diagnostic_group d;
3760 if (warning_at (loc, OPT_Wsizeof_array_div,
3761 "expression does not compute the number of "
3762 "elements in this array; element type is "
3763 "%qT, not %qT", elt_type, type1))
3764 {
3765 if (EXPR_HAS_LOCATION (op1))
3766 {
3767 location_t op1_loc = EXPR_LOCATION (op1);
3768 gcc_rich_location richloc (op1_loc);
3769 richloc.add_fixit_insert_before (op1_loc, "(");
3770 richloc.add_fixit_insert_after (op1_loc, ")");
3771 inform (&richloc, "add parentheses around %qE to "
3772 "silence this warning", op1);
3773 }
3774 else
3775 inform (loc, "add parentheses around the second %<sizeof%> "
3776 "to silence this warning");
3777 if (DECL_P (arr))
3778 inform (DECL_SOURCE_LOCATION (arr), "array %qD declared here", arr);
3779 }
3780 }
3781 }
3782
3783 /* Warn about C++20 [depr.array.comp] array comparisons: "Equality
3784 and relational comparisons between two operands of array type are
3785 deprecated." We also warn in C and earlier C++ standards. CODE is
3786 the code for this comparison, OP0 and OP1 are the operands. */
3787
3788 void
do_warn_array_compare(location_t location,tree_code code,tree op0,tree op1)3789 do_warn_array_compare (location_t location, tree_code code, tree op0, tree op1)
3790 {
3791 STRIP_NOPS (op0);
3792 STRIP_NOPS (op1);
3793 if (TREE_CODE (op0) == ADDR_EXPR)
3794 op0 = TREE_OPERAND (op0, 0);
3795 if (TREE_CODE (op1) == ADDR_EXPR)
3796 op1 = TREE_OPERAND (op1, 0);
3797
3798 auto_diagnostic_group d;
3799 if (warning_at (location, OPT_Warray_compare,
3800 (c_dialect_cxx () && cxx_dialect >= cxx20)
3801 ? G_("comparison between two arrays is deprecated in C++20")
3802 : G_("comparison between two arrays")))
3803 {
3804 /* C doesn't allow +arr. */
3805 if (c_dialect_cxx ())
3806 inform (location, "use unary %<+%> which decays operands to pointers "
3807 "or %<&%D[0] %s &%D[0]%> to compare the addresses",
3808 op0, op_symbol_code (code), op1);
3809 else
3810 inform (location, "use %<&%D[0] %s &%D[0]%> to compare the addresses",
3811 op0, op_symbol_code (code), op1);
3812 }
3813 }
3814