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"
29 #include "fold-const.h"
33 #include "hard-reg-set.h"
35 #include "dominance.h"
37 #include "basic-block.h"
38 #include "tree-ssa-alias.h"
39 #include "internal-fn.h"
40 #include "gimple-expr.h"
42 #include "gimple-iterator.h"
43 #include "gimple-walk.h"
45 #include "stringpool.h"
46 #include "tree-ssanames.h"
47 #include "gimple-ssa.h"
48 #include "tree-ssa-operands.h"
49 #include "tree-phinodes.h"
50 #include "ssa-iterators.h"
52 #include "tree-pass.h"
54 #include "diagnostic-core.h"
58 static bool cfg_altered
;
60 /* Callback for walk_stmt_load_store_ops.
62 Return TRUE if OP will dereference the tree stored in DATA, FALSE
65 This routine only makes a superficial check for a dereference. Thus,
66 it must only be used if it is safe to return a false negative. */
68 check_loadstore (gimple stmt
, tree op
, tree
, void *data
)
70 if ((TREE_CODE (op
) == MEM_REF
|| TREE_CODE (op
) == TARGET_MEM_REF
)
71 && operand_equal_p (TREE_OPERAND (op
, 0), (tree
)data
, 0))
73 TREE_THIS_VOLATILE (op
) = 1;
74 TREE_SIDE_EFFECTS (op
) = 1;
81 /* Insert a trap after SI and remove SI and all statements after the trap. */
84 insert_trap_and_remove_trailing_statements (gimple_stmt_iterator
*si_p
, tree op
)
86 /* We want the NULL pointer dereference to actually occur so that
87 code that wishes to catch the signal can do so.
89 If the dereference is a load, then there's nothing to do as the
90 LHS will be a throw-away SSA_NAME and the RHS is the NULL dereference.
92 If the dereference is a store and we can easily transform the RHS,
93 then simplify the RHS to enable more DCE. Note that we require the
94 statement to be a GIMPLE_ASSIGN which filters out calls on the RHS. */
95 gimple stmt
= gsi_stmt (*si_p
);
96 if (walk_stmt_load_store_ops (stmt
, (void *)op
, NULL
, check_loadstore
)
97 && is_gimple_assign (stmt
)
98 && INTEGRAL_TYPE_P (TREE_TYPE (gimple_assign_lhs (stmt
))))
100 /* We just need to turn the RHS into zero converted to the proper
102 tree type
= TREE_TYPE (gimple_assign_lhs (stmt
));
103 gimple_assign_set_rhs_code (stmt
, INTEGER_CST
);
104 gimple_assign_set_rhs1 (stmt
, fold_convert (type
, integer_zero_node
));
109 = gimple_build_call (builtin_decl_explicit (BUILT_IN_TRAP
), 0);
110 gimple_seq seq
= NULL
;
111 gimple_seq_add_stmt (&seq
, new_stmt
);
113 /* If we had a NULL pointer dereference, then we want to insert the
114 __builtin_trap after the statement, for the other cases we want
115 to insert before the statement. */
116 if (walk_stmt_load_store_ops (stmt
, (void *)op
,
119 gsi_insert_after (si_p
, seq
, GSI_NEW_STMT
);
121 gsi_insert_before (si_p
, seq
, GSI_NEW_STMT
);
123 /* We must remove statements from the end of the block so that we
124 never reference a released SSA_NAME. */
125 basic_block bb
= gimple_bb (gsi_stmt (*si_p
));
126 for (gimple_stmt_iterator si
= gsi_last_bb (bb
);
127 gsi_stmt (si
) != gsi_stmt (*si_p
);
128 si
= gsi_last_bb (bb
))
130 stmt
= gsi_stmt (si
);
131 unlink_stmt_vdef (stmt
);
132 gsi_remove (&si
, true);
137 /* BB when reached via incoming edge E will exhibit undefined behaviour
138 at STMT. Isolate and optimize the path which exhibits undefined
141 Isolation is simple. Duplicate BB and redirect E to BB'.
143 Optimization is simple as well. Replace STMT in BB' with an
144 unconditional trap and remove all outgoing edges from BB'.
146 If RET_ZERO, do not trap, only return NULL.
148 DUPLICATE is a pre-existing duplicate, use it as BB' if it exists.
153 isolate_path (basic_block bb
, basic_block duplicate
,
154 edge e
, gimple stmt
, tree op
, bool ret_zero
)
156 gimple_stmt_iterator si
, si2
;
160 /* First duplicate BB if we have not done so already and remove all
161 the duplicate's outgoing edges as duplicate is going to unconditionally
162 trap. Removing the outgoing edges is both an optimization and ensures
163 we don't need to do any PHI node updates. */
166 duplicate
= duplicate_block (bb
, NULL
, NULL
);
168 for (ei
= ei_start (duplicate
->succs
); (e2
= ei_safe_edge (ei
)); )
172 /* Complete the isolation step by redirecting E to reach DUPLICATE. */
173 e2
= redirect_edge_and_branch (e
, duplicate
);
175 flush_pending_stmts (e2
);
178 /* There may be more than one statement in DUPLICATE which exhibits
179 undefined behaviour. Ultimately we want the first such statement in
180 DUPLCIATE so that we're able to delete as much code as possible.
182 So each time we discover undefined behaviour in DUPLICATE, search for
183 the statement which triggers undefined behaviour. If found, then
184 transform the statement into a trap and delete everything after the
185 statement. If not found, then this particular instance was subsumed by
186 an earlier instance of undefined behaviour and there's nothing to do.
188 This is made more complicated by the fact that we have STMT, which is in
189 BB rather than in DUPLICATE. So we set up two iterators, one for each
190 block and walk forward looking for STMT in BB, advancing each iterator at
193 When we find STMT the second iterator should point to STMT's equivalent in
194 duplicate. If DUPLICATE ends before STMT is found in BB, then there's
197 Ignore labels and debug statements. */
198 si
= gsi_start_nondebug_after_labels_bb (bb
);
199 si2
= gsi_start_nondebug_after_labels_bb (duplicate
);
200 while (!gsi_end_p (si
) && !gsi_end_p (si2
) && gsi_stmt (si
) != stmt
)
202 gsi_next_nondebug (&si
);
203 gsi_next_nondebug (&si2
);
206 /* This would be an indicator that we never found STMT in BB, which should
208 gcc_assert (!gsi_end_p (si
));
210 /* If we did not run to the end of DUPLICATE, then SI points to STMT and
211 SI2 points to the duplicate of STMT in DUPLICATE. Insert a trap
212 before SI2 and remove SI2 and all trailing statements. */
213 if (!gsi_end_p (si2
))
217 greturn
*ret
= as_a
<greturn
*> (gsi_stmt (si2
));
218 tree zero
= build_zero_cst (TREE_TYPE (gimple_return_retval (ret
)));
219 gimple_return_set_retval (ret
, zero
);
223 insert_trap_and_remove_trailing_statements (&si2
, op
);
229 /* Look for PHI nodes which feed statements in the same block where
230 the value of the PHI node implies the statement is erroneous.
232 For example, a NULL PHI arg value which then feeds a pointer
235 When found isolate and optimize the path associated with the PHI
236 argument feeding the erroneous statement. */
238 find_implicit_erroneous_behaviour (void)
242 FOR_EACH_BB_FN (bb
, cfun
)
246 /* Out of an abundance of caution, do not isolate paths to a
247 block where the block has any abnormal outgoing edges.
249 We might be able to relax this in the future. We have to detect
250 when we have to split the block with the NULL dereference and
251 the trap we insert. We have to preserve abnormal edges out
252 of the isolated block which in turn means updating PHIs at
253 the targets of those abnormal outgoing edges. */
254 if (has_abnormal_or_eh_outgoing_edge_p (bb
))
257 /* First look for a PHI which sets a pointer to NULL and which
258 is then dereferenced within BB. This is somewhat overly
259 conservative, but probably catches most of the interesting
261 for (si
= gsi_start_phis (bb
); !gsi_end_p (si
); gsi_next (&si
))
263 gphi
*phi
= si
.phi ();
264 tree lhs
= gimple_phi_result (phi
);
266 /* If the result is not a pointer, then there is no need to
267 examine the arguments. */
268 if (!POINTER_TYPE_P (TREE_TYPE (lhs
)))
271 /* PHI produces a pointer result. See if any of the PHI's
274 When we remove an edge, we want to reprocess the current
275 index, hence the ugly way we update I for each iteration. */
276 basic_block duplicate
= NULL
;
277 for (unsigned i
= 0, next_i
= 0;
278 i
< gimple_phi_num_args (phi
);
281 tree op
= gimple_phi_arg_def (phi
, i
);
282 edge e
= gimple_phi_arg_edge (phi
, i
);
283 imm_use_iterator iter
;
288 if (TREE_CODE (op
) == ADDR_EXPR
)
290 tree valbase
= get_base_address (TREE_OPERAND (op
, 0));
291 if ((TREE_CODE (valbase
) == VAR_DECL
292 && !is_global_var (valbase
))
293 || TREE_CODE (valbase
) == PARM_DECL
)
295 FOR_EACH_IMM_USE_STMT (use_stmt
, iter
, lhs
)
298 = dyn_cast
<greturn
*> (use_stmt
);
302 if (gimple_return_retval (return_stmt
) != lhs
)
305 if (warning_at (gimple_location (use_stmt
),
306 OPT_Wreturn_local_addr
,
307 "function may return address "
308 "of local variable"))
309 inform (DECL_SOURCE_LOCATION(valbase
),
312 if (gimple_bb (use_stmt
) == bb
)
314 duplicate
= isolate_path (bb
, duplicate
, e
,
315 use_stmt
, lhs
, true);
317 /* When we remove an incoming edge, we need to
318 reprocess the Ith element. */
326 if (!integer_zerop (op
))
329 /* We've got a NULL PHI argument. Now see if the
330 PHI's result is dereferenced within BB. */
331 FOR_EACH_IMM_USE_STMT (use_stmt
, iter
, lhs
)
333 /* We only care about uses in BB. Catching cases in
334 in other blocks would require more complex path
336 if (gimple_bb (use_stmt
) != bb
)
339 if (infer_nonnull_range (use_stmt
, lhs
,
340 flag_isolate_erroneous_paths_dereference
,
341 flag_isolate_erroneous_paths_attribute
))
344 duplicate
= isolate_path (bb
, duplicate
, e
,
345 use_stmt
, lhs
, false);
347 /* When we remove an incoming edge, we need to
348 reprocess the Ith element. */
358 /* Look for statements which exhibit erroneous behaviour. For example
359 a NULL pointer dereference.
361 When found, optimize the block containing the erroneous behaviour. */
363 find_explicit_erroneous_behaviour (void)
367 FOR_EACH_BB_FN (bb
, cfun
)
369 gimple_stmt_iterator si
;
371 /* Out of an abundance of caution, do not isolate paths to a
372 block where the block has any abnormal outgoing edges.
374 We might be able to relax this in the future. We have to detect
375 when we have to split the block with the NULL dereference and
376 the trap we insert. We have to preserve abnormal edges out
377 of the isolated block which in turn means updating PHIs at
378 the targets of those abnormal outgoing edges. */
379 if (has_abnormal_or_eh_outgoing_edge_p (bb
))
382 /* Now look at the statements in the block and see if any of
383 them explicitly dereference a NULL pointer. This happens
384 because of jump threading and constant propagation. */
385 for (si
= gsi_start_bb (bb
); !gsi_end_p (si
); gsi_next (&si
))
387 gimple stmt
= gsi_stmt (si
);
389 /* By passing null_pointer_node, we can use infer_nonnull_range
390 to detect explicit NULL pointer dereferences and other uses
391 where a non-NULL value is required. */
392 if (infer_nonnull_range (stmt
, null_pointer_node
,
393 flag_isolate_erroneous_paths_dereference
,
394 flag_isolate_erroneous_paths_attribute
))
396 insert_trap_and_remove_trailing_statements (&si
,
399 /* And finally, remove all outgoing edges from BB. */
401 for (edge_iterator ei
= ei_start (bb
->succs
);
402 (e
= ei_safe_edge (ei
)); )
405 /* Ignore any more operands on this statement and
406 continue the statement iterator (which should
407 terminate its loop immediately. */
412 /* Detect returning the address of a local variable. This only
413 becomes undefined behavior if the result is used, so we do not
414 insert a trap and only return NULL instead. */
415 if (greturn
*return_stmt
= dyn_cast
<greturn
*> (stmt
))
417 tree val
= gimple_return_retval (return_stmt
);
418 if (val
&& TREE_CODE (val
) == ADDR_EXPR
)
420 tree valbase
= get_base_address (TREE_OPERAND (val
, 0));
421 if ((TREE_CODE (valbase
) == VAR_DECL
422 && !is_global_var (valbase
))
423 || TREE_CODE (valbase
) == PARM_DECL
)
425 /* We only need it for this particular case. */
426 calculate_dominance_info (CDI_POST_DOMINATORS
);
428 bool always_executed
= dominated_by_p
429 (CDI_POST_DOMINATORS
,
430 single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun
)), bb
);
432 msg
= N_("function returns address of local variable");
434 msg
= N_("function may return address of "
437 if (warning_at (gimple_location (stmt
),
438 OPT_Wreturn_local_addr
, msg
))
439 inform (DECL_SOURCE_LOCATION(valbase
), "declared here");
440 tree zero
= build_zero_cst (TREE_TYPE (val
));
441 gimple_return_set_retval (return_stmt
, zero
);
450 /* Search the function for statements which, if executed, would cause
451 the program to fault such as a dereference of a NULL pointer.
453 Such a program can't be valid if such a statement was to execute
454 according to ISO standards.
456 We detect explicit NULL pointer dereferences as well as those implied
457 by a PHI argument having a NULL value which unconditionally flows into
458 a dereference in the same block as the PHI.
460 In the former case we replace the offending statement with an
461 unconditional trap and eliminate the outgoing edges from the statement's
462 basic block. This may expose secondary optimization opportunities.
464 In the latter case, we isolate the path(s) with the NULL PHI
465 feeding the dereference. We can then replace the offending statement
466 and eliminate the outgoing edges in the duplicate. Again, this may
467 expose secondary optimization opportunities.
469 A warning for both cases may be advisable as well.
471 Other statically detectable violations of the ISO standard could be
472 handled in a similar way, such as out-of-bounds array indexing. */
475 gimple_ssa_isolate_erroneous_paths (void)
477 initialize_original_copy_tables ();
479 /* Search all the blocks for edges which, if traversed, will
480 result in undefined behaviour. */
483 /* First handle cases where traversal of a particular edge
484 triggers undefined behaviour. These cases require creating
485 duplicate blocks and thus new SSA_NAMEs.
487 We want that process complete prior to the phase where we start
488 removing edges from the CFG. Edge removal may ultimately result in
489 removal of PHI nodes and thus releasing SSA_NAMEs back to the
492 If the two processes run in parallel we could release an SSA_NAME
493 back to the manager but we could still have dangling references
494 to the released SSA_NAME in unreachable blocks.
495 that any released names not have dangling references in the IL. */
496 find_implicit_erroneous_behaviour ();
497 find_explicit_erroneous_behaviour ();
499 free_original_copy_tables ();
501 /* We scramble the CFG and loop structures a bit, clean up
502 appropriately. We really should incrementally update the
503 loop structures, in theory it shouldn't be that hard. */
506 free_dominance_info (CDI_DOMINATORS
);
507 free_dominance_info (CDI_POST_DOMINATORS
);
508 loops_state_set (LOOPS_NEED_FIXUP
);
509 return TODO_cleanup_cfg
| TODO_update_ssa
;
515 const pass_data pass_data_isolate_erroneous_paths
=
517 GIMPLE_PASS
, /* type */
518 "isolate-paths", /* name */
519 OPTGROUP_NONE
, /* optinfo_flags */
520 TV_ISOLATE_ERRONEOUS_PATHS
, /* tv_id */
521 ( PROP_cfg
| PROP_ssa
), /* properties_required */
522 0, /* properties_provided */
523 0, /* properties_destroyed */
524 0, /* todo_flags_start */
525 0, /* todo_flags_finish */
528 class pass_isolate_erroneous_paths
: public gimple_opt_pass
531 pass_isolate_erroneous_paths (gcc::context
*ctxt
)
532 : gimple_opt_pass (pass_data_isolate_erroneous_paths
, ctxt
)
535 /* opt_pass methods: */
536 opt_pass
* clone () { return new pass_isolate_erroneous_paths (m_ctxt
); }
537 virtual bool gate (function
*)
539 /* If we do not have a suitable builtin function for the trap statement,
540 then do not perform the optimization. */
541 return (flag_isolate_erroneous_paths_dereference
!= 0
542 || flag_isolate_erroneous_paths_attribute
!= 0);
545 virtual unsigned int execute (function
*)
547 return gimple_ssa_isolate_erroneous_paths ();
550 }; // class pass_isolate_erroneous_paths
554 make_pass_isolate_erroneous_paths (gcc::context
*ctxt
)
556 return new pass_isolate_erroneous_paths (ctxt
);