1 /* Detect paths through the CFG which can never be executed in a conforming
2 program and isolate them.
4 Copyright (C) 2013-2014 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"
33 #include "hard-reg-set.h"
36 #include "dominance.h"
38 #include "basic-block.h"
39 #include "tree-ssa-alias.h"
40 #include "internal-fn.h"
41 #include "gimple-expr.h"
44 #include "gimple-iterator.h"
45 #include "gimple-walk.h"
47 #include "stringpool.h"
48 #include "tree-ssanames.h"
49 #include "gimple-ssa.h"
50 #include "tree-ssa-operands.h"
51 #include "tree-phinodes.h"
52 #include "ssa-iterators.h"
54 #include "tree-pass.h"
56 #include "diagnostic-core.h"
60 static bool cfg_altered
;
62 /* Callback for walk_stmt_load_store_ops.
64 Return TRUE if OP will dereference the tree stored in DATA, FALSE
67 This routine only makes a superficial check for a dereference. Thus,
68 it must only be used if it is safe to return a false negative. */
70 check_loadstore (gimple stmt
, tree op
, tree
, void *data
)
72 if ((TREE_CODE (op
) == MEM_REF
|| TREE_CODE (op
) == TARGET_MEM_REF
)
73 && operand_equal_p (TREE_OPERAND (op
, 0), (tree
)data
, 0))
75 TREE_THIS_VOLATILE (op
) = 1;
76 TREE_SIDE_EFFECTS (op
) = 1;
83 /* Insert a trap after SI and remove SI and all statements after the trap. */
86 insert_trap_and_remove_trailing_statements (gimple_stmt_iterator
*si_p
, tree op
)
88 /* We want the NULL pointer dereference to actually occur so that
89 code that wishes to catch the signal can do so.
91 If the dereference is a load, then there's nothing to do as the
92 LHS will be a throw-away SSA_NAME and the RHS is the NULL dereference.
94 If the dereference is a store and we can easily transform the RHS,
95 then simplify the RHS to enable more DCE. Note that we require the
96 statement to be a GIMPLE_ASSIGN which filters out calls on the RHS. */
97 gimple stmt
= gsi_stmt (*si_p
);
98 if (walk_stmt_load_store_ops (stmt
, (void *)op
, NULL
, check_loadstore
)
99 && is_gimple_assign (stmt
)
100 && INTEGRAL_TYPE_P (TREE_TYPE (gimple_assign_lhs (stmt
))))
102 /* We just need to turn the RHS into zero converted to the proper
104 tree type
= TREE_TYPE (gimple_assign_lhs (stmt
));
105 gimple_assign_set_rhs_code (stmt
, INTEGER_CST
);
106 gimple_assign_set_rhs1 (stmt
, fold_convert (type
, integer_zero_node
));
111 = gimple_build_call (builtin_decl_explicit (BUILT_IN_TRAP
), 0);
112 gimple_seq seq
= NULL
;
113 gimple_seq_add_stmt (&seq
, new_stmt
);
115 /* If we had a NULL pointer dereference, then we want to insert the
116 __builtin_trap after the statement, for the other cases we want
117 to insert before the statement. */
118 if (walk_stmt_load_store_ops (stmt
, (void *)op
,
121 gsi_insert_after (si_p
, seq
, GSI_NEW_STMT
);
123 gsi_insert_before (si_p
, seq
, GSI_NEW_STMT
);
125 /* We must remove statements from the end of the block so that we
126 never reference a released SSA_NAME. */
127 basic_block bb
= gimple_bb (gsi_stmt (*si_p
));
128 for (gimple_stmt_iterator si
= gsi_last_bb (bb
);
129 gsi_stmt (si
) != gsi_stmt (*si_p
);
130 si
= gsi_last_bb (bb
))
132 stmt
= gsi_stmt (si
);
133 unlink_stmt_vdef (stmt
);
134 gsi_remove (&si
, true);
139 /* BB when reached via incoming edge E will exhibit undefined behaviour
140 at STMT. Isolate and optimize the path which exhibits undefined
143 Isolation is simple. Duplicate BB and redirect E to BB'.
145 Optimization is simple as well. Replace STMT in BB' with an
146 unconditional trap and remove all outgoing edges from BB'.
148 If RET_ZERO, do not trap, only return NULL.
150 DUPLICATE is a pre-existing duplicate, use it as BB' if it exists.
155 isolate_path (basic_block bb
, basic_block duplicate
,
156 edge e
, gimple stmt
, tree op
, bool ret_zero
)
158 gimple_stmt_iterator si
, si2
;
162 /* First duplicate BB if we have not done so already and remove all
163 the duplicate's outgoing edges as duplicate is going to unconditionally
164 trap. Removing the outgoing edges is both an optimization and ensures
165 we don't need to do any PHI node updates. */
168 duplicate
= duplicate_block (bb
, NULL
, NULL
);
170 for (ei
= ei_start (duplicate
->succs
); (e2
= ei_safe_edge (ei
)); )
174 /* Complete the isolation step by redirecting E to reach DUPLICATE. */
175 e2
= redirect_edge_and_branch (e
, duplicate
);
177 flush_pending_stmts (e2
);
180 /* There may be more than one statement in DUPLICATE which exhibits
181 undefined behaviour. Ultimately we want the first such statement in
182 DUPLCIATE so that we're able to delete as much code as possible.
184 So each time we discover undefined behaviour in DUPLICATE, search for
185 the statement which triggers undefined behaviour. If found, then
186 transform the statement into a trap and delete everything after the
187 statement. If not found, then this particular instance was subsumed by
188 an earlier instance of undefined behaviour and there's nothing to do.
190 This is made more complicated by the fact that we have STMT, which is in
191 BB rather than in DUPLICATE. So we set up two iterators, one for each
192 block and walk forward looking for STMT in BB, advancing each iterator at
195 When we find STMT the second iterator should point to STMT's equivalent in
196 duplicate. If DUPLICATE ends before STMT is found in BB, then there's
199 Ignore labels and debug statements. */
200 si
= gsi_start_nondebug_after_labels_bb (bb
);
201 si2
= gsi_start_nondebug_after_labels_bb (duplicate
);
202 while (!gsi_end_p (si
) && !gsi_end_p (si2
) && gsi_stmt (si
) != stmt
)
204 gsi_next_nondebug (&si
);
205 gsi_next_nondebug (&si2
);
208 /* This would be an indicator that we never found STMT in BB, which should
210 gcc_assert (!gsi_end_p (si
));
212 /* If we did not run to the end of DUPLICATE, then SI points to STMT and
213 SI2 points to the duplicate of STMT in DUPLICATE. Insert a trap
214 before SI2 and remove SI2 and all trailing statements. */
215 if (!gsi_end_p (si2
))
219 gimple ret
= gsi_stmt (si2
);
220 tree zero
= build_zero_cst (TREE_TYPE (gimple_return_retval (ret
)));
221 gimple_return_set_retval (ret
, zero
);
225 insert_trap_and_remove_trailing_statements (&si2
, op
);
231 /* Look for PHI nodes which feed statements in the same block where
232 the value of the PHI node implies the statement is erroneous.
234 For example, a NULL PHI arg value which then feeds a pointer
237 When found isolate and optimize the path associated with the PHI
238 argument feeding the erroneous statement. */
240 find_implicit_erroneous_behaviour (void)
244 FOR_EACH_BB_FN (bb
, cfun
)
246 gimple_stmt_iterator si
;
248 /* Out of an abundance of caution, do not isolate paths to a
249 block where the block has any abnormal outgoing edges.
251 We might be able to relax this in the future. We have to detect
252 when we have to split the block with the NULL dereference and
253 the trap we insert. We have to preserve abnormal edges out
254 of the isolated block which in turn means updating PHIs at
255 the targets of those abnormal outgoing edges. */
256 if (has_abnormal_or_eh_outgoing_edge_p (bb
))
259 /* First look for a PHI which sets a pointer to NULL and which
260 is then dereferenced within BB. This is somewhat overly
261 conservative, but probably catches most of the interesting
263 for (si
= gsi_start_phis (bb
); !gsi_end_p (si
); gsi_next (&si
))
265 gimple phi
= gsi_stmt (si
);
266 tree lhs
= gimple_phi_result (phi
);
268 /* If the result is not a pointer, then there is no need to
269 examine the arguments. */
270 if (!POINTER_TYPE_P (TREE_TYPE (lhs
)))
273 /* PHI produces a pointer result. See if any of the PHI's
276 When we remove an edge, we want to reprocess the current
277 index, hence the ugly way we update I for each iteration. */
278 basic_block duplicate
= NULL
;
279 for (unsigned i
= 0, next_i
= 0;
280 i
< gimple_phi_num_args (phi
);
283 tree op
= gimple_phi_arg_def (phi
, i
);
284 edge e
= gimple_phi_arg_edge (phi
, i
);
285 imm_use_iterator iter
;
290 if (TREE_CODE (op
) == ADDR_EXPR
)
292 tree valbase
= get_base_address (TREE_OPERAND (op
, 0));
293 if ((TREE_CODE (valbase
) == VAR_DECL
294 && !is_global_var (valbase
))
295 || TREE_CODE (valbase
) == PARM_DECL
)
297 FOR_EACH_IMM_USE_STMT (use_stmt
, iter
, lhs
)
299 if (gimple_code (use_stmt
) != GIMPLE_RETURN
300 || gimple_return_retval (use_stmt
) != lhs
)
303 if (warning_at (gimple_location (use_stmt
),
304 OPT_Wreturn_local_addr
,
305 "function may return address "
306 "of local variable"))
307 inform (DECL_SOURCE_LOCATION(valbase
),
310 if (gimple_bb (use_stmt
) == bb
)
312 duplicate
= isolate_path (bb
, duplicate
, e
,
313 use_stmt
, lhs
, true);
315 /* When we remove an incoming edge, we need to
316 reprocess the Ith element. */
324 if (!integer_zerop (op
))
327 /* We've got a NULL PHI argument. Now see if the
328 PHI's result is dereferenced within BB. */
329 FOR_EACH_IMM_USE_STMT (use_stmt
, iter
, lhs
)
331 /* We only care about uses in BB. Catching cases in
332 in other blocks would require more complex path
334 if (gimple_bb (use_stmt
) != bb
)
337 if (infer_nonnull_range (use_stmt
, lhs
,
338 flag_isolate_erroneous_paths_dereference
,
339 flag_isolate_erroneous_paths_attribute
))
342 duplicate
= isolate_path (bb
, duplicate
, e
,
343 use_stmt
, lhs
, false);
345 /* When we remove an incoming edge, we need to
346 reprocess the Ith element. */
356 /* Look for statements which exhibit erroneous behaviour. For example
357 a NULL pointer dereference.
359 When found, optimize the block containing the erroneous behaviour. */
361 find_explicit_erroneous_behaviour (void)
365 FOR_EACH_BB_FN (bb
, cfun
)
367 gimple_stmt_iterator si
;
369 /* Out of an abundance of caution, do not isolate paths to a
370 block where the block has any abnormal outgoing edges.
372 We might be able to relax this in the future. We have to detect
373 when we have to split the block with the NULL dereference and
374 the trap we insert. We have to preserve abnormal edges out
375 of the isolated block which in turn means updating PHIs at
376 the targets of those abnormal outgoing edges. */
377 if (has_abnormal_or_eh_outgoing_edge_p (bb
))
380 /* Now look at the statements in the block and see if any of
381 them explicitly dereference a NULL pointer. This happens
382 because of jump threading and constant propagation. */
383 for (si
= gsi_start_bb (bb
); !gsi_end_p (si
); gsi_next (&si
))
385 gimple stmt
= gsi_stmt (si
);
387 /* By passing null_pointer_node, we can use infer_nonnull_range
388 to detect explicit NULL pointer dereferences and other uses
389 where a non-NULL value is required. */
390 if (infer_nonnull_range (stmt
, null_pointer_node
,
391 flag_isolate_erroneous_paths_dereference
,
392 flag_isolate_erroneous_paths_attribute
))
394 insert_trap_and_remove_trailing_statements (&si
,
397 /* And finally, remove all outgoing edges from BB. */
399 for (edge_iterator ei
= ei_start (bb
->succs
);
400 (e
= ei_safe_edge (ei
)); )
403 /* Ignore any more operands on this statement and
404 continue the statement iterator (which should
405 terminate its loop immediately. */
410 /* Detect returning the address of a local variable. This only
411 becomes undefined behavior if the result is used, so we do not
412 insert a trap and only return NULL instead. */
413 if (gimple_code (stmt
) == GIMPLE_RETURN
)
415 tree val
= gimple_return_retval (stmt
);
416 if (val
&& TREE_CODE (val
) == ADDR_EXPR
)
418 tree valbase
= get_base_address (TREE_OPERAND (val
, 0));
419 if ((TREE_CODE (valbase
) == VAR_DECL
420 && !is_global_var (valbase
))
421 || TREE_CODE (valbase
) == PARM_DECL
)
423 /* We only need it for this particular case. */
424 calculate_dominance_info (CDI_POST_DOMINATORS
);
426 bool always_executed
= dominated_by_p
427 (CDI_POST_DOMINATORS
,
428 single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun
)), bb
);
430 msg
= N_("function returns address of local variable");
432 msg
= N_("function may return address of "
435 if (warning_at (gimple_location (stmt
),
436 OPT_Wreturn_local_addr
, msg
))
437 inform (DECL_SOURCE_LOCATION(valbase
), "declared here");
438 tree zero
= build_zero_cst (TREE_TYPE (val
));
439 gimple_return_set_retval (stmt
, zero
);
448 /* Search the function for statements which, if executed, would cause
449 the program to fault such as a dereference of a NULL pointer.
451 Such a program can't be valid if such a statement was to execute
452 according to ISO standards.
454 We detect explicit NULL pointer dereferences as well as those implied
455 by a PHI argument having a NULL value which unconditionally flows into
456 a dereference in the same block as the PHI.
458 In the former case we replace the offending statement with an
459 unconditional trap and eliminate the outgoing edges from the statement's
460 basic block. This may expose secondary optimization opportunities.
462 In the latter case, we isolate the path(s) with the NULL PHI
463 feeding the dereference. We can then replace the offending statement
464 and eliminate the outgoing edges in the duplicate. Again, this may
465 expose secondary optimization opportunities.
467 A warning for both cases may be advisable as well.
469 Other statically detectable violations of the ISO standard could be
470 handled in a similar way, such as out-of-bounds array indexing. */
473 gimple_ssa_isolate_erroneous_paths (void)
475 initialize_original_copy_tables ();
477 /* Search all the blocks for edges which, if traversed, will
478 result in undefined behaviour. */
481 /* First handle cases where traversal of a particular edge
482 triggers undefined behaviour. These cases require creating
483 duplicate blocks and thus new SSA_NAMEs.
485 We want that process complete prior to the phase where we start
486 removing edges from the CFG. Edge removal may ultimately result in
487 removal of PHI nodes and thus releasing SSA_NAMEs back to the
490 If the two processes run in parallel we could release an SSA_NAME
491 back to the manager but we could still have dangling references
492 to the released SSA_NAME in unreachable blocks.
493 that any released names not have dangling references in the IL. */
494 find_implicit_erroneous_behaviour ();
495 find_explicit_erroneous_behaviour ();
497 free_original_copy_tables ();
499 /* We scramble the CFG and loop structures a bit, clean up
500 appropriately. We really should incrementally update the
501 loop structures, in theory it shouldn't be that hard. */
504 free_dominance_info (CDI_DOMINATORS
);
505 free_dominance_info (CDI_POST_DOMINATORS
);
506 loops_state_set (LOOPS_NEED_FIXUP
);
507 return TODO_cleanup_cfg
| TODO_update_ssa
;
513 const pass_data pass_data_isolate_erroneous_paths
=
515 GIMPLE_PASS
, /* type */
516 "isolate-paths", /* name */
517 OPTGROUP_NONE
, /* optinfo_flags */
518 TV_ISOLATE_ERRONEOUS_PATHS
, /* tv_id */
519 ( PROP_cfg
| PROP_ssa
), /* properties_required */
520 0, /* properties_provided */
521 0, /* properties_destroyed */
522 0, /* todo_flags_start */
523 0, /* todo_flags_finish */
526 class pass_isolate_erroneous_paths
: public gimple_opt_pass
529 pass_isolate_erroneous_paths (gcc::context
*ctxt
)
530 : gimple_opt_pass (pass_data_isolate_erroneous_paths
, ctxt
)
533 /* opt_pass methods: */
534 opt_pass
* clone () { return new pass_isolate_erroneous_paths (m_ctxt
); }
535 virtual bool gate (function
*)
537 /* If we do not have a suitable builtin function for the trap statement,
538 then do not perform the optimization. */
539 return (flag_isolate_erroneous_paths_dereference
!= 0
540 || flag_isolate_erroneous_paths_attribute
!= 0);
543 virtual unsigned int execute (function
*)
545 return gimple_ssa_isolate_erroneous_paths ();
548 }; // class pass_isolate_erroneous_paths
552 make_pass_isolate_erroneous_paths (gcc::context
*ctxt
)
554 return new pass_isolate_erroneous_paths (ctxt
);