]> git.ipfire.org Git - thirdparty/gcc.git/blob - gcc/gimple-ssa-isolate-paths.c
2014-10-27 Andrew MacLeod <amacleod@redhat.com>
[thirdparty/gcc.git] / gcc / gimple-ssa-isolate-paths.c
1 /* Detect paths through the CFG which can never be executed in a conforming
2 program and isolate them.
3
4 Copyright (C) 2013-2014 Free Software Foundation, Inc.
5
6 This file is part of GCC.
7
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.
12
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.
17
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/>. */
21
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "tree.h"
26 #include "flags.h"
27 #include "predict.h"
28 #include "vec.h"
29 #include "hashtab.h"
30 #include "hash-set.h"
31 #include "machmode.h"
32 #include "tm.h"
33 #include "hard-reg-set.h"
34 #include "input.h"
35 #include "function.h"
36 #include "dominance.h"
37 #include "cfg.h"
38 #include "basic-block.h"
39 #include "tree-ssa-alias.h"
40 #include "internal-fn.h"
41 #include "gimple-expr.h"
42 #include "is-a.h"
43 #include "gimple.h"
44 #include "gimple-iterator.h"
45 #include "gimple-walk.h"
46 #include "tree-ssa.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"
53 #include "cfgloop.h"
54 #include "tree-pass.h"
55 #include "tree-cfg.h"
56 #include "diagnostic-core.h"
57 #include "intl.h"
58
59
60 static bool cfg_altered;
61
62 /* Callback for walk_stmt_load_store_ops.
63
64 Return TRUE if OP will dereference the tree stored in DATA, FALSE
65 otherwise.
66
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. */
69 static bool
70 check_loadstore (gimple stmt, tree op, tree, void *data)
71 {
72 if ((TREE_CODE (op) == MEM_REF || TREE_CODE (op) == TARGET_MEM_REF)
73 && operand_equal_p (TREE_OPERAND (op, 0), (tree)data, 0))
74 {
75 TREE_THIS_VOLATILE (op) = 1;
76 TREE_SIDE_EFFECTS (op) = 1;
77 update_stmt (stmt);
78 return true;
79 }
80 return false;
81 }
82
83 /* Insert a trap after SI and remove SI and all statements after the trap. */
84
85 static void
86 insert_trap_and_remove_trailing_statements (gimple_stmt_iterator *si_p, tree op)
87 {
88 /* We want the NULL pointer dereference to actually occur so that
89 code that wishes to catch the signal can do so.
90
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.
93
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))))
101 {
102 /* We just need to turn the RHS into zero converted to the proper
103 type. */
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));
107 update_stmt (stmt);
108 }
109
110 gimple new_stmt
111 = gimple_build_call (builtin_decl_explicit (BUILT_IN_TRAP), 0);
112 gimple_seq seq = NULL;
113 gimple_seq_add_stmt (&seq, new_stmt);
114
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,
119 check_loadstore,
120 check_loadstore))
121 gsi_insert_after (si_p, seq, GSI_NEW_STMT);
122 else
123 gsi_insert_before (si_p, seq, GSI_NEW_STMT);
124
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))
131 {
132 stmt = gsi_stmt (si);
133 unlink_stmt_vdef (stmt);
134 gsi_remove (&si, true);
135 release_defs (stmt);
136 }
137 }
138
139 /* BB when reached via incoming edge E will exhibit undefined behaviour
140 at STMT. Isolate and optimize the path which exhibits undefined
141 behaviour.
142
143 Isolation is simple. Duplicate BB and redirect E to BB'.
144
145 Optimization is simple as well. Replace STMT in BB' with an
146 unconditional trap and remove all outgoing edges from BB'.
147
148 If RET_ZERO, do not trap, only return NULL.
149
150 DUPLICATE is a pre-existing duplicate, use it as BB' if it exists.
151
152 Return BB'. */
153
154 basic_block
155 isolate_path (basic_block bb, basic_block duplicate,
156 edge e, gimple stmt, tree op, bool ret_zero)
157 {
158 gimple_stmt_iterator si, si2;
159 edge_iterator ei;
160 edge e2;
161
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. */
166 if (!duplicate)
167 {
168 duplicate = duplicate_block (bb, NULL, NULL);
169 if (!ret_zero)
170 for (ei = ei_start (duplicate->succs); (e2 = ei_safe_edge (ei)); )
171 remove_edge (e2);
172 }
173
174 /* Complete the isolation step by redirecting E to reach DUPLICATE. */
175 e2 = redirect_edge_and_branch (e, duplicate);
176 if (e2)
177 flush_pending_stmts (e2);
178
179
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.
183
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.
189
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
193 each step.
194
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
197 nothing to do.
198
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)
203 {
204 gsi_next_nondebug (&si);
205 gsi_next_nondebug (&si2);
206 }
207
208 /* This would be an indicator that we never found STMT in BB, which should
209 never happen. */
210 gcc_assert (!gsi_end_p (si));
211
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))
216 {
217 if (ret_zero)
218 {
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);
222 update_stmt (ret);
223 }
224 else
225 insert_trap_and_remove_trailing_statements (&si2, op);
226 }
227
228 return duplicate;
229 }
230
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.
233
234 For example, a NULL PHI arg value which then feeds a pointer
235 dereference.
236
237 When found isolate and optimize the path associated with the PHI
238 argument feeding the erroneous statement. */
239 static void
240 find_implicit_erroneous_behaviour (void)
241 {
242 basic_block bb;
243
244 FOR_EACH_BB_FN (bb, cfun)
245 {
246 gimple_stmt_iterator si;
247
248 /* Out of an abundance of caution, do not isolate paths to a
249 block where the block has any abnormal outgoing edges.
250
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))
257 continue;
258
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
262 cases. */
263 for (si = gsi_start_phis (bb); !gsi_end_p (si); gsi_next (&si))
264 {
265 gimple phi = gsi_stmt (si);
266 tree lhs = gimple_phi_result (phi);
267
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)))
271 continue;
272
273 /* PHI produces a pointer result. See if any of the PHI's
274 arguments are NULL.
275
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);
281 i = next_i)
282 {
283 tree op = gimple_phi_arg_def (phi, i);
284 edge e = gimple_phi_arg_edge (phi, i);
285 imm_use_iterator iter;
286 gimple use_stmt;
287
288 next_i = i + 1;
289
290 if (TREE_CODE (op) == ADDR_EXPR)
291 {
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)
296 {
297 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
298 {
299 if (gimple_code (use_stmt) != GIMPLE_RETURN
300 || gimple_return_retval (use_stmt) != lhs)
301 continue;
302
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),
308 "declared here");
309
310 if (gimple_bb (use_stmt) == bb)
311 {
312 duplicate = isolate_path (bb, duplicate, e,
313 use_stmt, lhs, true);
314
315 /* When we remove an incoming edge, we need to
316 reprocess the Ith element. */
317 next_i = i;
318 cfg_altered = true;
319 }
320 }
321 }
322 }
323
324 if (!integer_zerop (op))
325 continue;
326
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)
330 {
331 /* We only care about uses in BB. Catching cases in
332 in other blocks would require more complex path
333 isolation code. */
334 if (gimple_bb (use_stmt) != bb)
335 continue;
336
337 if (infer_nonnull_range (use_stmt, lhs,
338 flag_isolate_erroneous_paths_dereference,
339 flag_isolate_erroneous_paths_attribute))
340
341 {
342 duplicate = isolate_path (bb, duplicate, e,
343 use_stmt, lhs, false);
344
345 /* When we remove an incoming edge, we need to
346 reprocess the Ith element. */
347 next_i = i;
348 cfg_altered = true;
349 }
350 }
351 }
352 }
353 }
354 }
355
356 /* Look for statements which exhibit erroneous behaviour. For example
357 a NULL pointer dereference.
358
359 When found, optimize the block containing the erroneous behaviour. */
360 static void
361 find_explicit_erroneous_behaviour (void)
362 {
363 basic_block bb;
364
365 FOR_EACH_BB_FN (bb, cfun)
366 {
367 gimple_stmt_iterator si;
368
369 /* Out of an abundance of caution, do not isolate paths to a
370 block where the block has any abnormal outgoing edges.
371
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))
378 continue;
379
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))
384 {
385 gimple stmt = gsi_stmt (si);
386
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))
393 {
394 insert_trap_and_remove_trailing_statements (&si,
395 null_pointer_node);
396
397 /* And finally, remove all outgoing edges from BB. */
398 edge e;
399 for (edge_iterator ei = ei_start (bb->succs);
400 (e = ei_safe_edge (ei)); )
401 remove_edge (e);
402
403 /* Ignore any more operands on this statement and
404 continue the statement iterator (which should
405 terminate its loop immediately. */
406 cfg_altered = true;
407 break;
408 }
409
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)
414 {
415 tree val = gimple_return_retval (stmt);
416 if (val && TREE_CODE (val) == ADDR_EXPR)
417 {
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)
422 {
423 /* We only need it for this particular case. */
424 calculate_dominance_info (CDI_POST_DOMINATORS);
425 const char* msg;
426 bool always_executed = dominated_by_p
427 (CDI_POST_DOMINATORS,
428 single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun)), bb);
429 if (always_executed)
430 msg = N_("function returns address of local variable");
431 else
432 msg = N_("function may return address of "
433 "local variable");
434
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);
440 update_stmt (stmt);
441 }
442 }
443 }
444 }
445 }
446 }
447
448 /* Search the function for statements which, if executed, would cause
449 the program to fault such as a dereference of a NULL pointer.
450
451 Such a program can't be valid if such a statement was to execute
452 according to ISO standards.
453
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.
457
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.
461
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.
466
467 A warning for both cases may be advisable as well.
468
469 Other statically detectable violations of the ISO standard could be
470 handled in a similar way, such as out-of-bounds array indexing. */
471
472 static unsigned int
473 gimple_ssa_isolate_erroneous_paths (void)
474 {
475 initialize_original_copy_tables ();
476
477 /* Search all the blocks for edges which, if traversed, will
478 result in undefined behaviour. */
479 cfg_altered = false;
480
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.
484
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
488 name manager.
489
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 ();
496
497 free_original_copy_tables ();
498
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. */
502 if (cfg_altered)
503 {
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;
508 }
509 return 0;
510 }
511
512 namespace {
513 const pass_data pass_data_isolate_erroneous_paths =
514 {
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 */
524 };
525
526 class pass_isolate_erroneous_paths : public gimple_opt_pass
527 {
528 public:
529 pass_isolate_erroneous_paths (gcc::context *ctxt)
530 : gimple_opt_pass (pass_data_isolate_erroneous_paths, ctxt)
531 {}
532
533 /* opt_pass methods: */
534 opt_pass * clone () { return new pass_isolate_erroneous_paths (m_ctxt); }
535 virtual bool gate (function *)
536 {
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);
541 }
542
543 virtual unsigned int execute (function *)
544 {
545 return gimple_ssa_isolate_erroneous_paths ();
546 }
547
548 }; // class pass_isolate_erroneous_paths
549 }
550
551 gimple_opt_pass *
552 make_pass_isolate_erroneous_paths (gcc::context *ctxt)
553 {
554 return new pass_isolate_erroneous_paths (ctxt);
555 }