1 /* Detect paths through the CFG which can never be executed in a conforming
2 program and isolate them.
4 Copyright (C) 2013-2018 Free Software Foundation, Inc.
6 This file is part of GCC.
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)
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.
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/>. */
24 #include "coretypes.h"
29 #include "tree-pass.h"
31 #include "diagnostic-core.h"
32 #include "fold-const.h"
33 #include "gimple-iterator.h"
34 #include "gimple-walk.h"
42 static bool cfg_altered
;
44 /* Callback for walk_stmt_load_store_ops.
46 Return TRUE if OP will dereference the tree stored in DATA, FALSE
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. */
52 check_loadstore (gimple
*stmt
, tree op
, tree
, void *data
)
54 if ((TREE_CODE (op
) == MEM_REF
|| TREE_CODE (op
) == TARGET_MEM_REF
)
55 && operand_equal_p (TREE_OPERAND (op
, 0), (tree
)data
, 0))
57 TREE_THIS_VOLATILE (op
) = 1;
58 TREE_SIDE_EFFECTS (op
) = 1;
65 /* Insert a trap after SI and split the block after the trap. */
68 insert_trap (gimple_stmt_iterator
*si_p
, tree op
)
70 /* We want the NULL pointer dereference to actually occur so that
71 code that wishes to catch the signal can do so.
73 If the dereference is a load, then there's nothing to do as the
74 LHS will be a throw-away SSA_NAME and the RHS is the NULL dereference.
76 If the dereference is a store and we can easily transform the RHS,
77 then simplify the RHS to enable more DCE. Note that we require the
78 statement to be a GIMPLE_ASSIGN which filters out calls on the RHS. */
79 gimple
*stmt
= gsi_stmt (*si_p
);
80 if (walk_stmt_load_store_ops (stmt
, (void *)op
, NULL
, check_loadstore
)
81 && is_gimple_assign (stmt
)
82 && INTEGRAL_TYPE_P (TREE_TYPE (gimple_assign_lhs (stmt
))))
84 /* We just need to turn the RHS into zero converted to the proper
86 tree type
= TREE_TYPE (gimple_assign_lhs (stmt
));
87 gimple_assign_set_rhs_code (stmt
, INTEGER_CST
);
88 gimple_assign_set_rhs1 (stmt
, fold_convert (type
, integer_zero_node
));
93 = gimple_build_call (builtin_decl_explicit (BUILT_IN_TRAP
), 0);
94 gimple_seq seq
= NULL
;
95 gimple_seq_add_stmt (&seq
, new_stmt
);
97 /* If we had a NULL pointer dereference, then we want to insert the
98 __builtin_trap after the statement, for the other cases we want
99 to insert before the statement. */
100 if (walk_stmt_load_store_ops (stmt
, (void *)op
,
104 gsi_insert_after (si_p
, seq
, GSI_NEW_STMT
);
105 if (stmt_ends_bb_p (stmt
))
107 split_block (gimple_bb (stmt
), stmt
);
112 gsi_insert_before (si_p
, seq
, GSI_NEW_STMT
);
114 split_block (gimple_bb (new_stmt
), new_stmt
);
115 *si_p
= gsi_for_stmt (stmt
);
118 /* BB when reached via incoming edge E will exhibit undefined behavior
119 at STMT. Isolate and optimize the path which exhibits undefined
122 Isolation is simple. Duplicate BB and redirect E to BB'.
124 Optimization is simple as well. Replace STMT in BB' with an
125 unconditional trap and remove all outgoing edges from BB'.
127 If RET_ZERO, do not trap, only return NULL.
129 DUPLICATE is a pre-existing duplicate, use it as BB' if it exists.
134 isolate_path (basic_block bb
, basic_block duplicate
,
135 edge e
, gimple
*stmt
, tree op
, bool ret_zero
)
137 gimple_stmt_iterator si
, si2
;
140 bool impossible
= true;
142 for (si
= gsi_start_bb (bb
); gsi_stmt (si
) != stmt
; gsi_next (&si
))
143 if (stmt_can_terminate_bb_p (gsi_stmt (si
)))
148 force_edge_cold (e
, impossible
);
150 /* First duplicate BB if we have not done so already and remove all
151 the duplicate's outgoing edges as duplicate is going to unconditionally
152 trap. Removing the outgoing edges is both an optimization and ensures
153 we don't need to do any PHI node updates. */
156 duplicate
= duplicate_block (bb
, NULL
, NULL
);
157 bb
->count
= profile_count::zero ();
159 for (ei
= ei_start (duplicate
->succs
); (e2
= ei_safe_edge (ei
)); )
163 /* Complete the isolation step by redirecting E to reach DUPLICATE. */
164 e2
= redirect_edge_and_branch (e
, duplicate
);
167 flush_pending_stmts (e2
);
169 /* Update profile only when redirection is really processed. */
170 bb
->count
+= e
->count ();
173 /* There may be more than one statement in DUPLICATE which exhibits
174 undefined behavior. Ultimately we want the first such statement in
175 DUPLCIATE so that we're able to delete as much code as possible.
177 So each time we discover undefined behavior in DUPLICATE, search for
178 the statement which triggers undefined behavior. If found, then
179 transform the statement into a trap and delete everything after the
180 statement. If not found, then this particular instance was subsumed by
181 an earlier instance of undefined behavior and there's nothing to do.
183 This is made more complicated by the fact that we have STMT, which is in
184 BB rather than in DUPLICATE. So we set up two iterators, one for each
185 block and walk forward looking for STMT in BB, advancing each iterator at
188 When we find STMT the second iterator should point to STMT's equivalent in
189 duplicate. If DUPLICATE ends before STMT is found in BB, then there's
192 Ignore labels and debug statements. */
193 si
= gsi_start_nondebug_after_labels_bb (bb
);
194 si2
= gsi_start_nondebug_after_labels_bb (duplicate
);
195 while (!gsi_end_p (si
) && !gsi_end_p (si2
) && gsi_stmt (si
) != stmt
)
197 gsi_next_nondebug (&si
);
198 gsi_next_nondebug (&si2
);
201 /* This would be an indicator that we never found STMT in BB, which should
203 gcc_assert (!gsi_end_p (si
));
205 /* If we did not run to the end of DUPLICATE, then SI points to STMT and
206 SI2 points to the duplicate of STMT in DUPLICATE. Insert a trap
207 before SI2 and remove SI2 and all trailing statements. */
208 if (!gsi_end_p (si2
))
212 greturn
*ret
= as_a
<greturn
*> (gsi_stmt (si2
));
213 tree zero
= build_zero_cst (TREE_TYPE (gimple_return_retval (ret
)));
214 gimple_return_set_retval (ret
, zero
);
218 insert_trap (&si2
, op
);
224 /* Return TRUE if STMT is a div/mod operation using DIVISOR as the divisor.
228 is_divmod_with_given_divisor (gimple
*stmt
, tree divisor
)
230 /* Only assignments matter. */
231 if (!is_gimple_assign (stmt
))
234 /* Check for every DIV/MOD expression. */
235 enum tree_code rhs_code
= gimple_assign_rhs_code (stmt
);
236 if (rhs_code
== TRUNC_DIV_EXPR
237 || rhs_code
== FLOOR_DIV_EXPR
238 || rhs_code
== CEIL_DIV_EXPR
239 || rhs_code
== EXACT_DIV_EXPR
240 || rhs_code
== ROUND_DIV_EXPR
241 || rhs_code
== TRUNC_MOD_EXPR
242 || rhs_code
== FLOOR_MOD_EXPR
243 || rhs_code
== CEIL_MOD_EXPR
244 || rhs_code
== ROUND_MOD_EXPR
)
246 /* Pointer equality is fine when DIVISOR is an SSA_NAME, but
247 not sufficient for constants which may have different types. */
248 if (operand_equal_p (gimple_assign_rhs2 (stmt
), divisor
, 0))
254 /* NAME is an SSA_NAME that we have already determined has the value 0 or NULL.
256 Return TRUE if USE_STMT uses NAME in a way where a 0 or NULL value results
257 in undefined behavior, FALSE otherwise
259 LOC is used for issuing diagnostics. This case represents potential
260 undefined behavior exposed by path splitting and that's reflected in
264 stmt_uses_name_in_undefined_way (gimple
*use_stmt
, tree name
, location_t loc
)
266 /* If we are working with a non pointer type, then see
267 if this use is a DIV/MOD operation using NAME as the
269 if (!POINTER_TYPE_P (TREE_TYPE (name
)))
271 if (!flag_non_call_exceptions
)
272 return is_divmod_with_given_divisor (use_stmt
, name
);
276 /* NAME is a pointer, so see if it's used in a context where it must
279 = infer_nonnull_range_by_dereference (use_stmt
, name
);
282 || infer_nonnull_range_by_attribute (use_stmt
, name
))
287 warning_at (loc
, OPT_Wnull_dereference
,
288 "potential null pointer dereference");
289 if (!flag_isolate_erroneous_paths_dereference
)
294 if (!flag_isolate_erroneous_paths_attribute
)
302 /* Return TRUE if USE_STMT uses 0 or NULL in a context which results in
303 undefined behavior, FALSE otherwise.
305 These cases are explicit in the IL. */
308 stmt_uses_0_or_null_in_undefined_way (gimple
*stmt
)
310 if (!flag_non_call_exceptions
311 && is_divmod_with_given_divisor (stmt
, integer_zero_node
))
314 /* By passing null_pointer_node, we can use the
315 infer_nonnull_range functions to detect explicit NULL
316 pointer dereferences and other uses where a non-NULL
317 value is required. */
320 = infer_nonnull_range_by_dereference (stmt
, null_pointer_node
);
322 || infer_nonnull_range_by_attribute (stmt
, null_pointer_node
))
326 location_t loc
= gimple_location (stmt
);
327 warning_at (loc
, OPT_Wnull_dereference
,
328 "null pointer dereference");
329 if (!flag_isolate_erroneous_paths_dereference
)
334 if (!flag_isolate_erroneous_paths_attribute
)
342 /* Look for PHI nodes which feed statements in the same block where
343 the value of the PHI node implies the statement is erroneous.
345 For example, a NULL PHI arg value which then feeds a pointer
348 When found isolate and optimize the path associated with the PHI
349 argument feeding the erroneous statement. */
351 find_implicit_erroneous_behavior (void)
355 FOR_EACH_BB_FN (bb
, cfun
)
359 /* Out of an abundance of caution, do not isolate paths to a
360 block where the block has any abnormal outgoing edges.
362 We might be able to relax this in the future. We have to detect
363 when we have to split the block with the NULL dereference and
364 the trap we insert. We have to preserve abnormal edges out
365 of the isolated block which in turn means updating PHIs at
366 the targets of those abnormal outgoing edges. */
367 if (has_abnormal_or_eh_outgoing_edge_p (bb
))
371 /* If BB has an edge to itself, then duplication of BB below
372 could result in reallocation of BB's PHI nodes. If that happens
373 then the loop below over the PHIs would use the old PHI and
374 thus invalid information. We don't have a good way to know
375 if a PHI has been reallocated, so just avoid isolation in
377 if (find_edge (bb
, bb
))
380 /* First look for a PHI which sets a pointer to NULL and which
381 is then dereferenced within BB. This is somewhat overly
382 conservative, but probably catches most of the interesting
384 for (si
= gsi_start_phis (bb
); !gsi_end_p (si
); gsi_next (&si
))
386 gphi
*phi
= si
.phi ();
387 tree lhs
= gimple_phi_result (phi
);
389 /* PHI produces a pointer result. See if any of the PHI's
392 When we remove an edge, we want to reprocess the current
393 index, hence the ugly way we update I for each iteration. */
394 basic_block duplicate
= NULL
;
395 for (unsigned i
= 0, next_i
= 0;
396 i
< gimple_phi_num_args (phi
);
399 tree op
= gimple_phi_arg_def (phi
, i
);
400 edge e
= gimple_phi_arg_edge (phi
, i
);
401 imm_use_iterator iter
;
406 if (TREE_CODE (op
) == ADDR_EXPR
)
408 tree valbase
= get_base_address (TREE_OPERAND (op
, 0));
409 if ((VAR_P (valbase
) && !is_global_var (valbase
))
410 || TREE_CODE (valbase
) == PARM_DECL
)
412 FOR_EACH_IMM_USE_STMT (use_stmt
, iter
, lhs
)
415 = dyn_cast
<greturn
*> (use_stmt
);
419 if (gimple_return_retval (return_stmt
) != lhs
)
422 if (warning_at (gimple_location (use_stmt
),
423 OPT_Wreturn_local_addr
,
424 "function may return address "
425 "of local variable"))
426 inform (DECL_SOURCE_LOCATION(valbase
),
429 if (gimple_bb (use_stmt
) == bb
)
431 duplicate
= isolate_path (bb
, duplicate
, e
,
432 use_stmt
, lhs
, true);
434 /* When we remove an incoming edge, we need to
435 reprocess the Ith element. */
443 if (!integer_zerop (op
))
446 location_t phi_arg_loc
= gimple_phi_arg_location (phi
, i
);
448 /* We've got a NULL PHI argument. Now see if the
449 PHI's result is dereferenced within BB. */
450 FOR_EACH_IMM_USE_STMT (use_stmt
, iter
, lhs
)
452 /* We only care about uses in BB. Catching cases in
453 in other blocks would require more complex path
455 if (gimple_bb (use_stmt
) != bb
)
458 location_t loc
= gimple_location (use_stmt
)
459 ? gimple_location (use_stmt
)
462 if (stmt_uses_name_in_undefined_way (use_stmt
, lhs
, loc
))
464 duplicate
= isolate_path (bb
, duplicate
, e
,
465 use_stmt
, lhs
, false);
467 /* When we remove an incoming edge, we need to
468 reprocess the Ith element. */
478 /* Look for statements which exhibit erroneous behavior. For example
479 a NULL pointer dereference.
481 When found, optimize the block containing the erroneous behavior. */
483 find_explicit_erroneous_behavior (void)
487 FOR_EACH_BB_FN (bb
, cfun
)
489 gimple_stmt_iterator si
;
491 /* Out of an abundance of caution, do not isolate paths to a
492 block where the block has any abnormal outgoing edges.
494 We might be able to relax this in the future. We have to detect
495 when we have to split the block with the NULL dereference and
496 the trap we insert. We have to preserve abnormal edges out
497 of the isolated block which in turn means updating PHIs at
498 the targets of those abnormal outgoing edges. */
499 if (has_abnormal_or_eh_outgoing_edge_p (bb
))
502 /* Now look at the statements in the block and see if any of
503 them explicitly dereference a NULL pointer. This happens
504 because of jump threading and constant propagation. */
505 for (si
= gsi_start_bb (bb
); !gsi_end_p (si
); gsi_next (&si
))
507 gimple
*stmt
= gsi_stmt (si
);
509 if (stmt_uses_0_or_null_in_undefined_way (stmt
))
511 insert_trap (&si
, null_pointer_node
);
512 bb
= gimple_bb (gsi_stmt (si
));
514 /* Ignore any more operands on this statement and
515 continue the statement iterator (which should
516 terminate its loop immediately. */
521 /* Detect returning the address of a local variable. This only
522 becomes undefined behavior if the result is used, so we do not
523 insert a trap and only return NULL instead. */
524 if (greturn
*return_stmt
= dyn_cast
<greturn
*> (stmt
))
526 tree val
= gimple_return_retval (return_stmt
);
527 if (val
&& TREE_CODE (val
) == ADDR_EXPR
)
529 tree valbase
= get_base_address (TREE_OPERAND (val
, 0));
530 if ((VAR_P (valbase
) && !is_global_var (valbase
))
531 || TREE_CODE (valbase
) == PARM_DECL
)
533 /* We only need it for this particular case. */
534 calculate_dominance_info (CDI_POST_DOMINATORS
);
536 bool always_executed
= dominated_by_p
537 (CDI_POST_DOMINATORS
,
538 single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun
)), bb
);
540 msg
= N_("function returns address of local variable");
542 msg
= N_("function may return address of "
545 if (warning_at (gimple_location (stmt
),
546 OPT_Wreturn_local_addr
, msg
))
547 inform (DECL_SOURCE_LOCATION(valbase
), "declared here");
548 tree zero
= build_zero_cst (TREE_TYPE (val
));
549 gimple_return_set_retval (return_stmt
, zero
);
558 /* Search the function for statements which, if executed, would cause
559 the program to fault such as a dereference of a NULL pointer.
561 Such a program can't be valid if such a statement was to execute
562 according to ISO standards.
564 We detect explicit NULL pointer dereferences as well as those implied
565 by a PHI argument having a NULL value which unconditionally flows into
566 a dereference in the same block as the PHI.
568 In the former case we replace the offending statement with an
569 unconditional trap and eliminate the outgoing edges from the statement's
570 basic block. This may expose secondary optimization opportunities.
572 In the latter case, we isolate the path(s) with the NULL PHI
573 feeding the dereference. We can then replace the offending statement
574 and eliminate the outgoing edges in the duplicate. Again, this may
575 expose secondary optimization opportunities.
577 A warning for both cases may be advisable as well.
579 Other statically detectable violations of the ISO standard could be
580 handled in a similar way, such as out-of-bounds array indexing. */
583 gimple_ssa_isolate_erroneous_paths (void)
585 initialize_original_copy_tables ();
587 /* Search all the blocks for edges which, if traversed, will
588 result in undefined behavior. */
591 /* First handle cases where traversal of a particular edge
592 triggers undefined behavior. These cases require creating
593 duplicate blocks and thus new SSA_NAMEs.
595 We want that process complete prior to the phase where we start
596 removing edges from the CFG. Edge removal may ultimately result in
597 removal of PHI nodes and thus releasing SSA_NAMEs back to the
600 If the two processes run in parallel we could release an SSA_NAME
601 back to the manager but we could still have dangling references
602 to the released SSA_NAME in unreachable blocks.
603 that any released names not have dangling references in the IL. */
604 find_implicit_erroneous_behavior ();
605 find_explicit_erroneous_behavior ();
607 free_original_copy_tables ();
609 /* We scramble the CFG and loop structures a bit, clean up
610 appropriately. We really should incrementally update the
611 loop structures, in theory it shouldn't be that hard. */
612 free_dominance_info (CDI_POST_DOMINATORS
);
615 free_dominance_info (CDI_DOMINATORS
);
616 loops_state_set (LOOPS_NEED_FIXUP
);
617 return TODO_cleanup_cfg
| TODO_update_ssa
;
623 const pass_data pass_data_isolate_erroneous_paths
=
625 GIMPLE_PASS
, /* type */
626 "isolate-paths", /* name */
627 OPTGROUP_NONE
, /* optinfo_flags */
628 TV_ISOLATE_ERRONEOUS_PATHS
, /* tv_id */
629 ( PROP_cfg
| PROP_ssa
), /* properties_required */
630 0, /* properties_provided */
631 0, /* properties_destroyed */
632 0, /* todo_flags_start */
633 0, /* todo_flags_finish */
636 class pass_isolate_erroneous_paths
: public gimple_opt_pass
639 pass_isolate_erroneous_paths (gcc::context
*ctxt
)
640 : gimple_opt_pass (pass_data_isolate_erroneous_paths
, ctxt
)
643 /* opt_pass methods: */
644 opt_pass
* clone () { return new pass_isolate_erroneous_paths (m_ctxt
); }
645 virtual bool gate (function
*)
647 /* If we do not have a suitable builtin function for the trap statement,
648 then do not perform the optimization. */
649 return (flag_isolate_erroneous_paths_dereference
!= 0
650 || flag_isolate_erroneous_paths_attribute
!= 0
651 || warn_null_dereference
);
654 virtual unsigned int execute (function
*)
656 return gimple_ssa_isolate_erroneous_paths ();
659 }; // class pass_isolate_erroneous_paths
663 make_pass_isolate_erroneous_paths (gcc::context
*ctxt
)
665 return new pass_isolate_erroneous_paths (ctxt
);