* config/i386/predicates.md (general_reg_operand): Use GENERAL_REGNO_P.
[official-gcc.git] / gcc / gimple-ssa-isolate-paths.c
blobd43b5ac5abff2347f9c01deeb25ea54135f866d8
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)
11 any later version.
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/>. */
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "alias.h"
26 #include "backend.h"
27 #include "tree.h"
28 #include "gimple.h"
29 #include "hard-reg-set.h"
30 #include "ssa.h"
31 #include "options.h"
32 #include "fold-const.h"
33 #include "flags.h"
34 #include "internal-fn.h"
35 #include "gimple-iterator.h"
36 #include "gimple-walk.h"
37 #include "tree-ssa.h"
38 #include "cfgloop.h"
39 #include "tree-pass.h"
40 #include "tree-cfg.h"
41 #include "diagnostic-core.h"
42 #include "intl.h"
45 static bool cfg_altered;
47 /* Callback for walk_stmt_load_store_ops.
49 Return TRUE if OP will dereference the tree stored in DATA, FALSE
50 otherwise.
52 This routine only makes a superficial check for a dereference. Thus,
53 it must only be used if it is safe to return a false negative. */
54 static bool
55 check_loadstore (gimple stmt, tree op, tree, void *data)
57 if ((TREE_CODE (op) == MEM_REF || TREE_CODE (op) == TARGET_MEM_REF)
58 && operand_equal_p (TREE_OPERAND (op, 0), (tree)data, 0))
60 TREE_THIS_VOLATILE (op) = 1;
61 TREE_SIDE_EFFECTS (op) = 1;
62 update_stmt (stmt);
63 return true;
65 return false;
68 /* Insert a trap after SI and remove SI and all statements after the trap. */
70 static void
71 insert_trap_and_remove_trailing_statements (gimple_stmt_iterator *si_p, tree op)
73 /* We want the NULL pointer dereference to actually occur so that
74 code that wishes to catch the signal can do so.
76 If the dereference is a load, then there's nothing to do as the
77 LHS will be a throw-away SSA_NAME and the RHS is the NULL dereference.
79 If the dereference is a store and we can easily transform the RHS,
80 then simplify the RHS to enable more DCE. Note that we require the
81 statement to be a GIMPLE_ASSIGN which filters out calls on the RHS. */
82 gimple stmt = gsi_stmt (*si_p);
83 if (walk_stmt_load_store_ops (stmt, (void *)op, NULL, check_loadstore)
84 && is_gimple_assign (stmt)
85 && INTEGRAL_TYPE_P (TREE_TYPE (gimple_assign_lhs (stmt))))
87 /* We just need to turn the RHS into zero converted to the proper
88 type. */
89 tree type = TREE_TYPE (gimple_assign_lhs (stmt));
90 gimple_assign_set_rhs_code (stmt, INTEGER_CST);
91 gimple_assign_set_rhs1 (stmt, fold_convert (type, integer_zero_node));
92 update_stmt (stmt);
95 gcall *new_stmt
96 = gimple_build_call (builtin_decl_explicit (BUILT_IN_TRAP), 0);
97 gimple_seq seq = NULL;
98 gimple_seq_add_stmt (&seq, new_stmt);
100 /* If we had a NULL pointer dereference, then we want to insert the
101 __builtin_trap after the statement, for the other cases we want
102 to insert before the statement. */
103 if (walk_stmt_load_store_ops (stmt, (void *)op,
104 check_loadstore,
105 check_loadstore))
107 gsi_insert_after (si_p, seq, GSI_NEW_STMT);
108 if (stmt_ends_bb_p (stmt))
110 split_block (gimple_bb (stmt), stmt);
111 return;
114 else
115 gsi_insert_before (si_p, seq, GSI_NEW_STMT);
117 /* We must remove statements from the end of the block so that we
118 never reference a released SSA_NAME. */
119 basic_block bb = gimple_bb (gsi_stmt (*si_p));
120 for (gimple_stmt_iterator si = gsi_last_bb (bb);
121 gsi_stmt (si) != gsi_stmt (*si_p);
122 si = gsi_last_bb (bb))
124 stmt = gsi_stmt (si);
125 unlink_stmt_vdef (stmt);
126 gsi_remove (&si, true);
127 release_defs (stmt);
131 /* BB when reached via incoming edge E will exhibit undefined behaviour
132 at STMT. Isolate and optimize the path which exhibits undefined
133 behaviour.
135 Isolation is simple. Duplicate BB and redirect E to BB'.
137 Optimization is simple as well. Replace STMT in BB' with an
138 unconditional trap and remove all outgoing edges from BB'.
140 If RET_ZERO, do not trap, only return NULL.
142 DUPLICATE is a pre-existing duplicate, use it as BB' if it exists.
144 Return BB'. */
146 basic_block
147 isolate_path (basic_block bb, basic_block duplicate,
148 edge e, gimple stmt, tree op, bool ret_zero)
150 gimple_stmt_iterator si, si2;
151 edge_iterator ei;
152 edge e2;
154 /* First duplicate BB if we have not done so already and remove all
155 the duplicate's outgoing edges as duplicate is going to unconditionally
156 trap. Removing the outgoing edges is both an optimization and ensures
157 we don't need to do any PHI node updates. */
158 if (!duplicate)
160 duplicate = duplicate_block (bb, NULL, NULL);
161 if (!ret_zero)
162 for (ei = ei_start (duplicate->succs); (e2 = ei_safe_edge (ei)); )
163 remove_edge (e2);
166 /* Complete the isolation step by redirecting E to reach DUPLICATE. */
167 e2 = redirect_edge_and_branch (e, duplicate);
168 if (e2)
169 flush_pending_stmts (e2);
172 /* There may be more than one statement in DUPLICATE which exhibits
173 undefined behaviour. Ultimately we want the first such statement in
174 DUPLCIATE so that we're able to delete as much code as possible.
176 So each time we discover undefined behaviour in DUPLICATE, search for
177 the statement which triggers undefined behaviour. If found, then
178 transform the statement into a trap and delete everything after the
179 statement. If not found, then this particular instance was subsumed by
180 an earlier instance of undefined behaviour and there's nothing to do.
182 This is made more complicated by the fact that we have STMT, which is in
183 BB rather than in DUPLICATE. So we set up two iterators, one for each
184 block and walk forward looking for STMT in BB, advancing each iterator at
185 each step.
187 When we find STMT the second iterator should point to STMT's equivalent in
188 duplicate. If DUPLICATE ends before STMT is found in BB, then there's
189 nothing to do.
191 Ignore labels and debug statements. */
192 si = gsi_start_nondebug_after_labels_bb (bb);
193 si2 = gsi_start_nondebug_after_labels_bb (duplicate);
194 while (!gsi_end_p (si) && !gsi_end_p (si2) && gsi_stmt (si) != stmt)
196 gsi_next_nondebug (&si);
197 gsi_next_nondebug (&si2);
200 /* This would be an indicator that we never found STMT in BB, which should
201 never happen. */
202 gcc_assert (!gsi_end_p (si));
204 /* If we did not run to the end of DUPLICATE, then SI points to STMT and
205 SI2 points to the duplicate of STMT in DUPLICATE. Insert a trap
206 before SI2 and remove SI2 and all trailing statements. */
207 if (!gsi_end_p (si2))
209 if (ret_zero)
211 greturn *ret = as_a <greturn *> (gsi_stmt (si2));
212 tree zero = build_zero_cst (TREE_TYPE (gimple_return_retval (ret)));
213 gimple_return_set_retval (ret, zero);
214 update_stmt (ret);
216 else
217 insert_trap_and_remove_trailing_statements (&si2, op);
220 return duplicate;
223 /* Look for PHI nodes which feed statements in the same block where
224 the value of the PHI node implies the statement is erroneous.
226 For example, a NULL PHI arg value which then feeds a pointer
227 dereference.
229 When found isolate and optimize the path associated with the PHI
230 argument feeding the erroneous statement. */
231 static void
232 find_implicit_erroneous_behaviour (void)
234 basic_block bb;
236 FOR_EACH_BB_FN (bb, cfun)
238 gphi_iterator si;
240 /* Out of an abundance of caution, do not isolate paths to a
241 block where the block has any abnormal outgoing edges.
243 We might be able to relax this in the future. We have to detect
244 when we have to split the block with the NULL dereference and
245 the trap we insert. We have to preserve abnormal edges out
246 of the isolated block which in turn means updating PHIs at
247 the targets of those abnormal outgoing edges. */
248 if (has_abnormal_or_eh_outgoing_edge_p (bb))
249 continue;
251 /* First look for a PHI which sets a pointer to NULL and which
252 is then dereferenced within BB. This is somewhat overly
253 conservative, but probably catches most of the interesting
254 cases. */
255 for (si = gsi_start_phis (bb); !gsi_end_p (si); gsi_next (&si))
257 gphi *phi = si.phi ();
258 tree lhs = gimple_phi_result (phi);
260 /* If the result is not a pointer, then there is no need to
261 examine the arguments. */
262 if (!POINTER_TYPE_P (TREE_TYPE (lhs)))
263 continue;
265 /* PHI produces a pointer result. See if any of the PHI's
266 arguments are NULL.
268 When we remove an edge, we want to reprocess the current
269 index, hence the ugly way we update I for each iteration. */
270 basic_block duplicate = NULL;
271 for (unsigned i = 0, next_i = 0;
272 i < gimple_phi_num_args (phi);
273 i = next_i)
275 tree op = gimple_phi_arg_def (phi, i);
276 edge e = gimple_phi_arg_edge (phi, i);
277 imm_use_iterator iter;
278 gimple use_stmt;
280 next_i = i + 1;
282 if (TREE_CODE (op) == ADDR_EXPR)
284 tree valbase = get_base_address (TREE_OPERAND (op, 0));
285 if ((TREE_CODE (valbase) == VAR_DECL
286 && !is_global_var (valbase))
287 || TREE_CODE (valbase) == PARM_DECL)
289 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
291 greturn *return_stmt
292 = dyn_cast <greturn *> (use_stmt);
293 if (!return_stmt)
294 continue;
296 if (gimple_return_retval (return_stmt) != lhs)
297 continue;
299 if (warning_at (gimple_location (use_stmt),
300 OPT_Wreturn_local_addr,
301 "function may return address "
302 "of local variable"))
303 inform (DECL_SOURCE_LOCATION(valbase),
304 "declared here");
306 if (gimple_bb (use_stmt) == bb)
308 duplicate = isolate_path (bb, duplicate, e,
309 use_stmt, lhs, true);
311 /* When we remove an incoming edge, we need to
312 reprocess the Ith element. */
313 next_i = i;
314 cfg_altered = true;
320 if (!integer_zerop (op))
321 continue;
323 /* We've got a NULL PHI argument. Now see if the
324 PHI's result is dereferenced within BB. */
325 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
327 /* We only care about uses in BB. Catching cases in
328 in other blocks would require more complex path
329 isolation code. */
330 if (gimple_bb (use_stmt) != bb)
331 continue;
333 if (infer_nonnull_range (use_stmt, lhs,
334 flag_isolate_erroneous_paths_dereference,
335 flag_isolate_erroneous_paths_attribute))
338 duplicate = isolate_path (bb, duplicate, e,
339 use_stmt, lhs, false);
341 /* When we remove an incoming edge, we need to
342 reprocess the Ith element. */
343 next_i = i;
344 cfg_altered = true;
352 /* Look for statements which exhibit erroneous behaviour. For example
353 a NULL pointer dereference.
355 When found, optimize the block containing the erroneous behaviour. */
356 static void
357 find_explicit_erroneous_behaviour (void)
359 basic_block bb;
361 FOR_EACH_BB_FN (bb, cfun)
363 gimple_stmt_iterator si;
365 /* Out of an abundance of caution, do not isolate paths to a
366 block where the block has any abnormal outgoing edges.
368 We might be able to relax this in the future. We have to detect
369 when we have to split the block with the NULL dereference and
370 the trap we insert. We have to preserve abnormal edges out
371 of the isolated block which in turn means updating PHIs at
372 the targets of those abnormal outgoing edges. */
373 if (has_abnormal_or_eh_outgoing_edge_p (bb))
374 continue;
376 /* Now look at the statements in the block and see if any of
377 them explicitly dereference a NULL pointer. This happens
378 because of jump threading and constant propagation. */
379 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
381 gimple stmt = gsi_stmt (si);
383 /* By passing null_pointer_node, we can use infer_nonnull_range
384 to detect explicit NULL pointer dereferences and other uses
385 where a non-NULL value is required. */
386 if (infer_nonnull_range (stmt, null_pointer_node,
387 flag_isolate_erroneous_paths_dereference,
388 flag_isolate_erroneous_paths_attribute))
390 insert_trap_and_remove_trailing_statements (&si,
391 null_pointer_node);
393 /* And finally, remove all outgoing edges from BB. */
394 edge e;
395 for (edge_iterator ei = ei_start (bb->succs);
396 (e = ei_safe_edge (ei)); )
397 remove_edge (e);
399 /* Ignore any more operands on this statement and
400 continue the statement iterator (which should
401 terminate its loop immediately. */
402 cfg_altered = true;
403 break;
406 /* Detect returning the address of a local variable. This only
407 becomes undefined behavior if the result is used, so we do not
408 insert a trap and only return NULL instead. */
409 if (greturn *return_stmt = dyn_cast <greturn *> (stmt))
411 tree val = gimple_return_retval (return_stmt);
412 if (val && TREE_CODE (val) == ADDR_EXPR)
414 tree valbase = get_base_address (TREE_OPERAND (val, 0));
415 if ((TREE_CODE (valbase) == VAR_DECL
416 && !is_global_var (valbase))
417 || TREE_CODE (valbase) == PARM_DECL)
419 /* We only need it for this particular case. */
420 calculate_dominance_info (CDI_POST_DOMINATORS);
421 const char* msg;
422 bool always_executed = dominated_by_p
423 (CDI_POST_DOMINATORS,
424 single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun)), bb);
425 if (always_executed)
426 msg = N_("function returns address of local variable");
427 else
428 msg = N_("function may return address of "
429 "local variable");
431 if (warning_at (gimple_location (stmt),
432 OPT_Wreturn_local_addr, msg))
433 inform (DECL_SOURCE_LOCATION(valbase), "declared here");
434 tree zero = build_zero_cst (TREE_TYPE (val));
435 gimple_return_set_retval (return_stmt, zero);
436 update_stmt (stmt);
444 /* Search the function for statements which, if executed, would cause
445 the program to fault such as a dereference of a NULL pointer.
447 Such a program can't be valid if such a statement was to execute
448 according to ISO standards.
450 We detect explicit NULL pointer dereferences as well as those implied
451 by a PHI argument having a NULL value which unconditionally flows into
452 a dereference in the same block as the PHI.
454 In the former case we replace the offending statement with an
455 unconditional trap and eliminate the outgoing edges from the statement's
456 basic block. This may expose secondary optimization opportunities.
458 In the latter case, we isolate the path(s) with the NULL PHI
459 feeding the dereference. We can then replace the offending statement
460 and eliminate the outgoing edges in the duplicate. Again, this may
461 expose secondary optimization opportunities.
463 A warning for both cases may be advisable as well.
465 Other statically detectable violations of the ISO standard could be
466 handled in a similar way, such as out-of-bounds array indexing. */
468 static unsigned int
469 gimple_ssa_isolate_erroneous_paths (void)
471 initialize_original_copy_tables ();
473 /* Search all the blocks for edges which, if traversed, will
474 result in undefined behaviour. */
475 cfg_altered = false;
477 /* First handle cases where traversal of a particular edge
478 triggers undefined behaviour. These cases require creating
479 duplicate blocks and thus new SSA_NAMEs.
481 We want that process complete prior to the phase where we start
482 removing edges from the CFG. Edge removal may ultimately result in
483 removal of PHI nodes and thus releasing SSA_NAMEs back to the
484 name manager.
486 If the two processes run in parallel we could release an SSA_NAME
487 back to the manager but we could still have dangling references
488 to the released SSA_NAME in unreachable blocks.
489 that any released names not have dangling references in the IL. */
490 find_implicit_erroneous_behaviour ();
491 find_explicit_erroneous_behaviour ();
493 free_original_copy_tables ();
495 /* We scramble the CFG and loop structures a bit, clean up
496 appropriately. We really should incrementally update the
497 loop structures, in theory it shouldn't be that hard. */
498 free_dominance_info (CDI_POST_DOMINATORS);
499 if (cfg_altered)
501 free_dominance_info (CDI_DOMINATORS);
502 loops_state_set (LOOPS_NEED_FIXUP);
503 return TODO_cleanup_cfg | TODO_update_ssa;
505 return 0;
508 namespace {
509 const pass_data pass_data_isolate_erroneous_paths =
511 GIMPLE_PASS, /* type */
512 "isolate-paths", /* name */
513 OPTGROUP_NONE, /* optinfo_flags */
514 TV_ISOLATE_ERRONEOUS_PATHS, /* tv_id */
515 ( PROP_cfg | PROP_ssa ), /* properties_required */
516 0, /* properties_provided */
517 0, /* properties_destroyed */
518 0, /* todo_flags_start */
519 0, /* todo_flags_finish */
522 class pass_isolate_erroneous_paths : public gimple_opt_pass
524 public:
525 pass_isolate_erroneous_paths (gcc::context *ctxt)
526 : gimple_opt_pass (pass_data_isolate_erroneous_paths, ctxt)
529 /* opt_pass methods: */
530 opt_pass * clone () { return new pass_isolate_erroneous_paths (m_ctxt); }
531 virtual bool gate (function *)
533 /* If we do not have a suitable builtin function for the trap statement,
534 then do not perform the optimization. */
535 return (flag_isolate_erroneous_paths_dereference != 0
536 || flag_isolate_erroneous_paths_attribute != 0);
539 virtual unsigned int execute (function *)
541 return gimple_ssa_isolate_erroneous_paths ();
544 }; // class pass_isolate_erroneous_paths
547 gimple_opt_pass *
548 make_pass_isolate_erroneous_paths (gcc::context *ctxt)
550 return new pass_isolate_erroneous_paths (ctxt);