* varasm.c (output_constructor_regular_field): Check TYPE_SIZE_UNIT of
[official-gcc.git] / gcc / gimple-ssa-warn-alloca.c
blob4d5aed866e1b696e7e28b37313126b7feaca321d
1 /* Warn on problematic uses of alloca and variable length arrays.
2 Copyright (C) 2016-2018 Free Software Foundation, Inc.
3 Contributed by Aldy Hernandez <aldyh@redhat.com>.
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 3, or (at your option) any later
10 version.
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "backend.h"
25 #include "tree.h"
26 #include "gimple.h"
27 #include "tree-pass.h"
28 #include "ssa.h"
29 #include "gimple-pretty-print.h"
30 #include "diagnostic-core.h"
31 #include "fold-const.h"
32 #include "gimple-iterator.h"
33 #include "tree-ssa.h"
34 #include "params.h"
35 #include "tree-cfg.h"
36 #include "builtins.h"
37 #include "calls.h"
38 #include "cfgloop.h"
39 #include "intl.h"
41 static unsigned HOST_WIDE_INT adjusted_warn_limit (bool);
43 const pass_data pass_data_walloca = {
44 GIMPLE_PASS,
45 "walloca",
46 OPTGROUP_NONE,
47 TV_NONE,
48 PROP_cfg, // properties_required
49 0, // properties_provided
50 0, // properties_destroyed
51 0, // properties_start
52 0, // properties_finish
55 class pass_walloca : public gimple_opt_pass
57 public:
58 pass_walloca (gcc::context *ctxt)
59 : gimple_opt_pass(pass_data_walloca, ctxt), first_time_p (false)
61 opt_pass *clone () { return new pass_walloca (m_ctxt); }
62 void set_pass_param (unsigned int n, bool param)
64 gcc_assert (n == 0);
65 first_time_p = param;
67 virtual bool gate (function *);
68 virtual unsigned int execute (function *);
70 private:
71 // Set to TRUE the first time we run this pass on a function.
72 bool first_time_p;
75 bool
76 pass_walloca::gate (function *fun ATTRIBUTE_UNUSED)
78 // The first time this pass is called, it is called before
79 // optimizations have been run and range information is unavailable,
80 // so we can only perform strict alloca checking.
81 if (first_time_p)
82 return warn_alloca != 0;
84 // Warning is disabled when its size limit is greater than PTRDIFF_MAX
85 // for the target maximum, which makes the limit negative since when
86 // represented in signed HOST_WIDE_INT.
87 unsigned HOST_WIDE_INT max = tree_to_uhwi (TYPE_MAX_VALUE (ptrdiff_type_node));
88 return (adjusted_warn_limit (false) <= max
89 || adjusted_warn_limit (true) <= max);
92 // Possible problematic uses of alloca.
93 enum alloca_type {
94 // Alloca argument is within known bounds that are appropriate.
95 ALLOCA_OK,
97 // Alloca argument is KNOWN to have a value that is too large.
98 ALLOCA_BOUND_DEFINITELY_LARGE,
100 // Alloca argument may be too large.
101 ALLOCA_BOUND_MAYBE_LARGE,
103 // Alloca argument is bounded but of an indeterminate size.
104 ALLOCA_BOUND_UNKNOWN,
106 // Alloca argument was casted from a signed integer.
107 ALLOCA_CAST_FROM_SIGNED,
109 // Alloca appears in a loop.
110 ALLOCA_IN_LOOP,
112 // Alloca argument is 0.
113 ALLOCA_ARG_IS_ZERO,
115 // Alloca call is unbounded. That is, there is no controlling
116 // predicate for its argument.
117 ALLOCA_UNBOUNDED
120 // Type of an alloca call with its corresponding limit, if applicable.
121 struct alloca_type_and_limit {
122 enum alloca_type type;
123 // For ALLOCA_BOUND_MAYBE_LARGE and ALLOCA_BOUND_DEFINITELY_LARGE
124 // types, this field indicates the assumed limit if known or
125 // integer_zero_node if unknown. For any other alloca types, this
126 // field is undefined.
127 wide_int limit;
128 alloca_type_and_limit ();
129 alloca_type_and_limit (enum alloca_type type,
130 wide_int i) : type(type), limit(i) { }
131 alloca_type_and_limit (enum alloca_type type) : type(type) { }
134 /* Return the value of the argument N to -Walloca-larger-than= or
135 -Wvla-larger-than= adjusted for the target data model so that
136 when N == HOST_WIDE_INT_MAX, the adjusted value is set to
137 PTRDIFF_MAX on the target. This is done to prevent warnings
138 for unknown/unbounded allocations in the "permissive mode"
139 while still diagnosing excessive and necessarily invalid
140 allocations. */
142 static unsigned HOST_WIDE_INT
143 adjusted_warn_limit (bool idx)
145 static HOST_WIDE_INT limits[2];
146 if (limits[idx])
147 return limits[idx];
149 limits[idx] = idx ? warn_vla_limit : warn_alloca_limit;
150 if (limits[idx] != HOST_WIDE_INT_MAX)
151 return limits[idx];
153 limits[idx] = tree_to_shwi (TYPE_MAX_VALUE (ptrdiff_type_node));
154 return limits[idx];
158 // NOTE: When we get better range info, this entire function becomes
159 // irrelevant, as it should be possible to get range info for an SSA
160 // name at any point in the program.
162 // We have a few heuristics up our sleeve to determine if a call to
163 // alloca() is within bounds. Try them out and return the type of
164 // alloca call with its assumed limit (if applicable).
166 // Given a known argument (ARG) to alloca() and an EDGE (E)
167 // calculating said argument, verify that the last statement in the BB
168 // in E->SRC is a gate comparing ARG to an acceptable bound for
169 // alloca(). See examples below.
171 // If set, ARG_CASTED is the possible unsigned argument to which ARG
172 // was casted to. This is to handle cases where the controlling
173 // predicate is looking at a casted value, not the argument itself.
174 // arg_casted = (size_t) arg;
175 // if (arg_casted < N)
176 // goto bb3;
177 // else
178 // goto bb5;
180 // MAX_SIZE is WARN_ALLOCA= adjusted for VLAs. It is the maximum size
181 // in bytes we allow for arg.
183 static struct alloca_type_and_limit
184 alloca_call_type_by_arg (tree arg, tree arg_casted, edge e,
185 unsigned HOST_WIDE_INT max_size)
187 basic_block bb = e->src;
188 gimple_stmt_iterator gsi = gsi_last_bb (bb);
189 gimple *last = gsi_stmt (gsi);
191 const offset_int maxobjsize = tree_to_shwi (max_object_size ());
193 /* When MAX_SIZE is greater than or equal to PTRDIFF_MAX treat
194 allocations that aren't visibly constrained as OK, otherwise
195 report them as (potentially) unbounded. */
196 alloca_type unbounded_result = (max_size < maxobjsize.to_uhwi ()
197 ? ALLOCA_UNBOUNDED : ALLOCA_OK);
199 if (!last || gimple_code (last) != GIMPLE_COND)
201 return alloca_type_and_limit (unbounded_result);
204 enum tree_code cond_code = gimple_cond_code (last);
205 if (e->flags & EDGE_TRUE_VALUE)
207 else if (e->flags & EDGE_FALSE_VALUE)
208 cond_code = invert_tree_comparison (cond_code, false);
209 else
210 return alloca_type_and_limit (unbounded_result);
212 // Check for:
213 // if (ARG .COND. N)
214 // goto <bb 3>;
215 // else
216 // goto <bb 4>;
217 // <bb 3>:
218 // alloca(ARG);
219 if ((cond_code == LE_EXPR
220 || cond_code == LT_EXPR
221 || cond_code == GT_EXPR
222 || cond_code == GE_EXPR)
223 && (gimple_cond_lhs (last) == arg
224 || gimple_cond_lhs (last) == arg_casted))
226 if (TREE_CODE (gimple_cond_rhs (last)) == INTEGER_CST)
228 tree rhs = gimple_cond_rhs (last);
229 int tst = wi::cmpu (wi::to_widest (rhs), max_size);
230 if ((cond_code == LT_EXPR && tst == -1)
231 || (cond_code == LE_EXPR && (tst == -1 || tst == 0)))
232 return alloca_type_and_limit (ALLOCA_OK);
233 else
235 // Let's not get too specific as to how large the limit
236 // may be. Someone's clearly an idiot when things
237 // degrade into "if (N > Y) alloca(N)".
238 if (cond_code == GT_EXPR || cond_code == GE_EXPR)
239 rhs = integer_zero_node;
240 return alloca_type_and_limit (ALLOCA_BOUND_MAYBE_LARGE,
241 wi::to_wide (rhs));
244 else
246 /* Analogous to ALLOCA_UNBOUNDED, when MAX_SIZE is greater
247 than or equal to PTRDIFF_MAX, treat allocations with
248 an unknown bound as OK. */
249 alloca_type unknown_result
250 = (max_size < maxobjsize.to_uhwi ()
251 ? ALLOCA_BOUND_UNKNOWN : ALLOCA_OK);
252 return alloca_type_and_limit (unknown_result);
256 // Similarly, but check for a comparison with an unknown LIMIT.
257 // if (LIMIT .COND. ARG)
258 // alloca(arg);
260 // Where LIMIT has a bound of unknown range.
262 // Note: All conditions of the form (ARG .COND. XXXX) where covered
263 // by the previous check above, so we only need to look for (LIMIT
264 // .COND. ARG) here.
265 tree limit = gimple_cond_lhs (last);
266 if ((gimple_cond_rhs (last) == arg
267 || gimple_cond_rhs (last) == arg_casted)
268 && TREE_CODE (limit) == SSA_NAME)
270 wide_int min, max;
271 value_range_type range_type = get_range_info (limit, &min, &max);
273 if (range_type == VR_UNDEFINED || range_type == VR_VARYING)
274 return alloca_type_and_limit (ALLOCA_BOUND_UNKNOWN);
276 // ?? It looks like the above `if' is unnecessary, as we never
277 // get any VR_RANGE or VR_ANTI_RANGE here. If we had a range
278 // for LIMIT, I suppose we would have taken care of it in
279 // alloca_call_type(), or handled above where we handle (ARG .COND. N).
281 // If this ever triggers, we should probably figure out why and
282 // handle it, though it is likely to be just an ALLOCA_UNBOUNDED.
283 return alloca_type_and_limit (unbounded_result);
286 return alloca_type_and_limit (unbounded_result);
289 // Return TRUE if SSA's definition is a cast from a signed type.
290 // If so, set *INVALID_CASTED_TYPE to the signed type.
292 static bool
293 cast_from_signed_p (tree ssa, tree *invalid_casted_type)
295 gimple *def = SSA_NAME_DEF_STMT (ssa);
296 if (def
297 && !gimple_nop_p (def)
298 && gimple_assign_cast_p (def)
299 && !TYPE_UNSIGNED (TREE_TYPE (gimple_assign_rhs1 (def))))
301 *invalid_casted_type = TREE_TYPE (gimple_assign_rhs1 (def));
302 return true;
304 return false;
307 // Return TRUE if X has a maximum range of MAX, basically covering the
308 // entire domain, in which case it's no range at all.
310 static bool
311 is_max (tree x, wide_int max)
313 return wi::max_value (TREE_TYPE (x)) == max;
316 // Analyze the alloca call in STMT and return the alloca type with its
317 // corresponding limit (if applicable). IS_VLA is set if the alloca
318 // call was created by the gimplifier for a VLA.
320 // If the alloca call may be too large because of a cast from a signed
321 // type to an unsigned type, set *INVALID_CASTED_TYPE to the
322 // problematic signed type.
324 static struct alloca_type_and_limit
325 alloca_call_type (gimple *stmt, bool is_vla, tree *invalid_casted_type)
327 gcc_assert (gimple_alloca_call_p (stmt));
328 bool tentative_cast_from_signed = false;
329 tree len = gimple_call_arg (stmt, 0);
330 tree len_casted = NULL;
331 wide_int min, max;
332 edge_iterator ei;
333 edge e;
335 gcc_assert (!is_vla || warn_vla_limit >= 0);
336 gcc_assert (is_vla || warn_alloca_limit >= 0);
338 // Adjust warn_alloca_max_size for VLAs, by taking the underlying
339 // type into account.
340 unsigned HOST_WIDE_INT max_size = adjusted_warn_limit (is_vla);
342 // Check for the obviously bounded case.
343 if (TREE_CODE (len) == INTEGER_CST)
345 if (tree_to_uhwi (len) > max_size)
346 return alloca_type_and_limit (ALLOCA_BOUND_DEFINITELY_LARGE,
347 wi::to_wide (len));
348 if (integer_zerop (len))
350 const offset_int maxobjsize
351 = wi::to_offset (max_object_size ());
352 alloca_type result = (max_size < maxobjsize
353 ? ALLOCA_ARG_IS_ZERO : ALLOCA_OK);
354 return alloca_type_and_limit (result);
357 return alloca_type_and_limit (ALLOCA_OK);
360 // Check the range info if available.
361 if (TREE_CODE (len) == SSA_NAME)
363 value_range_type range_type = get_range_info (len, &min, &max);
364 if (range_type == VR_RANGE)
366 if (wi::leu_p (max, max_size))
367 return alloca_type_and_limit (ALLOCA_OK);
368 else
370 // A cast may have created a range we don't care
371 // about. For instance, a cast from 16-bit to
372 // 32-bit creates a range of 0..65535, even if there
373 // is not really a determinable range in the
374 // underlying code. In this case, look through the
375 // cast at the original argument, and fall through
376 // to look at other alternatives.
378 // We only look at through the cast when its from
379 // unsigned to unsigned, otherwise we may risk
380 // looking at SIGNED_INT < N, which is clearly not
381 // what we want. In this case, we'd be interested
382 // in a VR_RANGE of [0..N].
384 // Note: None of this is perfect, and should all go
385 // away with better range information. But it gets
386 // most of the cases.
387 gimple *def = SSA_NAME_DEF_STMT (len);
388 if (gimple_assign_cast_p (def))
390 tree rhs1 = gimple_assign_rhs1 (def);
391 tree rhs1type = TREE_TYPE (rhs1);
393 // Bail if the argument type is not valid.
394 if (!INTEGRAL_TYPE_P (rhs1type))
395 return alloca_type_and_limit (ALLOCA_OK);
397 if (TYPE_UNSIGNED (rhs1type))
399 len_casted = rhs1;
400 range_type = get_range_info (len_casted, &min, &max);
403 // An unknown range or a range of the entire domain is
404 // really no range at all.
405 if (range_type == VR_VARYING
406 || (!len_casted && is_max (len, max))
407 || (len_casted && is_max (len_casted, max)))
409 // Fall through.
411 else if (range_type == VR_ANTI_RANGE)
412 return alloca_type_and_limit (ALLOCA_UNBOUNDED);
414 if (range_type != VR_VARYING)
416 const offset_int maxobjsize
417 = wi::to_offset (max_object_size ());
418 alloca_type result = (max_size < maxobjsize
419 ? ALLOCA_BOUND_MAYBE_LARGE : ALLOCA_OK);
420 return alloca_type_and_limit (result, max);
424 else if (range_type == VR_ANTI_RANGE)
426 // There may be some wrapping around going on. Catch it
427 // with this heuristic. Hopefully, this VR_ANTI_RANGE
428 // nonsense will go away, and we won't have to catch the
429 // sign conversion problems with this crap.
431 // This is here to catch things like:
432 // void foo(signed int n) {
433 // if (n < 100)
434 // alloca(n);
435 // ...
436 // }
437 if (cast_from_signed_p (len, invalid_casted_type))
439 // Unfortunately this also triggers:
441 // __SIZE_TYPE__ n = (__SIZE_TYPE__)blah;
442 // if (n < 100)
443 // alloca(n);
445 // ...which is clearly bounded. So, double check that
446 // the paths leading up to the size definitely don't
447 // have a bound.
448 tentative_cast_from_signed = true;
451 // No easily determined range and try other things.
454 // If we couldn't find anything, try a few heuristics for things we
455 // can easily determine. Check these misc cases but only accept
456 // them if all predecessors have a known bound.
457 struct alloca_type_and_limit ret = alloca_type_and_limit (ALLOCA_OK);
458 FOR_EACH_EDGE (e, ei, gimple_bb (stmt)->preds)
460 gcc_assert (!len_casted || TYPE_UNSIGNED (TREE_TYPE (len_casted)));
461 ret = alloca_call_type_by_arg (len, len_casted, e, max_size);
462 if (ret.type != ALLOCA_OK)
463 break;
466 if (ret.type != ALLOCA_OK && tentative_cast_from_signed)
467 ret = alloca_type_and_limit (ALLOCA_CAST_FROM_SIGNED);
469 // If we have a declared maximum size, we can take it into account.
470 if (ret.type != ALLOCA_OK
471 && gimple_call_builtin_p (stmt, BUILT_IN_ALLOCA_WITH_ALIGN_AND_MAX))
473 tree arg = gimple_call_arg (stmt, 2);
474 if (compare_tree_int (arg, max_size) <= 0)
475 ret = alloca_type_and_limit (ALLOCA_OK);
476 else
478 const offset_int maxobjsize
479 = wi::to_offset (max_object_size ());
480 alloca_type result = (max_size < maxobjsize
481 ? ALLOCA_BOUND_MAYBE_LARGE : ALLOCA_OK);
482 ret = alloca_type_and_limit (result, wi::to_wide (arg));
486 return ret;
489 // Return TRUE if STMT is in a loop, otherwise return FALSE.
491 static bool
492 in_loop_p (gimple *stmt)
494 basic_block bb = gimple_bb (stmt);
495 return
496 bb->loop_father && bb->loop_father->header != ENTRY_BLOCK_PTR_FOR_FN (cfun);
499 unsigned int
500 pass_walloca::execute (function *fun)
502 basic_block bb;
503 FOR_EACH_BB_FN (bb, fun)
505 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
506 gsi_next (&si))
508 gimple *stmt = gsi_stmt (si);
509 location_t loc = gimple_location (stmt);
511 if (!gimple_alloca_call_p (stmt))
512 continue;
514 const bool is_vla
515 = gimple_call_alloca_for_var_p (as_a <gcall *> (stmt));
517 // Strict mode whining for VLAs is handled by the front-end,
518 // so we can safely ignore this case. Also, ignore VLAs if
519 // the user doesn't care about them.
520 if (is_vla)
522 if (warn_vla > 0 || warn_vla_limit < 0)
523 continue;
525 else if (warn_alloca)
527 warning_at (loc, OPT_Walloca, G_("use of %<alloca%>"));
528 continue;
530 else if (warn_alloca_limit < 0)
531 continue;
533 tree invalid_casted_type = NULL;
534 struct alloca_type_and_limit t
535 = alloca_call_type (stmt, is_vla, &invalid_casted_type);
537 unsigned HOST_WIDE_INT adjusted_alloca_limit
538 = adjusted_warn_limit (false);
539 // Even if we think the alloca call is OK, make sure it's not in a
540 // loop, except for a VLA, since VLAs are guaranteed to be cleaned
541 // up when they go out of scope, including in a loop.
542 if (t.type == ALLOCA_OK && !is_vla && in_loop_p (stmt))
544 /* As in other instances, only diagnose this when the limit
545 is less than the maximum valid object size. */
546 const offset_int maxobjsize
547 = wi::to_offset (max_object_size ());
548 if (adjusted_alloca_limit < maxobjsize.to_uhwi ())
549 t = alloca_type_and_limit (ALLOCA_IN_LOOP);
552 enum opt_code wcode
553 = is_vla ? OPT_Wvla_larger_than_ : OPT_Walloca_larger_than_;
554 char buff[WIDE_INT_MAX_PRECISION / 4 + 4];
555 switch (t.type)
557 case ALLOCA_OK:
558 break;
559 case ALLOCA_BOUND_MAYBE_LARGE:
561 auto_diagnostic_group d;
562 if (warning_at (loc, wcode,
563 is_vla ? G_("argument to variable-length "
564 "array may be too large")
565 : G_("argument to %<alloca%> may be too "
566 "large"))
567 && t.limit != 0)
569 print_decu (t.limit, buff);
570 inform (loc, G_("limit is %wu bytes, but argument "
571 "may be as large as %s"),
572 is_vla ? warn_vla_limit : adjusted_alloca_limit,
573 buff);
576 break;
577 case ALLOCA_BOUND_DEFINITELY_LARGE:
579 auto_diagnostic_group d;
580 if (warning_at (loc, wcode,
581 is_vla ? G_("argument to variable-length"
582 " array is too large")
583 : G_("argument to %<alloca%> is too large"))
584 && t.limit != 0)
586 print_decu (t.limit, buff);
587 inform (loc, G_("limit is %wu bytes, but argument is %s"),
588 is_vla ? warn_vla_limit : adjusted_alloca_limit,
589 buff);
592 break;
593 case ALLOCA_BOUND_UNKNOWN:
594 warning_at (loc, wcode,
595 is_vla ? G_("variable-length array bound is unknown")
596 : G_("%<alloca%> bound is unknown"));
597 break;
598 case ALLOCA_UNBOUNDED:
599 warning_at (loc, wcode,
600 is_vla ? G_("unbounded use of variable-length array")
601 : G_("unbounded use of %<alloca%>"));
602 break;
603 case ALLOCA_IN_LOOP:
604 gcc_assert (!is_vla);
605 warning_at (loc, wcode, G_("use of %<alloca%> within a loop"));
606 break;
607 case ALLOCA_CAST_FROM_SIGNED:
608 gcc_assert (invalid_casted_type != NULL_TREE);
609 warning_at (loc, wcode,
610 is_vla ? G_("argument to variable-length array "
611 "may be too large due to "
612 "conversion from %qT to %qT")
613 : G_("argument to %<alloca%> may be too large "
614 "due to conversion from %qT to %qT"),
615 invalid_casted_type, size_type_node);
616 break;
617 case ALLOCA_ARG_IS_ZERO:
618 warning_at (loc, wcode,
619 is_vla ? G_("argument to variable-length array "
620 "is zero")
621 : G_("argument to %<alloca%> is zero"));
622 break;
623 default:
624 gcc_unreachable ();
628 return 0;
631 gimple_opt_pass *
632 make_pass_walloca (gcc::context *ctxt)
634 return new pass_walloca (ctxt);