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