1 /* Detect paths through the CFG which can never be executed in a conforming
2 program and isolate them.
4 Copyright (C) 2013-2015 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"
30 #include "hard-reg-set.h"
33 #include "fold-const.h"
35 #include "internal-fn.h"
36 #include "gimple-iterator.h"
37 #include "gimple-walk.h"
40 #include "tree-pass.h"
42 #include "diagnostic-core.h"
46 static bool cfg_altered
;
48 /* Callback for walk_stmt_load_store_ops.
50 Return TRUE if OP will dereference the tree stored in DATA, FALSE
53 This routine only makes a superficial check for a dereference. Thus,
54 it must only be used if it is safe to return a false negative. */
56 check_loadstore (gimple stmt
, tree op
, tree
, void *data
)
58 if ((TREE_CODE (op
) == MEM_REF
|| TREE_CODE (op
) == TARGET_MEM_REF
)
59 && operand_equal_p (TREE_OPERAND (op
, 0), (tree
)data
, 0))
61 TREE_THIS_VOLATILE (op
) = 1;
62 TREE_SIDE_EFFECTS (op
) = 1;
69 /* Insert a trap after SI and split the block after the trap. */
72 insert_trap (gimple_stmt_iterator
*si_p
, tree op
)
74 /* We want the NULL pointer dereference to actually occur so that
75 code that wishes to catch the signal can do so.
77 If the dereference is a load, then there's nothing to do as the
78 LHS will be a throw-away SSA_NAME and the RHS is the NULL dereference.
80 If the dereference is a store and we can easily transform the RHS,
81 then simplify the RHS to enable more DCE. Note that we require the
82 statement to be a GIMPLE_ASSIGN which filters out calls on the RHS. */
83 gimple stmt
= gsi_stmt (*si_p
);
84 if (walk_stmt_load_store_ops (stmt
, (void *)op
, NULL
, check_loadstore
)
85 && is_gimple_assign (stmt
)
86 && INTEGRAL_TYPE_P (TREE_TYPE (gimple_assign_lhs (stmt
))))
88 /* We just need to turn the RHS into zero converted to the proper
90 tree type
= TREE_TYPE (gimple_assign_lhs (stmt
));
91 gimple_assign_set_rhs_code (stmt
, INTEGER_CST
);
92 gimple_assign_set_rhs1 (stmt
, fold_convert (type
, integer_zero_node
));
97 = gimple_build_call (builtin_decl_explicit (BUILT_IN_TRAP
), 0);
98 gimple_seq seq
= NULL
;
99 gimple_seq_add_stmt (&seq
, new_stmt
);
101 /* If we had a NULL pointer dereference, then we want to insert the
102 __builtin_trap after the statement, for the other cases we want
103 to insert before the statement. */
104 if (walk_stmt_load_store_ops (stmt
, (void *)op
,
108 gsi_insert_after (si_p
, seq
, GSI_NEW_STMT
);
109 if (stmt_ends_bb_p (stmt
))
111 split_block (gimple_bb (stmt
), stmt
);
116 gsi_insert_before (si_p
, seq
, GSI_NEW_STMT
);
118 split_block (gimple_bb (new_stmt
), new_stmt
);
119 *si_p
= gsi_for_stmt (stmt
);
122 /* BB when reached via incoming edge E will exhibit undefined behaviour
123 at STMT. Isolate and optimize the path which exhibits undefined
126 Isolation is simple. Duplicate BB and redirect E to BB'.
128 Optimization is simple as well. Replace STMT in BB' with an
129 unconditional trap and remove all outgoing edges from BB'.
131 If RET_ZERO, do not trap, only return NULL.
133 DUPLICATE is a pre-existing duplicate, use it as BB' if it exists.
138 isolate_path (basic_block bb
, basic_block duplicate
,
139 edge e
, gimple stmt
, tree op
, bool ret_zero
)
141 gimple_stmt_iterator si
, si2
;
145 /* First duplicate BB if we have not done so already and remove all
146 the duplicate's outgoing edges as duplicate is going to unconditionally
147 trap. Removing the outgoing edges is both an optimization and ensures
148 we don't need to do any PHI node updates. */
151 duplicate
= duplicate_block (bb
, NULL
, NULL
);
153 for (ei
= ei_start (duplicate
->succs
); (e2
= ei_safe_edge (ei
)); )
157 /* Complete the isolation step by redirecting E to reach DUPLICATE. */
158 e2
= redirect_edge_and_branch (e
, duplicate
);
160 flush_pending_stmts (e2
);
163 /* There may be more than one statement in DUPLICATE which exhibits
164 undefined behaviour. Ultimately we want the first such statement in
165 DUPLCIATE so that we're able to delete as much code as possible.
167 So each time we discover undefined behaviour in DUPLICATE, search for
168 the statement which triggers undefined behaviour. If found, then
169 transform the statement into a trap and delete everything after the
170 statement. If not found, then this particular instance was subsumed by
171 an earlier instance of undefined behaviour and there's nothing to do.
173 This is made more complicated by the fact that we have STMT, which is in
174 BB rather than in DUPLICATE. So we set up two iterators, one for each
175 block and walk forward looking for STMT in BB, advancing each iterator at
178 When we find STMT the second iterator should point to STMT's equivalent in
179 duplicate. If DUPLICATE ends before STMT is found in BB, then there's
182 Ignore labels and debug statements. */
183 si
= gsi_start_nondebug_after_labels_bb (bb
);
184 si2
= gsi_start_nondebug_after_labels_bb (duplicate
);
185 while (!gsi_end_p (si
) && !gsi_end_p (si2
) && gsi_stmt (si
) != stmt
)
187 gsi_next_nondebug (&si
);
188 gsi_next_nondebug (&si2
);
191 /* This would be an indicator that we never found STMT in BB, which should
193 gcc_assert (!gsi_end_p (si
));
195 /* If we did not run to the end of DUPLICATE, then SI points to STMT and
196 SI2 points to the duplicate of STMT in DUPLICATE. Insert a trap
197 before SI2 and remove SI2 and all trailing statements. */
198 if (!gsi_end_p (si2
))
202 greturn
*ret
= as_a
<greturn
*> (gsi_stmt (si2
));
203 tree zero
= build_zero_cst (TREE_TYPE (gimple_return_retval (ret
)));
204 gimple_return_set_retval (ret
, zero
);
208 insert_trap (&si2
, op
);
214 /* Look for PHI nodes which feed statements in the same block where
215 the value of the PHI node implies the statement is erroneous.
217 For example, a NULL PHI arg value which then feeds a pointer
220 When found isolate and optimize the path associated with the PHI
221 argument feeding the erroneous statement. */
223 find_implicit_erroneous_behaviour (void)
227 FOR_EACH_BB_FN (bb
, cfun
)
231 /* Out of an abundance of caution, do not isolate paths to a
232 block where the block has any abnormal outgoing edges.
234 We might be able to relax this in the future. We have to detect
235 when we have to split the block with the NULL dereference and
236 the trap we insert. We have to preserve abnormal edges out
237 of the isolated block which in turn means updating PHIs at
238 the targets of those abnormal outgoing edges. */
239 if (has_abnormal_or_eh_outgoing_edge_p (bb
))
242 /* First look for a PHI which sets a pointer to NULL and which
243 is then dereferenced within BB. This is somewhat overly
244 conservative, but probably catches most of the interesting
246 for (si
= gsi_start_phis (bb
); !gsi_end_p (si
); gsi_next (&si
))
248 gphi
*phi
= si
.phi ();
249 tree lhs
= gimple_phi_result (phi
);
251 /* If the result is not a pointer, then there is no need to
252 examine the arguments. */
253 if (!POINTER_TYPE_P (TREE_TYPE (lhs
)))
256 /* PHI produces a pointer result. See if any of the PHI's
259 When we remove an edge, we want to reprocess the current
260 index, hence the ugly way we update I for each iteration. */
261 basic_block duplicate
= NULL
;
262 for (unsigned i
= 0, next_i
= 0;
263 i
< gimple_phi_num_args (phi
);
266 tree op
= gimple_phi_arg_def (phi
, i
);
267 edge e
= gimple_phi_arg_edge (phi
, i
);
268 imm_use_iterator iter
;
273 if (TREE_CODE (op
) == ADDR_EXPR
)
275 tree valbase
= get_base_address (TREE_OPERAND (op
, 0));
276 if ((TREE_CODE (valbase
) == VAR_DECL
277 && !is_global_var (valbase
))
278 || TREE_CODE (valbase
) == PARM_DECL
)
280 FOR_EACH_IMM_USE_STMT (use_stmt
, iter
, lhs
)
283 = dyn_cast
<greturn
*> (use_stmt
);
287 if (gimple_return_retval (return_stmt
) != lhs
)
290 if (warning_at (gimple_location (use_stmt
),
291 OPT_Wreturn_local_addr
,
292 "function may return address "
293 "of local variable"))
294 inform (DECL_SOURCE_LOCATION(valbase
),
297 if (gimple_bb (use_stmt
) == bb
)
299 duplicate
= isolate_path (bb
, duplicate
, e
,
300 use_stmt
, lhs
, true);
302 /* When we remove an incoming edge, we need to
303 reprocess the Ith element. */
311 if (!integer_zerop (op
))
314 /* We've got a NULL PHI argument. Now see if the
315 PHI's result is dereferenced within BB. */
316 FOR_EACH_IMM_USE_STMT (use_stmt
, iter
, lhs
)
318 /* We only care about uses in BB. Catching cases in
319 in other blocks would require more complex path
321 if (gimple_bb (use_stmt
) != bb
)
325 = infer_nonnull_range_by_dereference (use_stmt
, lhs
);
328 || infer_nonnull_range_by_attribute (use_stmt
, lhs
))
330 location_t loc
= gimple_location (use_stmt
)
331 ? gimple_location (use_stmt
)
332 : gimple_phi_arg_location (phi
, i
);
336 warning_at (loc
, OPT_Wnull_dereference
,
337 "potential null pointer dereference");
338 if (!flag_isolate_erroneous_paths_dereference
)
343 if (!flag_isolate_erroneous_paths_attribute
)
347 duplicate
= isolate_path (bb
, duplicate
, e
,
348 use_stmt
, lhs
, false);
350 /* When we remove an incoming edge, we need to
351 reprocess the Ith element. */
361 /* Look for statements which exhibit erroneous behaviour. For example
362 a NULL pointer dereference.
364 When found, optimize the block containing the erroneous behaviour. */
366 find_explicit_erroneous_behaviour (void)
370 FOR_EACH_BB_FN (bb
, cfun
)
372 gimple_stmt_iterator si
;
374 /* Out of an abundance of caution, do not isolate paths to a
375 block where the block has any abnormal outgoing edges.
377 We might be able to relax this in the future. We have to detect
378 when we have to split the block with the NULL dereference and
379 the trap we insert. We have to preserve abnormal edges out
380 of the isolated block which in turn means updating PHIs at
381 the targets of those abnormal outgoing edges. */
382 if (has_abnormal_or_eh_outgoing_edge_p (bb
))
385 /* Now look at the statements in the block and see if any of
386 them explicitly dereference a NULL pointer. This happens
387 because of jump threading and constant propagation. */
388 for (si
= gsi_start_bb (bb
); !gsi_end_p (si
); gsi_next (&si
))
390 gimple stmt
= gsi_stmt (si
);
392 /* By passing null_pointer_node, we can use the
393 infer_nonnull_range functions to detect explicit NULL
394 pointer dereferences and other uses where a non-NULL
395 value is required. */
398 = infer_nonnull_range_by_dereference (stmt
, null_pointer_node
);
400 || infer_nonnull_range_by_attribute (stmt
, null_pointer_node
))
404 warning_at (gimple_location (stmt
), OPT_Wnull_dereference
,
405 "null pointer dereference");
406 if (!flag_isolate_erroneous_paths_dereference
)
411 if (!flag_isolate_erroneous_paths_attribute
)
415 insert_trap (&si
, null_pointer_node
);
416 bb
= gimple_bb (gsi_stmt (si
));
418 /* Ignore any more operands on this statement and
419 continue the statement iterator (which should
420 terminate its loop immediately. */
425 /* Detect returning the address of a local variable. This only
426 becomes undefined behavior if the result is used, so we do not
427 insert a trap and only return NULL instead. */
428 if (greturn
*return_stmt
= dyn_cast
<greturn
*> (stmt
))
430 tree val
= gimple_return_retval (return_stmt
);
431 if (val
&& TREE_CODE (val
) == ADDR_EXPR
)
433 tree valbase
= get_base_address (TREE_OPERAND (val
, 0));
434 if ((TREE_CODE (valbase
) == VAR_DECL
435 && !is_global_var (valbase
))
436 || TREE_CODE (valbase
) == PARM_DECL
)
438 /* We only need it for this particular case. */
439 calculate_dominance_info (CDI_POST_DOMINATORS
);
441 bool always_executed
= dominated_by_p
442 (CDI_POST_DOMINATORS
,
443 single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun
)), bb
);
445 msg
= N_("function returns address of local variable");
447 msg
= N_("function may return address of "
450 if (warning_at (gimple_location (stmt
),
451 OPT_Wreturn_local_addr
, msg
))
452 inform (DECL_SOURCE_LOCATION(valbase
), "declared here");
453 tree zero
= build_zero_cst (TREE_TYPE (val
));
454 gimple_return_set_retval (return_stmt
, zero
);
463 /* Search the function for statements which, if executed, would cause
464 the program to fault such as a dereference of a NULL pointer.
466 Such a program can't be valid if such a statement was to execute
467 according to ISO standards.
469 We detect explicit NULL pointer dereferences as well as those implied
470 by a PHI argument having a NULL value which unconditionally flows into
471 a dereference in the same block as the PHI.
473 In the former case we replace the offending statement with an
474 unconditional trap and eliminate the outgoing edges from the statement's
475 basic block. This may expose secondary optimization opportunities.
477 In the latter case, we isolate the path(s) with the NULL PHI
478 feeding the dereference. We can then replace the offending statement
479 and eliminate the outgoing edges in the duplicate. Again, this may
480 expose secondary optimization opportunities.
482 A warning for both cases may be advisable as well.
484 Other statically detectable violations of the ISO standard could be
485 handled in a similar way, such as out-of-bounds array indexing. */
488 gimple_ssa_isolate_erroneous_paths (void)
490 initialize_original_copy_tables ();
492 /* Search all the blocks for edges which, if traversed, will
493 result in undefined behaviour. */
496 /* First handle cases where traversal of a particular edge
497 triggers undefined behaviour. These cases require creating
498 duplicate blocks and thus new SSA_NAMEs.
500 We want that process complete prior to the phase where we start
501 removing edges from the CFG. Edge removal may ultimately result in
502 removal of PHI nodes and thus releasing SSA_NAMEs back to the
505 If the two processes run in parallel we could release an SSA_NAME
506 back to the manager but we could still have dangling references
507 to the released SSA_NAME in unreachable blocks.
508 that any released names not have dangling references in the IL. */
509 find_implicit_erroneous_behaviour ();
510 find_explicit_erroneous_behaviour ();
512 free_original_copy_tables ();
514 /* We scramble the CFG and loop structures a bit, clean up
515 appropriately. We really should incrementally update the
516 loop structures, in theory it shouldn't be that hard. */
517 free_dominance_info (CDI_POST_DOMINATORS
);
520 free_dominance_info (CDI_DOMINATORS
);
521 loops_state_set (LOOPS_NEED_FIXUP
);
522 return TODO_cleanup_cfg
| TODO_update_ssa
;
528 const pass_data pass_data_isolate_erroneous_paths
=
530 GIMPLE_PASS
, /* type */
531 "isolate-paths", /* name */
532 OPTGROUP_NONE
, /* optinfo_flags */
533 TV_ISOLATE_ERRONEOUS_PATHS
, /* tv_id */
534 ( PROP_cfg
| PROP_ssa
), /* properties_required */
535 0, /* properties_provided */
536 0, /* properties_destroyed */
537 0, /* todo_flags_start */
538 0, /* todo_flags_finish */
541 class pass_isolate_erroneous_paths
: public gimple_opt_pass
544 pass_isolate_erroneous_paths (gcc::context
*ctxt
)
545 : gimple_opt_pass (pass_data_isolate_erroneous_paths
, ctxt
)
548 /* opt_pass methods: */
549 opt_pass
* clone () { return new pass_isolate_erroneous_paths (m_ctxt
); }
550 virtual bool gate (function
*)
552 /* If we do not have a suitable builtin function for the trap statement,
553 then do not perform the optimization. */
554 return (flag_isolate_erroneous_paths_dereference
!= 0
555 || flag_isolate_erroneous_paths_attribute
!= 0
556 || warn_null_dereference
);
559 virtual unsigned int execute (function
*)
561 return gimple_ssa_isolate_erroneous_paths ();
564 }; // class pass_isolate_erroneous_paths
568 make_pass_isolate_erroneous_paths (gcc::context
*ctxt
)
570 return new pass_isolate_erroneous_paths (ctxt
);