Line data Source code
1 : /* Detect paths through the CFG which can never be executed in a conforming
2 : program and isolate them.
3 :
4 : Copyright (C) 2013-2026 Free Software Foundation, Inc.
5 :
6 : This file is part of GCC.
7 :
8 : GCC is free software; you can redistribute it and/or modify
9 : it under the terms of the GNU General Public License as published by
10 : the Free Software Foundation; either version 3, or (at your option)
11 : any later version.
12 :
13 : GCC is distributed in the hope that it will be useful,
14 : but WITHOUT ANY WARRANTY; without even the implied warranty of
15 : MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 : GNU General Public License for more details.
17 :
18 : You should have received a copy of the GNU General Public License
19 : along with GCC; see the file COPYING3. If not see
20 : <http://www.gnu.org/licenses/>. */
21 :
22 : #include "config.h"
23 : #include "system.h"
24 : #include "coretypes.h"
25 : #include "backend.h"
26 : #include "tree.h"
27 : #include "gimple.h"
28 : #include "cfghooks.h"
29 : #include "tree-pass.h"
30 : #include "ssa.h"
31 : #include "diagnostic-core.h"
32 : #include "fold-const.h"
33 : #include "gimple-iterator.h"
34 : #include "gimple-walk.h"
35 : #include "tree-ssa.h"
36 : #include "cfgloop.h"
37 : #include "tree-cfg.h"
38 : #include "cfganal.h"
39 : #include "intl.h"
40 :
41 :
42 : static bool cfg_altered;
43 :
44 : /* Callback for walk_stmt_load_store_ops.
45 :
46 : Return TRUE if OP will dereference the tree stored in DATA, FALSE
47 : otherwise.
48 :
49 : This routine only makes a superficial check for a dereference. Thus,
50 : it must only be used if it is safe to return a false negative. */
51 : static bool
52 3955 : check_loadstore (gimple *stmt, tree op, tree, void *data)
53 : {
54 7910 : if ((TREE_CODE (op) == MEM_REF
55 47 : || (TREE_CODE (op) == TARGET_MEM_REF
56 0 : && !TMR_INDEX2 (op)
57 0 : && (!TMR_INDEX (op)
58 0 : || (TMR_STEP (op)
59 0 : && expr_not_equal_to (TMR_STEP (op),
60 3955 : wi::one (TYPE_PRECISION (TREE_TYPE
61 : (TMR_STEP (op)))),
62 : stmt)))))
63 3955 : && operand_equal_p (TREE_OPERAND (op, 0), (tree)data, 0))
64 : {
65 3845 : TREE_THIS_VOLATILE (op) = 1;
66 3845 : TREE_SIDE_EFFECTS (op) = 1;
67 3845 : gimple_set_has_volatile_ops (stmt, true);
68 : return true;
69 : }
70 : return false;
71 : }
72 :
73 : static vec<gimple *> *bb_split_points;
74 :
75 : /* Insert a trap after SI and split the block after the trap. */
76 :
77 : static void
78 2985 : insert_trap (gimple_stmt_iterator *si_p, tree op)
79 : {
80 : /* We want the NULL pointer dereference to actually occur so that
81 : code that wishes to catch the signal can do so.
82 :
83 : If the dereference is a load, then there's nothing to do as the
84 : LHS will be a throw-away SSA_NAME and the RHS is the NULL dereference.
85 :
86 : If the dereference is a store and we can easily transform the RHS,
87 : then simplify the RHS to enable more DCE. Note that we require the
88 : statement to be a GIMPLE_ASSIGN which filters out calls on the RHS. */
89 2985 : gimple *stmt = gsi_stmt (*si_p);
90 2985 : gassign *stmt_a = dyn_cast<gassign *> (stmt);
91 2985 : if (walk_stmt_load_store_ops (stmt, (void *)op, NULL, check_loadstore)
92 1180 : && stmt_a
93 4162 : && INTEGRAL_TYPE_P (TREE_TYPE (gimple_assign_lhs (stmt_a))))
94 : {
95 : /* We just need to turn the RHS into zero converted to the proper
96 : type. */
97 650 : tree type = TREE_TYPE (gimple_assign_lhs (stmt_a));
98 650 : gimple_assign_set_rhs_code (stmt_a, INTEGER_CST);
99 650 : gimple_assign_set_rhs1 (stmt_a, fold_convert (type, integer_zero_node));
100 650 : update_stmt (stmt_a);
101 : }
102 :
103 2985 : gcall *new_stmt
104 2985 : = gimple_build_call (builtin_decl_explicit (BUILT_IN_TRAP), 0);
105 2985 : gimple_seq seq = NULL;
106 2985 : gimple_seq_add_stmt (&seq, new_stmt);
107 :
108 : /* If we had a NULL pointer dereference, then we want to insert the
109 : __builtin_trap after the statement, for the other cases we want
110 : to insert before the statement. */
111 2985 : if (walk_stmt_load_store_ops (stmt, (void *)op,
112 : check_loadstore,
113 : check_loadstore))
114 : {
115 2665 : gsi_insert_after (si_p, seq, GSI_NEW_STMT);
116 2665 : if (stmt_ends_bb_p (stmt))
117 : {
118 1 : if (dom_info_available_p (CDI_POST_DOMINATORS))
119 0 : bb_split_points->safe_push (stmt);
120 : else
121 1 : split_block (gimple_bb (stmt), stmt);
122 1 : return;
123 : }
124 : }
125 : else
126 320 : gsi_insert_before (si_p, seq, GSI_NEW_STMT);
127 :
128 2984 : if (dom_info_available_p (CDI_POST_DOMINATORS))
129 1 : bb_split_points->safe_push (new_stmt);
130 : else
131 2983 : split_block (gimple_bb (new_stmt), new_stmt);
132 2984 : *si_p = gsi_for_stmt (stmt);
133 : }
134 :
135 : /* BB when reached via incoming edge E will exhibit undefined behavior
136 : at STMT. Isolate and optimize the path which exhibits undefined
137 : behavior.
138 :
139 : Isolation is simple. Duplicate BB and redirect E to BB'.
140 :
141 : Optimization is simple as well. Replace STMT in BB' with an
142 : unconditional trap and remove all outgoing edges from BB'.
143 :
144 : If RET_ZERO, do not trap, only return NULL.
145 :
146 : DUPLICATE is a pre-existing duplicate, use it as BB' if it exists.
147 :
148 : Return BB' (which may be equal to DUPLICATE). */
149 :
150 : ATTRIBUTE_RETURNS_NONNULL basic_block
151 2016 : isolate_path (basic_block bb, basic_block duplicate,
152 : edge e, gimple *stmt, tree op, bool ret_zero)
153 : {
154 2016 : gimple_stmt_iterator si, si2;
155 2016 : edge_iterator ei;
156 2016 : edge e2;
157 2016 : bool impossible = true;
158 2016 : profile_count count = e->count ();
159 :
160 26435 : for (si = gsi_start_bb (bb); gsi_stmt (si) != stmt; gsi_next (&si))
161 22756 : if (stmt_can_terminate_bb_p (gsi_stmt (si)))
162 : {
163 : impossible = false;
164 : break;
165 : }
166 2016 : force_edge_cold (e, impossible);
167 :
168 : /* First duplicate BB if we have not done so already and remove all
169 : the duplicate's outgoing edges as duplicate is going to unconditionally
170 : trap. Removing the outgoing edges is both an optimization and ensures
171 : we don't need to do any PHI node updates. */
172 2016 : if (!duplicate)
173 : {
174 1179 : duplicate = duplicate_block (bb, NULL, NULL);
175 1179 : duplicate->count = profile_count::zero ();
176 1179 : if (!ret_zero)
177 2908 : for (ei = ei_start (duplicate->succs); (e2 = ei_safe_edge (ei)); )
178 1793 : remove_edge (e2);
179 : }
180 2016 : bb->count -= count;
181 :
182 : /* Complete the isolation step by redirecting E to reach DUPLICATE. */
183 2016 : e2 = redirect_edge_and_branch (e, duplicate);
184 2016 : if (e2)
185 : {
186 1224 : flush_pending_stmts (e2);
187 :
188 : /* Update profile only when redirection is really processed. */
189 1224 : bb->count += e->count ();
190 : }
191 :
192 : /* There may be more than one statement in DUPLICATE which exhibits
193 : undefined behavior. Ultimately we want the first such statement in
194 : DUPLCIATE so that we're able to delete as much code as possible.
195 :
196 : So each time we discover undefined behavior in DUPLICATE, search for
197 : the statement which triggers undefined behavior. If found, then
198 : transform the statement into a trap and delete everything after the
199 : statement. If not found, then this particular instance was subsumed by
200 : an earlier instance of undefined behavior and there's nothing to do.
201 :
202 : This is made more complicated by the fact that we have STMT, which is in
203 : BB rather than in DUPLICATE. So we set up two iterators, one for each
204 : block and walk forward looking for STMT in BB, advancing each iterator at
205 : each step.
206 :
207 : When we find STMT the second iterator should point to STMT's equivalent in
208 : duplicate. If DUPLICATE ends before STMT is found in BB, then there's
209 : nothing to do.
210 :
211 : Ignore labels and debug statements. */
212 2016 : si = gsi_start_nondebug_after_labels_bb (bb);
213 2016 : si2 = gsi_start_nondebug_after_labels_bb (duplicate);
214 9907 : while (!gsi_end_p (si) && !gsi_end_p (si2) && gsi_stmt (si) != stmt)
215 : {
216 7891 : gsi_next_nondebug (&si);
217 7891 : gsi_next_nondebug (&si2);
218 : }
219 :
220 : /* This would be an indicator that we never found STMT in BB, which should
221 : never happen. */
222 2016 : gcc_assert (!gsi_end_p (si));
223 :
224 : /* If we did not run to the end of DUPLICATE, then SI points to STMT and
225 : SI2 points to the duplicate of STMT in DUPLICATE. Insert a trap
226 : before SI2 and remove SI2 and all trailing statements. */
227 2016 : if (!gsi_end_p (si2))
228 : {
229 1866 : if (ret_zero)
230 : {
231 109 : greturn *ret = as_a <greturn *> (gsi_stmt (si2));
232 109 : tree zero = build_zero_cst (TREE_TYPE (gimple_return_retval (ret)));
233 109 : gimple_return_set_retval (ret, zero);
234 109 : update_stmt (ret);
235 : }
236 : else
237 1757 : insert_trap (&si2, op);
238 : }
239 :
240 2016 : return duplicate;
241 : }
242 :
243 : /* Return TRUE if STMT is a div/mod operation using DIVISOR as the divisor.
244 : FALSE otherwise. */
245 :
246 : static bool
247 67609279 : is_divmod_with_given_divisor (gimple *stmt, tree divisor)
248 : {
249 : /* Only assignments matter. */
250 67609279 : if (!is_gimple_assign (stmt))
251 : return false;
252 :
253 : /* Check for every DIV/MOD expression. */
254 15393975 : enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
255 15393975 : if (rhs_code == TRUNC_DIV_EXPR
256 15393975 : || rhs_code == FLOOR_DIV_EXPR
257 15341181 : || rhs_code == CEIL_DIV_EXPR
258 15341181 : || rhs_code == EXACT_DIV_EXPR
259 : || rhs_code == ROUND_DIV_EXPR
260 15290406 : || rhs_code == TRUNC_MOD_EXPR
261 : || rhs_code == FLOOR_MOD_EXPR
262 15242970 : || rhs_code == CEIL_MOD_EXPR
263 15242523 : || rhs_code == ROUND_MOD_EXPR)
264 : {
265 : /* Pointer equality is fine when DIVISOR is an SSA_NAME, but
266 : not sufficient for constants which may have different types. */
267 151470 : if (operand_equal_p (gimple_assign_rhs2 (stmt), divisor, 0))
268 : return true;
269 : }
270 : return false;
271 : }
272 :
273 : /* NAME is an SSA_NAME that we have already determined has the value 0 or NULL.
274 :
275 : Return TRUE if USE_STMT uses NAME in a way where a 0 or NULL value results
276 : in undefined behavior, FALSE otherwise
277 :
278 : LOC is used for issuing diagnostics. This case represents potential
279 : undefined behavior exposed by path splitting and that's reflected in
280 : the diagnostic. */
281 :
282 : bool
283 747335 : stmt_uses_name_in_undefined_way (gimple *use_stmt, tree name, location_t loc)
284 : {
285 : /* If we are working with a non pointer type, then see
286 : if this use is a DIV/MOD operation using NAME as the
287 : divisor. */
288 747335 : if (!POINTER_TYPE_P (TREE_TYPE (name)))
289 : {
290 628445 : if (!cfun->can_throw_non_call_exceptions)
291 418786 : return is_divmod_with_given_divisor (use_stmt, name);
292 : return false;
293 : }
294 :
295 : /* NAME is a pointer, so see if it's used in a context where it must
296 : be non-NULL. */
297 118890 : bool by_dereference
298 118890 : = infer_nonnull_range_by_dereference (use_stmt, name);
299 :
300 118890 : if (by_dereference
301 118890 : || infer_nonnull_range_by_attribute (use_stmt, name))
302 : {
303 :
304 2029 : if (by_dereference)
305 : {
306 1860 : warning_at (loc, OPT_Wnull_dereference,
307 : "potential null pointer dereference");
308 1860 : if (!flag_isolate_erroneous_paths_dereference)
309 : return false;
310 : }
311 : else
312 : {
313 169 : if (!flag_isolate_erroneous_paths_attribute)
314 : return false;
315 : }
316 1862 : return true;
317 : }
318 : return false;
319 : }
320 :
321 : /* Return TRUE if USE_STMT uses 0 or NULL in a context which results in
322 : undefined behavior, FALSE otherwise.
323 :
324 : These cases are explicit in the IL. */
325 :
326 : bool
327 78166074 : stmt_uses_0_or_null_in_undefined_way (gimple *stmt)
328 : {
329 78166074 : if (!cfun->can_throw_non_call_exceptions
330 78166074 : && is_divmod_with_given_divisor (stmt, integer_zero_node))
331 : return true;
332 :
333 : /* By passing null_pointer_node, we can use the
334 : infer_nonnull_range functions to detect explicit NULL
335 : pointer dereferences and other uses where a non-NULL
336 : value is required. */
337 :
338 78165807 : bool by_dereference
339 78165807 : = infer_nonnull_range_by_dereference (stmt, null_pointer_node);
340 78165807 : if (by_dereference
341 78165807 : || infer_nonnull_range_by_attribute (stmt, null_pointer_node))
342 : {
343 1289 : if (by_dereference)
344 : {
345 960 : location_t loc = gimple_location (stmt);
346 960 : warning_at (loc, OPT_Wnull_dereference,
347 : "null pointer dereference");
348 960 : if (!flag_isolate_erroneous_paths_dereference)
349 : return false;
350 : }
351 : else
352 : {
353 329 : if (!flag_isolate_erroneous_paths_attribute)
354 : return false;
355 : }
356 961 : return true;
357 : }
358 : return false;
359 : }
360 :
361 : /* Describes the property of a return statement that may return
362 : the address of one or more local variables. The type must
363 : be safely assignable and copyable so that it can be stored in
364 : a hash_map. */
365 : class args_loc_t
366 : {
367 : public:
368 :
369 45383 : args_loc_t (): nargs (), locvec (), ptr (&ptr)
370 : {
371 45383 : locvec.create (4);
372 45383 : }
373 :
374 0 : args_loc_t (const args_loc_t &rhs)
375 0 : : nargs (rhs.nargs), locvec (rhs.locvec.copy ()), ptr (&ptr) { }
376 :
377 : args_loc_t& operator= (const args_loc_t &rhs)
378 : {
379 : nargs = rhs.nargs;
380 : locvec.release ();
381 : locvec = rhs.locvec.copy ();
382 : return *this;
383 : }
384 :
385 45383 : ~args_loc_t ()
386 : {
387 45383 : locvec.release ();
388 45383 : gcc_assert (ptr == &ptr);
389 45383 : }
390 :
391 : /* For a PHI in a return statement its number of arguments. When greater
392 : than LOCVEC.LENGTH () implies that an address of one of the locals in
393 : LOCVEC may but need not be returned by the statement. Otherwise,
394 : unless both are zero, it implies it definitely is returned. */
395 : unsigned nargs;
396 : /* The locations of local variables/alloca calls returned by the return
397 : statement. Avoid using auto_vec here since it's not safe to copy due
398 : to pr90904. */
399 : vec <location_t> locvec;
400 : void *ptr;
401 : };
402 :
403 : /* A mapping from a return statement to the locations of local variables
404 : whose addresses it may return. */
405 : typedef hash_map <gimple *, args_loc_t> locmap_t;
406 :
407 : /* Given the LOCMAP mapping, issue diagnostics about returning addresses
408 : of local variables. When MAYBE is set, all diagnostics will be of
409 : the "may return" kind. Otherwise each will be determined based on
410 : the equality of the corresponding NARGS and LOCVEC.LENGTH () values. */
411 :
412 : static void
413 987923 : diag_returned_locals (bool maybe, const locmap_t &locmap)
414 : {
415 988242 : for (locmap_t::iterator it = locmap.begin (); it != locmap.end (); ++it)
416 : {
417 319 : gimple *stmt = (*it).first;
418 319 : const args_loc_t &argsloc = (*it).second;
419 319 : location_t stmtloc = gimple_location (stmt);
420 319 : if (stmtloc == UNKNOWN_LOCATION)
421 : /* When multiple return statements are merged into one it
422 : may not have an associated location. Use the location
423 : of the closing brace instead. */
424 18 : stmtloc = cfun->function_end_locus;
425 :
426 319 : auto_diagnostic_group d;
427 319 : unsigned nargs = argsloc.locvec.length ();
428 638 : if (warning_at (stmtloc, OPT_Wreturn_local_addr,
429 151 : (maybe || argsloc.nargs > nargs
430 : ? G_("function may return address of local variable")
431 : : G_("function returns address of local variable"))))
432 : {
433 578 : for (unsigned i = 0; i != nargs; ++i)
434 322 : inform (argsloc.locvec[i], "declared here");
435 : }
436 319 : }
437 987923 : }
438 :
439 : /* Return true if EXPR is an expression of pointer type that refers
440 : to the address of one or more variables with automatic storage
441 : duration. If so, add an entry to *PLOCMAP and insert into
442 : PLOCMAP->LOCVEC the locations of the corresponding local variables
443 : whose address is returned by the RETURN_STMT (which may be set to
444 : (gimple*)-1 as a placeholder for such a statement). VISITED is
445 : a bitmap of PHI nodes already visited by recursive calls. When
446 : null, PHI expressions are not considered. */
447 :
448 : static bool
449 8778865 : is_addr_local (gimple *return_stmt, tree exp, locmap_t *plocmap,
450 : hash_set<gphi *> *visited)
451 : {
452 8778865 : if (TREE_CODE (exp) == ADDR_EXPR)
453 : {
454 106875 : tree baseaddr = get_base_address (TREE_OPERAND (exp, 0));
455 106875 : if (TREE_CODE (baseaddr) == MEM_REF)
456 23750 : return is_addr_local (return_stmt, TREE_OPERAND (baseaddr, 0),
457 23750 : plocmap, visited);
458 :
459 83125 : if ((!VAR_P (baseaddr)
460 59305 : || is_global_var (baseaddr))
461 109065 : && TREE_CODE (baseaddr) != PARM_DECL)
462 : return false;
463 :
464 33563 : args_loc_t &argsloc = plocmap->get_or_insert (return_stmt);
465 33563 : argsloc.locvec.safe_push (DECL_SOURCE_LOCATION (baseaddr));
466 33563 : return true;
467 : }
468 :
469 8671990 : if (!POINTER_TYPE_P (TREE_TYPE (exp)))
470 : return false;
471 :
472 1530071 : if (TREE_CODE (exp) == SSA_NAME)
473 : {
474 1425445 : gimple *def_stmt = SSA_NAME_DEF_STMT (exp);
475 1425445 : enum gimple_code code = gimple_code (def_stmt);
476 :
477 1425445 : if (auto def_stmt_a = dyn_cast<gassign *> (def_stmt))
478 : {
479 707903 : tree type = TREE_TYPE (gimple_assign_lhs (def_stmt_a));
480 707903 : if (POINTER_TYPE_P (type))
481 : {
482 707903 : tree_code code = gimple_assign_rhs_code (def_stmt_a);
483 707903 : tree ptr1 = NULL_TREE, ptr2 = NULL_TREE;
484 :
485 : /* Set to the number of arguments examined that should
486 : be added to ARGSLOC->NARGS to identify expressions
487 : only some but not all of whose operands refer to local
488 : addresses. */
489 707903 : unsigned nargs = 0;
490 707903 : if (code == COND_EXPR)
491 : {
492 0 : ptr1 = gimple_assign_rhs2 (def_stmt_a);
493 0 : ptr2 = gimple_assign_rhs3 (def_stmt_a);
494 : nargs = 2;
495 : }
496 : else if (code == MAX_EXPR || code == MIN_EXPR)
497 : {
498 257 : ptr1 = gimple_assign_rhs1 (def_stmt_a);
499 257 : ptr2 = gimple_assign_rhs2 (def_stmt_a);
500 : nargs = 2;
501 : }
502 : else if (code == ADDR_EXPR
503 : || code == NOP_EXPR
504 : || code == POINTER_PLUS_EXPR)
505 : /* Leave NARGS at zero and let the recursive call set it. */
506 279531 : ptr1 = gimple_assign_rhs1 (def_stmt_a);
507 :
508 : /* Avoid short-circuiting the logical OR result in case
509 : both operands refer to local variables, in which case
510 : both should be considered and identified in the warning. */
511 987691 : bool res1 = false, res2 = false;
512 279788 : if (ptr1)
513 279788 : res1 = is_addr_local (return_stmt, ptr1, plocmap, visited);
514 707903 : if (ptr2)
515 257 : res2 = is_addr_local (return_stmt, ptr2, plocmap, visited);
516 :
517 707903 : if (nargs)
518 257 : if (args_loc_t *argsloc = plocmap->get (return_stmt))
519 90 : argsloc->nargs += nargs;
520 :
521 707903 : return res1 || res2;
522 : }
523 : return false;
524 : }
525 :
526 717542 : if (code == GIMPLE_CALL
527 717542 : && gimple_call_builtin_p (def_stmt, BUILT_IN_NORMAL))
528 : {
529 : /* Handle alloca and friends that return pointers to automatic
530 : storage. */
531 15978 : tree fn = gimple_call_fndecl (def_stmt);
532 15978 : int code = DECL_FUNCTION_CODE (fn);
533 15978 : if (code == BUILT_IN_ALLOCA
534 15978 : || code == BUILT_IN_ALLOCA_WITH_ALIGN
535 13847 : || code == BUILT_IN_ALLOCA_WITH_ALIGN_AND_MAX)
536 : {
537 2131 : args_loc_t &argsloc = plocmap->get_or_insert (return_stmt);
538 2131 : argsloc.locvec.safe_push (gimple_location (def_stmt));
539 2131 : return true;
540 : }
541 :
542 13847 : if (gimple_call_num_args (def_stmt) < 1)
543 : return false;
544 :
545 : /* Recursively examine the first argument of calls to built-ins
546 : that return it. */
547 12938 : switch (code)
548 : {
549 1462 : case BUILT_IN_MEMCPY:
550 1462 : case BUILT_IN_MEMCPY_CHK:
551 1462 : case BUILT_IN_MEMPCPY:
552 1462 : case BUILT_IN_MEMPCPY_CHK:
553 1462 : case BUILT_IN_MEMMOVE:
554 1462 : case BUILT_IN_MEMMOVE_CHK:
555 1462 : case BUILT_IN_STPCPY:
556 1462 : case BUILT_IN_STPCPY_CHK:
557 1462 : case BUILT_IN_STPNCPY:
558 1462 : case BUILT_IN_STPNCPY_CHK:
559 1462 : case BUILT_IN_STRCAT:
560 1462 : case BUILT_IN_STRCAT_CHK:
561 1462 : case BUILT_IN_STRCHR:
562 1462 : case BUILT_IN_STRCPY:
563 1462 : case BUILT_IN_STRCPY_CHK:
564 1462 : case BUILT_IN_STRNCAT:
565 1462 : case BUILT_IN_STRNCAT_CHK:
566 1462 : case BUILT_IN_STRNCPY:
567 1462 : case BUILT_IN_STRNCPY_CHK:
568 1462 : case BUILT_IN_STRRCHR:
569 1462 : case BUILT_IN_STRSTR:
570 1462 : return is_addr_local (return_stmt,
571 : gimple_call_arg (def_stmt, 0),
572 1462 : plocmap, visited);
573 : default:
574 : return false;
575 : }
576 : }
577 :
578 701564 : if (code == GIMPLE_PHI && visited)
579 : {
580 32223 : gphi *phi_stmt = as_a <gphi *> (def_stmt);
581 32223 : if (visited->add (phi_stmt))
582 : return false;
583 :
584 21292 : unsigned count = 0;
585 21292 : unsigned nargs = gimple_phi_num_args (phi_stmt);
586 21292 : args_loc_t &argsloc = plocmap->get_or_insert (return_stmt);
587 : /* Bump up the number of operands examined by the number of
588 : operands of this PHI. */
589 21292 : argsloc.nargs += nargs;
590 85856 : for (unsigned i = 0; i < gimple_phi_num_args (phi_stmt); ++i)
591 : {
592 64564 : tree arg = gimple_phi_arg_def (phi_stmt, i);
593 64564 : if (is_addr_local (return_stmt, arg, plocmap, visited))
594 52 : ++count;
595 : }
596 21292 : return count != 0;
597 : }
598 : }
599 :
600 : return false;
601 : }
602 :
603 : /* Detect returning the address of a local variable in a PHI result LHS
604 : and argument ARG and PHI edge E in basic block BB. Add an entry for
605 : each use to LOCMAP, setting its NARGS member to the NARGS argument
606 : (the number of PHI operands) plus the number of arguments in binary
607 : expressions referenced by ARG. Call isolate_path for each returned
608 : address and set *ISOLATED to true if called.
609 : Return either DUPLICATE or the most recent result of isolate_path. */
610 :
611 : static basic_block
612 7858004 : handle_return_addr_local_phi_arg (basic_block bb, basic_block duplicate,
613 : tree lhs, tree arg, edge e, locmap_t &locmap,
614 : unsigned nargs, bool *isolated)
615 : {
616 : /* Use (gimple*)-1 as a temporary placeholder and replace it with
617 : the return statement below once it is known. Using a null doesn't
618 : work because it's used by the hash_map to mean "no-entry." Pass
619 : null instead of a visited_phis bitmap to avoid descending into
620 : PHIs since they are being processed by the caller. Those that
621 : remain will be checked again later. */
622 7858004 : if (!is_addr_local ((gimple*)-1, arg, &locmap, NULL))
623 : {
624 : /* Remove the placeholder regardless of success or failure. */
625 7822609 : locmap.remove ((gimple*)-1);
626 7822609 : return duplicate;
627 : }
628 :
629 35395 : const args_loc_t* const placeargsloc = locmap.get ((gimple*)-1);
630 35395 : const unsigned nlocs = placeargsloc->locvec.length ();
631 35395 : gcc_assert (nlocs);
632 :
633 : /* Add to the number of PHI arguments determined by the caller
634 : the number of operands of the expressions referenced by ARG.
635 : This lets the caller determine whether it's dealing with
636 : a "may return" or "definitely returns." */
637 35395 : nargs += placeargsloc->nargs;
638 :
639 : /* Set to true if any expressions referenced by ARG involve
640 : multiple addresses only some of which are those of locals. */
641 35395 : bool maybe = placeargsloc->nargs > placeargsloc->locvec.length ();
642 :
643 35395 : gimple *use_stmt;
644 35395 : imm_use_iterator iter;
645 :
646 : /* Look for uses of the PHI result LHS in return statements. */
647 174063 : FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
648 : {
649 138668 : greturn *return_stmt = dyn_cast <greturn *> (use_stmt);
650 138668 : if (!return_stmt)
651 138538 : continue;
652 :
653 130 : if (gimple_return_retval (return_stmt) != lhs
654 130 : || !dominated_by_p (CDI_DOMINATORS, gimple_bb (use_stmt), bb))
655 6 : continue;
656 :
657 : /* Add an entry for the return statement and the locations
658 : oof the PHI arguments obtained above to the map. */
659 124 : args_loc_t &argsloc = locmap.get_or_insert (use_stmt);
660 124 : argsloc.nargs = nargs;
661 124 : unsigned nelts = argsloc.locvec.length () + nlocs;
662 124 : argsloc.locvec.reserve (nelts);
663 124 : argsloc.locvec.splice (placeargsloc->locvec);
664 :
665 124 : if (!maybe
666 109 : && (flag_isolate_erroneous_paths_dereference
667 0 : || flag_isolate_erroneous_paths_attribute)
668 109 : && gimple_bb (use_stmt) == bb
669 233 : && (duplicate || can_duplicate_block_p (bb)))
670 : {
671 109 : duplicate = isolate_path (bb, duplicate, e,
672 : use_stmt, lhs, true);
673 :
674 : /* Let caller know the path has been isolated. */
675 109 : *isolated = true;
676 : }
677 35395 : }
678 :
679 35395 : locmap.remove ((gimple*)-1);
680 :
681 35395 : return duplicate;
682 : }
683 :
684 : /* Look for PHI nodes which feed statements in the same block where
685 : the value of the PHI node implies the statement is erroneous.
686 :
687 : For example, a NULL PHI arg value which then feeds a pointer
688 : dereference.
689 :
690 : When found isolate and optimize the path associated with the PHI
691 : argument feeding the erroneous statement. */
692 : static void
693 987676 : find_implicit_erroneous_behavior (void)
694 : {
695 987676 : locmap_t locmap;
696 :
697 987676 : basic_block bb;
698 :
699 10225926 : FOR_EACH_BB_FN (bb, cfun)
700 : {
701 9238250 : gphi_iterator si;
702 :
703 : /* Out of an abundance of caution, do not isolate paths to a
704 : block where the block has any abnormal outgoing edges.
705 :
706 : We might be able to relax this in the future. We have to detect
707 : when we have to split the block with the NULL dereference and
708 : the trap we insert. We have to preserve abnormal edges out
709 : of the isolated block which in turn means updating PHIs at
710 : the targets of those abnormal outgoing edges. */
711 9238250 : if (has_abnormal_or_eh_outgoing_edge_p (bb))
712 1012908 : continue;
713 :
714 : /* If BB has an edge to itself, then duplication of BB below
715 : could result in reallocation of BB's PHI nodes. If that happens
716 : then the loop below over the PHIs would use the old PHI and
717 : thus invalid information. We don't have a good way to know
718 : if a PHI has been reallocated, so just avoid isolation in
719 : this case. */
720 8490092 : if (find_edge (bb, bb))
721 264750 : continue;
722 :
723 : /* First look for a PHI which sets a pointer to NULL and which
724 : is then dereferenced within BB. This is somewhat overly
725 : conservative, but probably catches most of the interesting
726 : cases. */
727 8225342 : edge e;
728 19701237 : for (edge_iterator ei = ei_start (bb->preds); (e = ei_safe_edge (ei));)
729 : {
730 11475895 : auto_vec <std::pair<gimple *, tree>, 4> uses_in_bb;
731 19335775 : for (si = gsi_start_phis (bb); !gsi_end_p (si); gsi_next (&si))
732 : {
733 7859880 : gphi *phi = si.phi ();
734 7859880 : tree lhs = gimple_phi_result (phi);
735 7859880 : tree arg = gimple_phi_arg_def_from_edge (phi, e);
736 :
737 : /* PHI produces a pointer result. See if any of the PHI's
738 : arguments are NULL. */
739 7859880 : if (!integer_zerop (arg))
740 7232883 : continue;
741 :
742 626997 : location_t phi_arg_loc
743 626997 : = gimple_phi_arg_location_from_edge (phi, e);
744 :
745 626997 : imm_use_iterator iter;
746 626997 : gimple *use_stmt;
747 :
748 : /* We've got a NULL PHI argument. Now see if the
749 : PHI's result is dereferenced within BB. */
750 2164526 : FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
751 : {
752 : /* We only care about uses in BB. Catching cases in
753 : in other blocks would require more complex path
754 : isolation code. */
755 1537529 : if (gimple_bb (use_stmt) != bb)
756 790194 : continue;
757 :
758 747335 : location_t loc = (gimple_location (use_stmt)
759 747335 : ? gimple_location (use_stmt)
760 : : phi_arg_loc);
761 :
762 747335 : if (stmt_uses_name_in_undefined_way (use_stmt, lhs, loc))
763 : {
764 1907 : if (!can_duplicate_block_p (bb))
765 : break;
766 1907 : uses_in_bb.safe_push (std::make_pair (use_stmt, lhs));
767 : }
768 626997 : }
769 : }
770 11475895 : basic_block duplicate = NULL;
771 34429592 : for (auto use : uses_in_bb)
772 : {
773 1907 : duplicate = isolate_path (bb, duplicate, e,
774 : use.first, use.second, false);
775 :
776 1907 : cfg_altered = true;
777 : }
778 :
779 11475895 : if (!duplicate)
780 11474780 : ei_next (&ei);
781 11475895 : }
782 :
783 : /* Then look for a PHI which have addresses of locals that
784 : are then returned. */
785 8225342 : basic_block duplicate = NULL;
786 11349579 : for (si = gsi_start_phis (bb); !gsi_end_p (si); gsi_next (&si))
787 : {
788 3124237 : gphi *phi = si.phi ();
789 3124237 : tree lhs = gimple_phi_result (phi);
790 :
791 : /* Initial number of PHI arguments. The result may change
792 : from one iteration of the loop below to the next in
793 : response to changes to the CFG but only the initial
794 : value is stored below for use by diagnostics. */
795 3124237 : unsigned nargs = gimple_phi_num_args (phi);
796 :
797 : /* PHI produces a pointer result. See if any of the PHI's
798 : arguments are NULL.
799 :
800 : When we remove an edge, we want to reprocess the current
801 : index since the argument at that index will have been
802 : removed, hence the ugly way we update I for each iteration. */
803 3124237 : for (unsigned i = 0, next_i = 0;
804 10982241 : i < gimple_phi_num_args (phi); i = next_i)
805 : {
806 7858004 : tree arg = gimple_phi_arg_def (phi, i);
807 7858004 : edge e = gimple_phi_arg_edge (phi, i);
808 :
809 : /* Advance the argument index unless a path involving
810 : the current argument has been isolated. */
811 7858004 : next_i = i + 1;
812 7858004 : bool isolated = false;
813 7858004 : duplicate = handle_return_addr_local_phi_arg (bb, duplicate, lhs,
814 : arg, e, locmap,
815 : nargs, &isolated);
816 7858004 : if (isolated)
817 : {
818 109 : cfg_altered = true;
819 109 : next_i = i;
820 : }
821 : }
822 : }
823 :
824 : }
825 :
826 987676 : diag_returned_locals (false, locmap);
827 987676 : }
828 :
829 : /* Detect and diagnose returning the address of a local variable
830 : in RETURN_STMT in basic block BB. This only becomes undefined
831 : behavior if the result is used, so we do not insert a trap and
832 : only return NULL instead. */
833 :
834 : static void
835 962956 : warn_return_addr_local (basic_block bb, greturn *return_stmt)
836 : {
837 962956 : tree val = gimple_return_retval (return_stmt);
838 962956 : if (!val)
839 962877 : return;
840 :
841 551040 : locmap_t locmap;
842 551040 : hash_set<gphi *> visited_phis;
843 551040 : if (!is_addr_local (return_stmt, val, &locmap, &visited_phis))
844 : return;
845 :
846 : /* We only need it for this particular case. */
847 247 : calculate_dominance_info (CDI_POST_DOMINATORS);
848 :
849 247 : const args_loc_t *argsloc = locmap.get (return_stmt);
850 247 : gcc_assert (argsloc);
851 :
852 247 : bool maybe = argsloc->nargs > argsloc->locvec.length ();
853 247 : if (!maybe)
854 215 : maybe = !dominated_by_p (CDI_POST_DOMINATORS,
855 215 : single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun)), bb);
856 :
857 247 : diag_returned_locals (maybe, locmap);
858 :
859 : /* Bail if the statement isn't certain to return the address
860 : of a local (e.g., if it involves a conditional expression
861 : that wasn't transformed into a PHI or if it involves
862 : a MAX_EXPR or MIN_EXPR only one of whose operands is a local
863 : (even though such an expression isn't valid in C or has
864 : defined semantics in C++). */
865 247 : if (maybe)
866 : return;
867 :
868 : /* Do not modify code if the user only asked for warnings. */
869 79 : if (flag_isolate_erroneous_paths_dereference
870 0 : || flag_isolate_erroneous_paths_attribute)
871 : {
872 79 : tree zero = build_zero_cst (TREE_TYPE (val));
873 79 : gimple_return_set_retval (return_stmt, zero);
874 79 : update_stmt (return_stmt);
875 : }
876 551040 : }
877 :
878 : /* Look for statements which exhibit erroneous behavior. For example
879 : a NULL pointer dereference.
880 :
881 : When found, optimize the block containing the erroneous behavior. */
882 : static void
883 987676 : find_explicit_erroneous_behavior (void)
884 : {
885 987676 : basic_block bb;
886 987676 : auto_vec<gimple *> local_bb_split_points;
887 987676 : bb_split_points = &local_bb_split_points;
888 :
889 10226883 : FOR_EACH_BB_FN (bb, cfun)
890 : {
891 9239207 : gimple_stmt_iterator si;
892 :
893 : /* Out of an abundance of caution, do not isolate paths to a
894 : block where the block has any abnormal outgoing edges.
895 :
896 : We might be able to relax this in the future. We have to detect
897 : when we have to split the block with the NULL dereference and
898 : the trap we insert. We have to preserve abnormal edges out
899 : of the isolated block which in turn means updating PHIs at
900 : the targets of those abnormal outgoing edges. */
901 9239207 : if (has_abnormal_or_eh_outgoing_edge_p (bb))
902 748158 : continue;
903 :
904 : /* Now look at the statements in the block and see if any of
905 : them explicitly dereference a NULL pointer. This happens
906 : because of jump threading and constant propagation. */
907 95146944 : for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
908 : {
909 78166074 : gimple *stmt = gsi_stmt (si);
910 :
911 78166074 : if (stmt_uses_0_or_null_in_undefined_way (stmt))
912 : {
913 1228 : insert_trap (&si, null_pointer_node);
914 1228 : bb = gimple_bb (gsi_stmt (si));
915 :
916 : /* Ignore any more operands on this statement and
917 : continue the statement iterator (which should
918 : terminate its loop immediately. */
919 1228 : cfg_altered = true;
920 1228 : break;
921 : }
922 :
923 : /* Look for a return statement that returns the address
924 : of a local variable or the result of alloca. */
925 79127802 : if (greturn *return_stmt = dyn_cast <greturn *> (stmt))
926 962956 : warn_return_addr_local (bb, return_stmt);
927 : }
928 : }
929 :
930 987676 : free_dominance_info (CDI_POST_DOMINATORS);
931 :
932 : /* Perform delayed splitting of blocks. */
933 987679 : for (gimple *stmt : local_bb_split_points)
934 1 : split_block (gimple_bb (stmt), stmt);
935 :
936 987676 : bb_split_points = NULL;
937 987676 : }
938 :
939 : /* Search the function for statements which, if executed, would cause
940 : the program to fault such as a dereference of a NULL pointer.
941 :
942 : Such a program can't be valid if such a statement was to execute
943 : according to ISO standards.
944 :
945 : We detect explicit NULL pointer dereferences as well as those implied
946 : by a PHI argument having a NULL value which unconditionally flows into
947 : a dereference in the same block as the PHI.
948 :
949 : In the former case we replace the offending statement with an
950 : unconditional trap and eliminate the outgoing edges from the statement's
951 : basic block. This may expose secondary optimization opportunities.
952 :
953 : In the latter case, we isolate the path(s) with the NULL PHI
954 : feeding the dereference. We can then replace the offending statement
955 : and eliminate the outgoing edges in the duplicate. Again, this may
956 : expose secondary optimization opportunities.
957 :
958 : A warning for both cases may be advisable as well.
959 :
960 : Other statically detectable violations of the ISO standard could be
961 : handled in a similar way, such as out-of-bounds array indexing. */
962 :
963 : static unsigned int
964 987676 : gimple_ssa_isolate_erroneous_paths (void)
965 : {
966 987676 : initialize_original_copy_tables ();
967 :
968 : /* Search all the blocks for edges which, if traversed, will
969 : result in undefined behavior. */
970 987676 : cfg_altered = false;
971 :
972 : /* First handle cases where traversal of a particular edge
973 : triggers undefined behavior. These cases require creating
974 : duplicate blocks and thus new SSA_NAMEs.
975 :
976 : We want that process complete prior to the phase where we start
977 : removing edges from the CFG. Edge removal may ultimately result in
978 : removal of PHI nodes and thus releasing SSA_NAMEs back to the
979 : name manager.
980 :
981 : If the two processes run in parallel we could release an SSA_NAME
982 : back to the manager but we could still have dangling references
983 : to the released SSA_NAME in unreachable blocks.
984 : that any released names not have dangling references in the IL. */
985 987676 : find_implicit_erroneous_behavior ();
986 987676 : find_explicit_erroneous_behavior ();
987 :
988 987676 : free_original_copy_tables ();
989 :
990 : /* We scramble the CFG and loop structures a bit, clean up
991 : appropriately. We really should incrementally update the
992 : loop structures, in theory it shouldn't be that hard. */
993 987676 : if (cfg_altered)
994 : {
995 1444 : free_dominance_info (CDI_DOMINATORS);
996 1444 : loops_state_set (LOOPS_NEED_FIXUP);
997 1444 : return TODO_cleanup_cfg | TODO_update_ssa;
998 : }
999 : return 0;
1000 : }
1001 :
1002 : namespace {
1003 : const pass_data pass_data_isolate_erroneous_paths =
1004 : {
1005 : GIMPLE_PASS, /* type */
1006 : "isolate-paths", /* name */
1007 : OPTGROUP_NONE, /* optinfo_flags */
1008 : TV_ISOLATE_ERRONEOUS_PATHS, /* tv_id */
1009 : ( PROP_cfg | PROP_ssa ), /* properties_required */
1010 : 0, /* properties_provided */
1011 : 0, /* properties_destroyed */
1012 : 0, /* todo_flags_start */
1013 : 0, /* todo_flags_finish */
1014 : };
1015 :
1016 : class pass_isolate_erroneous_paths : public gimple_opt_pass
1017 : {
1018 : public:
1019 302985 : pass_isolate_erroneous_paths (gcc::context *ctxt)
1020 605970 : : gimple_opt_pass (pass_data_isolate_erroneous_paths, ctxt)
1021 : {}
1022 :
1023 : /* opt_pass methods: */
1024 0 : opt_pass * clone () final override
1025 : {
1026 0 : return new pass_isolate_erroneous_paths (m_ctxt);
1027 : }
1028 1068301 : bool gate (function *) final override
1029 : {
1030 : /* If we do not have a suitable builtin function for the trap statement,
1031 : then do not perform the optimization. */
1032 1068301 : return (flag_isolate_erroneous_paths_dereference != 0
1033 80536 : || flag_isolate_erroneous_paths_attribute != 0
1034 1148835 : || warn_null_dereference);
1035 : }
1036 :
1037 987676 : unsigned int execute (function *) final override
1038 : {
1039 987676 : return gimple_ssa_isolate_erroneous_paths ();
1040 : }
1041 :
1042 : }; // class pass_isolate_erroneous_paths
1043 : }
1044 :
1045 : gimple_opt_pass *
1046 302985 : make_pass_isolate_erroneous_paths (gcc::context *ctxt)
1047 : {
1048 302985 : return new pass_isolate_erroneous_paths (ctxt);
1049 : }
|