]> git.ipfire.org Git - thirdparty/gcc.git/blob - gcc/gimple-ssa-isolate-paths.c
Update copyright years.
[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-2017 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 "backend.h"
26 #include "tree.h"
27 #include "gimple.h"
28 #include "cfghooks.h"
29 #include "tree-pass.h"
30 #include "ssa.h"
31 #include "diagnostic-core.h"
32 #include "fold-const.h"
33 #include "gimple-iterator.h"
34 #include "gimple-walk.h"
35 #include "tree-ssa.h"
36 #include "cfgloop.h"
37 #include "tree-cfg.h"
38 #include "intl.h"
39
40
41 static bool cfg_altered;
42
43 /* Callback for walk_stmt_load_store_ops.
44
45 Return TRUE if OP will dereference the tree stored in DATA, FALSE
46 otherwise.
47
48 This routine only makes a superficial check for a dereference. Thus,
49 it must only be used if it is safe to return a false negative. */
50 static bool
51 check_loadstore (gimple *stmt, tree op, tree, void *data)
52 {
53 if ((TREE_CODE (op) == MEM_REF || TREE_CODE (op) == TARGET_MEM_REF)
54 && operand_equal_p (TREE_OPERAND (op, 0), (tree)data, 0))
55 {
56 TREE_THIS_VOLATILE (op) = 1;
57 TREE_SIDE_EFFECTS (op) = 1;
58 update_stmt (stmt);
59 return true;
60 }
61 return false;
62 }
63
64 /* Insert a trap after SI and split the block after the trap. */
65
66 static void
67 insert_trap (gimple_stmt_iterator *si_p, tree op)
68 {
69 /* We want the NULL pointer dereference to actually occur so that
70 code that wishes to catch the signal can do so.
71
72 If the dereference is a load, then there's nothing to do as the
73 LHS will be a throw-away SSA_NAME and the RHS is the NULL dereference.
74
75 If the dereference is a store and we can easily transform the RHS,
76 then simplify the RHS to enable more DCE. Note that we require the
77 statement to be a GIMPLE_ASSIGN which filters out calls on the RHS. */
78 gimple *stmt = gsi_stmt (*si_p);
79 if (walk_stmt_load_store_ops (stmt, (void *)op, NULL, check_loadstore)
80 && is_gimple_assign (stmt)
81 && INTEGRAL_TYPE_P (TREE_TYPE (gimple_assign_lhs (stmt))))
82 {
83 /* We just need to turn the RHS into zero converted to the proper
84 type. */
85 tree type = TREE_TYPE (gimple_assign_lhs (stmt));
86 gimple_assign_set_rhs_code (stmt, INTEGER_CST);
87 gimple_assign_set_rhs1 (stmt, fold_convert (type, integer_zero_node));
88 update_stmt (stmt);
89 }
90
91 gcall *new_stmt
92 = gimple_build_call (builtin_decl_explicit (BUILT_IN_TRAP), 0);
93 gimple_seq seq = NULL;
94 gimple_seq_add_stmt (&seq, new_stmt);
95
96 /* If we had a NULL pointer dereference, then we want to insert the
97 __builtin_trap after the statement, for the other cases we want
98 to insert before the statement. */
99 if (walk_stmt_load_store_ops (stmt, (void *)op,
100 check_loadstore,
101 check_loadstore))
102 {
103 gsi_insert_after (si_p, seq, GSI_NEW_STMT);
104 if (stmt_ends_bb_p (stmt))
105 {
106 split_block (gimple_bb (stmt), stmt);
107 return;
108 }
109 }
110 else
111 gsi_insert_before (si_p, seq, GSI_NEW_STMT);
112
113 split_block (gimple_bb (new_stmt), new_stmt);
114 *si_p = gsi_for_stmt (stmt);
115 }
116
117 /* BB when reached via incoming edge E will exhibit undefined behavior
118 at STMT. Isolate and optimize the path which exhibits undefined
119 behavior.
120
121 Isolation is simple. Duplicate BB and redirect E to BB'.
122
123 Optimization is simple as well. Replace STMT in BB' with an
124 unconditional trap and remove all outgoing edges from BB'.
125
126 If RET_ZERO, do not trap, only return NULL.
127
128 DUPLICATE is a pre-existing duplicate, use it as BB' if it exists.
129
130 Return BB'. */
131
132 basic_block
133 isolate_path (basic_block bb, basic_block duplicate,
134 edge e, gimple *stmt, tree op, bool ret_zero)
135 {
136 gimple_stmt_iterator si, si2;
137 edge_iterator ei;
138 edge e2;
139
140 /* First duplicate BB if we have not done so already and remove all
141 the duplicate's outgoing edges as duplicate is going to unconditionally
142 trap. Removing the outgoing edges is both an optimization and ensures
143 we don't need to do any PHI node updates. */
144 if (!duplicate)
145 {
146 duplicate = duplicate_block (bb, NULL, NULL);
147 if (!ret_zero)
148 for (ei = ei_start (duplicate->succs); (e2 = ei_safe_edge (ei)); )
149 remove_edge (e2);
150 }
151
152 /* Complete the isolation step by redirecting E to reach DUPLICATE. */
153 e2 = redirect_edge_and_branch (e, duplicate);
154 if (e2)
155 flush_pending_stmts (e2);
156
157
158 /* There may be more than one statement in DUPLICATE which exhibits
159 undefined behavior. Ultimately we want the first such statement in
160 DUPLCIATE so that we're able to delete as much code as possible.
161
162 So each time we discover undefined behavior in DUPLICATE, search for
163 the statement which triggers undefined behavior. If found, then
164 transform the statement into a trap and delete everything after the
165 statement. If not found, then this particular instance was subsumed by
166 an earlier instance of undefined behavior and there's nothing to do.
167
168 This is made more complicated by the fact that we have STMT, which is in
169 BB rather than in DUPLICATE. So we set up two iterators, one for each
170 block and walk forward looking for STMT in BB, advancing each iterator at
171 each step.
172
173 When we find STMT the second iterator should point to STMT's equivalent in
174 duplicate. If DUPLICATE ends before STMT is found in BB, then there's
175 nothing to do.
176
177 Ignore labels and debug statements. */
178 si = gsi_start_nondebug_after_labels_bb (bb);
179 si2 = gsi_start_nondebug_after_labels_bb (duplicate);
180 while (!gsi_end_p (si) && !gsi_end_p (si2) && gsi_stmt (si) != stmt)
181 {
182 gsi_next_nondebug (&si);
183 gsi_next_nondebug (&si2);
184 }
185
186 /* This would be an indicator that we never found STMT in BB, which should
187 never happen. */
188 gcc_assert (!gsi_end_p (si));
189
190 /* If we did not run to the end of DUPLICATE, then SI points to STMT and
191 SI2 points to the duplicate of STMT in DUPLICATE. Insert a trap
192 before SI2 and remove SI2 and all trailing statements. */
193 if (!gsi_end_p (si2))
194 {
195 if (ret_zero)
196 {
197 greturn *ret = as_a <greturn *> (gsi_stmt (si2));
198 tree zero = build_zero_cst (TREE_TYPE (gimple_return_retval (ret)));
199 gimple_return_set_retval (ret, zero);
200 update_stmt (ret);
201 }
202 else
203 insert_trap (&si2, op);
204 }
205
206 return duplicate;
207 }
208
209 /* Return TRUE if STMT is a div/mod operation using DIVISOR as the divisor.
210 FALSE otherwise. */
211
212 static bool
213 is_divmod_with_given_divisor (gimple *stmt, tree divisor)
214 {
215 /* Only assignments matter. */
216 if (!is_gimple_assign (stmt))
217 return false;
218
219 /* Check for every DIV/MOD expression. */
220 enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
221 if (rhs_code == TRUNC_DIV_EXPR
222 || rhs_code == FLOOR_DIV_EXPR
223 || rhs_code == CEIL_DIV_EXPR
224 || rhs_code == EXACT_DIV_EXPR
225 || rhs_code == ROUND_DIV_EXPR
226 || rhs_code == TRUNC_MOD_EXPR
227 || rhs_code == FLOOR_MOD_EXPR
228 || rhs_code == CEIL_MOD_EXPR
229 || rhs_code == ROUND_MOD_EXPR)
230 {
231 /* Pointer equality is fine when DIVISOR is an SSA_NAME, but
232 not sufficient for constants which may have different types. */
233 if (operand_equal_p (gimple_assign_rhs2 (stmt), divisor, 0))
234 return true;
235 }
236 return false;
237 }
238
239 /* NAME is an SSA_NAME that we have already determined has the value 0 or NULL.
240
241 Return TRUE if USE_STMT uses NAME in a way where a 0 or NULL value results
242 in undefined behavior, FALSE otherwise
243
244 LOC is used for issuing diagnostics. This case represents potential
245 undefined behavior exposed by path splitting and that's reflected in
246 the diagnostic. */
247
248 bool
249 stmt_uses_name_in_undefined_way (gimple *use_stmt, tree name, location_t loc)
250 {
251 /* If we are working with a non pointer type, then see
252 if this use is a DIV/MOD operation using NAME as the
253 divisor. */
254 if (!POINTER_TYPE_P (TREE_TYPE (name)))
255 {
256 if (!flag_non_call_exceptions)
257 return is_divmod_with_given_divisor (use_stmt, name);
258 return false;
259 }
260
261 /* NAME is a pointer, so see if it's used in a context where it must
262 be non-NULL. */
263 bool by_dereference
264 = infer_nonnull_range_by_dereference (use_stmt, name);
265
266 if (by_dereference
267 || infer_nonnull_range_by_attribute (use_stmt, name))
268 {
269
270 if (by_dereference)
271 {
272 warning_at (loc, OPT_Wnull_dereference,
273 "potential null pointer dereference");
274 if (!flag_isolate_erroneous_paths_dereference)
275 return false;
276 }
277 else
278 {
279 if (!flag_isolate_erroneous_paths_attribute)
280 return false;
281 }
282 return true;
283 }
284 return false;
285 }
286
287 /* Return TRUE if USE_STMT uses 0 or NULL in a context which results in
288 undefined behavior, FALSE otherwise.
289
290 These cases are explicit in the IL. */
291
292 bool
293 stmt_uses_0_or_null_in_undefined_way (gimple *stmt)
294 {
295 if (!flag_non_call_exceptions
296 && is_divmod_with_given_divisor (stmt, integer_zero_node))
297 return true;
298
299 /* By passing null_pointer_node, we can use the
300 infer_nonnull_range functions to detect explicit NULL
301 pointer dereferences and other uses where a non-NULL
302 value is required. */
303
304 bool by_dereference
305 = infer_nonnull_range_by_dereference (stmt, null_pointer_node);
306 if (by_dereference
307 || infer_nonnull_range_by_attribute (stmt, null_pointer_node))
308 {
309 if (by_dereference)
310 {
311 location_t loc = gimple_location (stmt);
312 warning_at (loc, OPT_Wnull_dereference,
313 "null pointer dereference");
314 if (!flag_isolate_erroneous_paths_dereference)
315 return false;
316 }
317 else
318 {
319 if (!flag_isolate_erroneous_paths_attribute)
320 return false;
321 }
322 return true;
323 }
324 return false;
325 }
326
327 /* Look for PHI nodes which feed statements in the same block where
328 the value of the PHI node implies the statement is erroneous.
329
330 For example, a NULL PHI arg value which then feeds a pointer
331 dereference.
332
333 When found isolate and optimize the path associated with the PHI
334 argument feeding the erroneous statement. */
335 static void
336 find_implicit_erroneous_behavior (void)
337 {
338 basic_block bb;
339
340 FOR_EACH_BB_FN (bb, cfun)
341 {
342 gphi_iterator si;
343
344 /* Out of an abundance of caution, do not isolate paths to a
345 block where the block has any abnormal outgoing edges.
346
347 We might be able to relax this in the future. We have to detect
348 when we have to split the block with the NULL dereference and
349 the trap we insert. We have to preserve abnormal edges out
350 of the isolated block which in turn means updating PHIs at
351 the targets of those abnormal outgoing edges. */
352 if (has_abnormal_or_eh_outgoing_edge_p (bb))
353 continue;
354
355 /* First look for a PHI which sets a pointer to NULL and which
356 is then dereferenced within BB. This is somewhat overly
357 conservative, but probably catches most of the interesting
358 cases. */
359 for (si = gsi_start_phis (bb); !gsi_end_p (si); gsi_next (&si))
360 {
361 gphi *phi = si.phi ();
362 tree lhs = gimple_phi_result (phi);
363
364 /* PHI produces a pointer result. See if any of the PHI's
365 arguments are NULL.
366
367 When we remove an edge, we want to reprocess the current
368 index, hence the ugly way we update I for each iteration. */
369 basic_block duplicate = NULL;
370 for (unsigned i = 0, next_i = 0;
371 i < gimple_phi_num_args (phi);
372 i = next_i)
373 {
374 tree op = gimple_phi_arg_def (phi, i);
375 edge e = gimple_phi_arg_edge (phi, i);
376 imm_use_iterator iter;
377 gimple *use_stmt;
378
379 next_i = i + 1;
380
381 if (TREE_CODE (op) == ADDR_EXPR)
382 {
383 tree valbase = get_base_address (TREE_OPERAND (op, 0));
384 if ((VAR_P (valbase) && !is_global_var (valbase))
385 || TREE_CODE (valbase) == PARM_DECL)
386 {
387 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
388 {
389 greturn *return_stmt
390 = dyn_cast <greturn *> (use_stmt);
391 if (!return_stmt)
392 continue;
393
394 if (gimple_return_retval (return_stmt) != lhs)
395 continue;
396
397 if (warning_at (gimple_location (use_stmt),
398 OPT_Wreturn_local_addr,
399 "function may return address "
400 "of local variable"))
401 inform (DECL_SOURCE_LOCATION(valbase),
402 "declared here");
403
404 if (gimple_bb (use_stmt) == bb)
405 {
406 duplicate = isolate_path (bb, duplicate, e,
407 use_stmt, lhs, true);
408
409 /* When we remove an incoming edge, we need to
410 reprocess the Ith element. */
411 next_i = i;
412 cfg_altered = true;
413 }
414 }
415 }
416 }
417
418 if (!integer_zerop (op))
419 continue;
420
421 /* We've got a NULL PHI argument. Now see if the
422 PHI's result is dereferenced within BB. */
423 FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
424 {
425 /* We only care about uses in BB. Catching cases in
426 in other blocks would require more complex path
427 isolation code. */
428 if (gimple_bb (use_stmt) != bb)
429 continue;
430
431 location_t loc = gimple_location (use_stmt)
432 ? gimple_location (use_stmt)
433 : gimple_phi_arg_location (phi, i);
434
435 if (stmt_uses_name_in_undefined_way (use_stmt, lhs, loc))
436 {
437 duplicate = isolate_path (bb, duplicate, e,
438 use_stmt, lhs, false);
439
440 /* When we remove an incoming edge, we need to
441 reprocess the Ith element. */
442 next_i = i;
443 cfg_altered = true;
444 }
445 }
446 }
447 }
448 }
449 }
450
451 /* Look for statements which exhibit erroneous behavior. For example
452 a NULL pointer dereference.
453
454 When found, optimize the block containing the erroneous behavior. */
455 static void
456 find_explicit_erroneous_behavior (void)
457 {
458 basic_block bb;
459
460 FOR_EACH_BB_FN (bb, cfun)
461 {
462 gimple_stmt_iterator si;
463
464 /* Out of an abundance of caution, do not isolate paths to a
465 block where the block has any abnormal outgoing edges.
466
467 We might be able to relax this in the future. We have to detect
468 when we have to split the block with the NULL dereference and
469 the trap we insert. We have to preserve abnormal edges out
470 of the isolated block which in turn means updating PHIs at
471 the targets of those abnormal outgoing edges. */
472 if (has_abnormal_or_eh_outgoing_edge_p (bb))
473 continue;
474
475 /* Now look at the statements in the block and see if any of
476 them explicitly dereference a NULL pointer. This happens
477 because of jump threading and constant propagation. */
478 for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
479 {
480 gimple *stmt = gsi_stmt (si);
481
482 if (stmt_uses_0_or_null_in_undefined_way (stmt))
483 {
484 insert_trap (&si, null_pointer_node);
485 bb = gimple_bb (gsi_stmt (si));
486
487 /* Ignore any more operands on this statement and
488 continue the statement iterator (which should
489 terminate its loop immediately. */
490 cfg_altered = true;
491 break;
492 }
493
494 /* Detect returning the address of a local variable. This only
495 becomes undefined behavior if the result is used, so we do not
496 insert a trap and only return NULL instead. */
497 if (greturn *return_stmt = dyn_cast <greturn *> (stmt))
498 {
499 tree val = gimple_return_retval (return_stmt);
500 if (val && TREE_CODE (val) == ADDR_EXPR)
501 {
502 tree valbase = get_base_address (TREE_OPERAND (val, 0));
503 if ((VAR_P (valbase) && !is_global_var (valbase))
504 || TREE_CODE (valbase) == PARM_DECL)
505 {
506 /* We only need it for this particular case. */
507 calculate_dominance_info (CDI_POST_DOMINATORS);
508 const char* msg;
509 bool always_executed = dominated_by_p
510 (CDI_POST_DOMINATORS,
511 single_succ (ENTRY_BLOCK_PTR_FOR_FN (cfun)), bb);
512 if (always_executed)
513 msg = N_("function returns address of local variable");
514 else
515 msg = N_("function may return address of "
516 "local variable");
517
518 if (warning_at (gimple_location (stmt),
519 OPT_Wreturn_local_addr, msg))
520 inform (DECL_SOURCE_LOCATION(valbase), "declared here");
521 tree zero = build_zero_cst (TREE_TYPE (val));
522 gimple_return_set_retval (return_stmt, zero);
523 update_stmt (stmt);
524 }
525 }
526 }
527 }
528 }
529 }
530
531 /* Search the function for statements which, if executed, would cause
532 the program to fault such as a dereference of a NULL pointer.
533
534 Such a program can't be valid if such a statement was to execute
535 according to ISO standards.
536
537 We detect explicit NULL pointer dereferences as well as those implied
538 by a PHI argument having a NULL value which unconditionally flows into
539 a dereference in the same block as the PHI.
540
541 In the former case we replace the offending statement with an
542 unconditional trap and eliminate the outgoing edges from the statement's
543 basic block. This may expose secondary optimization opportunities.
544
545 In the latter case, we isolate the path(s) with the NULL PHI
546 feeding the dereference. We can then replace the offending statement
547 and eliminate the outgoing edges in the duplicate. Again, this may
548 expose secondary optimization opportunities.
549
550 A warning for both cases may be advisable as well.
551
552 Other statically detectable violations of the ISO standard could be
553 handled in a similar way, such as out-of-bounds array indexing. */
554
555 static unsigned int
556 gimple_ssa_isolate_erroneous_paths (void)
557 {
558 initialize_original_copy_tables ();
559
560 /* Search all the blocks for edges which, if traversed, will
561 result in undefined behavior. */
562 cfg_altered = false;
563
564 /* First handle cases where traversal of a particular edge
565 triggers undefined behavior. These cases require creating
566 duplicate blocks and thus new SSA_NAMEs.
567
568 We want that process complete prior to the phase where we start
569 removing edges from the CFG. Edge removal may ultimately result in
570 removal of PHI nodes and thus releasing SSA_NAMEs back to the
571 name manager.
572
573 If the two processes run in parallel we could release an SSA_NAME
574 back to the manager but we could still have dangling references
575 to the released SSA_NAME in unreachable blocks.
576 that any released names not have dangling references in the IL. */
577 find_implicit_erroneous_behavior ();
578 find_explicit_erroneous_behavior ();
579
580 free_original_copy_tables ();
581
582 /* We scramble the CFG and loop structures a bit, clean up
583 appropriately. We really should incrementally update the
584 loop structures, in theory it shouldn't be that hard. */
585 free_dominance_info (CDI_POST_DOMINATORS);
586 if (cfg_altered)
587 {
588 free_dominance_info (CDI_DOMINATORS);
589 loops_state_set (LOOPS_NEED_FIXUP);
590 return TODO_cleanup_cfg | TODO_update_ssa;
591 }
592 return 0;
593 }
594
595 namespace {
596 const pass_data pass_data_isolate_erroneous_paths =
597 {
598 GIMPLE_PASS, /* type */
599 "isolate-paths", /* name */
600 OPTGROUP_NONE, /* optinfo_flags */
601 TV_ISOLATE_ERRONEOUS_PATHS, /* tv_id */
602 ( PROP_cfg | PROP_ssa ), /* properties_required */
603 0, /* properties_provided */
604 0, /* properties_destroyed */
605 0, /* todo_flags_start */
606 0, /* todo_flags_finish */
607 };
608
609 class pass_isolate_erroneous_paths : public gimple_opt_pass
610 {
611 public:
612 pass_isolate_erroneous_paths (gcc::context *ctxt)
613 : gimple_opt_pass (pass_data_isolate_erroneous_paths, ctxt)
614 {}
615
616 /* opt_pass methods: */
617 opt_pass * clone () { return new pass_isolate_erroneous_paths (m_ctxt); }
618 virtual bool gate (function *)
619 {
620 /* If we do not have a suitable builtin function for the trap statement,
621 then do not perform the optimization. */
622 return (flag_isolate_erroneous_paths_dereference != 0
623 || flag_isolate_erroneous_paths_attribute != 0
624 || warn_null_dereference);
625 }
626
627 virtual unsigned int execute (function *)
628 {
629 return gimple_ssa_isolate_erroneous_paths ();
630 }
631
632 }; // class pass_isolate_erroneous_paths
633 }
634
635 gimple_opt_pass *
636 make_pass_isolate_erroneous_paths (gcc::context *ctxt)
637 {
638 return new pass_isolate_erroneous_paths (ctxt);
639 }