gimple.h: Remove all includes.
[platform/upstream/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
5    Free Software Foundation, Inc.
6
7 This file is part of GCC.
8
9 GCC is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3, or (at your option)
12 any later version.
13
14 GCC is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING3.  If not see
21 <http://www.gnu.org/licenses/>.  */
22
23 #include "config.h"
24 #include "system.h"
25 #include "coretypes.h"
26 #include "tree.h"
27 #include "flags.h"
28 #include "basic-block.h"
29 #include "tree-ssa-alias.h"
30 #include "internal-fn.h"
31 #include "gimple-expr.h"
32 #include "is-a.h"
33 #include "gimple.h"
34 #include "gimple-iterator.h"
35 #include "gimple-walk.h"
36 #include "tree-ssa.h"
37 #include "stringpool.h"
38 #include "tree-ssanames.h"
39 #include "gimple-ssa.h"
40 #include "tree-ssa-operands.h"
41 #include "tree-phinodes.h"
42 #include "ssa-iterators.h"
43 #include "cfgloop.h"
44 #include "tree-pass.h"
45 #include "tree-cfg.h"
46
47
48 static bool cfg_altered;
49
50 /* Callback for walk_stmt_load_store_ops.
51  
52    Return TRUE if OP will dereference the tree stored in DATA, FALSE
53    otherwise.
54
55    This routine only makes a superficial check for a dereference.  Thus,
56    it must only be used if it is safe to return a false negative.  */
57 static bool
58 check_loadstore (gimple stmt ATTRIBUTE_UNUSED, tree op, void *data)
59 {
60   if ((TREE_CODE (op) == MEM_REF || TREE_CODE (op) == TARGET_MEM_REF)
61       && operand_equal_p (TREE_OPERAND (op, 0), (tree)data, 0))
62     {
63       TREE_THIS_VOLATILE (op) = 1;
64       TREE_SIDE_EFFECTS (op) = 1;
65       update_stmt (stmt);
66       return true;
67     }
68   return false;
69 }
70
71 /* Insert a trap after SI and remove SI and all statements after the trap.  */
72
73 static void
74 insert_trap_and_remove_trailing_statements (gimple_stmt_iterator *si_p, tree op)
75 {
76   /* We want the NULL pointer dereference to actually occur so that
77      code that wishes to catch the signal can do so.
78
79      If the dereference is a load, then there's nothing to do as the
80      LHS will be a throw-away SSA_NAME and the RHS is the NULL dereference.
81
82      If the dereference is a store and we can easily transform the RHS,
83      then simplify the RHS to enable more DCE.   Note that we require the
84      statement to be a GIMPLE_ASSIGN which filters out calls on the RHS.  */
85   gimple stmt = gsi_stmt (*si_p);
86   if (walk_stmt_load_store_ops (stmt, (void *)op, NULL, check_loadstore)
87       && is_gimple_assign (stmt)
88       && INTEGRAL_TYPE_P (TREE_TYPE (gimple_assign_lhs (stmt))))
89     {
90       /* We just need to turn the RHS into zero converted to the proper
91          type.  */
92       tree type = TREE_TYPE (gimple_assign_lhs (stmt));
93       gimple_assign_set_rhs_code (stmt, INTEGER_CST);
94       gimple_assign_set_rhs1 (stmt, fold_convert (type, integer_zero_node));
95       update_stmt (stmt);
96     }
97
98   gimple new_stmt
99     = gimple_build_call (builtin_decl_explicit (BUILT_IN_TRAP), 0);
100   gimple_seq seq = NULL;
101   gimple_seq_add_stmt (&seq, new_stmt);
102
103   /* If we had a NULL pointer dereference, then we want to insert the
104      __builtin_trap after the statement, for the other cases we want
105      to insert before the statement.  */
106   if (walk_stmt_load_store_ops (stmt, (void *)op,
107                                 check_loadstore,
108                                 check_loadstore))
109     gsi_insert_after (si_p, seq, GSI_NEW_STMT);
110   else
111     gsi_insert_before (si_p, seq, GSI_NEW_STMT);
112
113   /* We must remove statements from the end of the block so that we
114      never reference a released SSA_NAME.  */
115   basic_block bb = gimple_bb (gsi_stmt (*si_p));
116   for (gimple_stmt_iterator si = gsi_last_bb (bb);
117        gsi_stmt (si) != gsi_stmt (*si_p);
118        si = gsi_last_bb (bb))
119     {
120       stmt = gsi_stmt (si);
121       unlink_stmt_vdef (stmt);
122       gsi_remove (&si, true);
123       release_defs (stmt);
124     }
125 }
126
127 /* BB when reached via incoming edge E will exhibit undefined behaviour
128    at STMT.  Isolate and optimize the path which exhibits undefined
129    behaviour.
130
131    Isolation is simple.  Duplicate BB and redirect E to BB'.
132
133    Optimization is simple as well.  Replace STMT in BB' with an
134    unconditional trap and remove all outgoing edges from BB'.
135
136    DUPLICATE is a pre-existing duplicate, use it as BB' if it exists.
137
138    Return BB'.  */
139
140 basic_block
141 isolate_path (basic_block bb, basic_block duplicate,
142               edge e, gimple stmt, tree op)
143 {
144   gimple_stmt_iterator si, si2;
145   edge_iterator ei;
146   edge e2;
147   
148
149   /* First duplicate BB if we have not done so already and remove all
150      the duplicate's outgoing edges as duplicate is going to unconditionally
151      trap.  Removing the outgoing edges is both an optimization and ensures
152      we don't need to do any PHI node updates.  */
153   if (!duplicate)
154     {
155       duplicate = duplicate_block (bb, NULL, NULL);
156       for (ei = ei_start (duplicate->succs); (e2 = ei_safe_edge (ei)); )
157         remove_edge (e2);
158     }
159
160   /* Complete the isolation step by redirecting E to reach DUPLICATE.  */
161   e2 = redirect_edge_and_branch (e, duplicate);
162   if (e2)
163     flush_pending_stmts (e2);
164
165
166   /* There may be more than one statement in DUPLICATE which exhibits
167      undefined behaviour.  Ultimately we want the first such statement in
168      DUPLCIATE so that we're able to delete as much code as possible.
169
170      So each time we discover undefined behaviour in DUPLICATE, search for
171      the statement which triggers undefined behaviour.  If found, then
172      transform the statement into a trap and delete everything after the
173      statement.  If not found, then this particular instance was subsumed by
174      an earlier instance of undefined behaviour and there's nothing to do. 
175
176      This is made more complicated by the fact that we have STMT, which is in
177      BB rather than in DUPLICATE.  So we set up two iterators, one for each
178      block and walk forward looking for STMT in BB, advancing each iterator at
179      each step.
180
181      When we find STMT the second iterator should point to STMT's equivalent in
182      duplicate.  If DUPLICATE ends before STMT is found in BB, then there's
183      nothing to do. 
184
185      Ignore labels and debug statements.  */
186   si = gsi_start_nondebug_after_labels_bb (bb);
187   si2 = gsi_start_nondebug_after_labels_bb (duplicate);
188   while (!gsi_end_p (si) && !gsi_end_p (si2) && gsi_stmt (si) != stmt)
189     {
190       gsi_next_nondebug (&si);
191       gsi_next_nondebug (&si2);
192     }
193
194   /* This would be an indicator that we never found STMT in BB, which should
195      never happen.  */
196   gcc_assert (!gsi_end_p (si));
197
198   /* If we did not run to the end of DUPLICATE, then SI points to STMT and
199      SI2 points to the duplicate of STMT in DUPLICATE.  Insert a trap
200      before SI2 and remove SI2 and all trailing statements.  */
201   if (!gsi_end_p (si2))
202     insert_trap_and_remove_trailing_statements (&si2, op);
203
204   return duplicate;
205 }
206
207 /* Look for PHI nodes which feed statements in the same block where
208    the value of the PHI node implies the statement is erroneous.
209
210    For example, a NULL PHI arg value which then feeds a pointer
211    dereference.
212
213    When found isolate and optimize the path associated with the PHI
214    argument feeding the erroneous statement.  */
215 static void
216 find_implicit_erroneous_behaviour (void)
217 {
218   basic_block bb;
219
220   FOR_EACH_BB (bb)
221     {
222       gimple_stmt_iterator si;
223
224       /* Out of an abundance of caution, do not isolate paths to a
225          block where the block has any abnormal outgoing edges.
226
227          We might be able to relax this in the future.  We have to detect
228          when we have to split the block with the NULL dereference and
229          the trap we insert.  We have to preserve abnormal edges out
230          of the isolated block which in turn means updating PHIs at
231          the targets of those abnormal outgoing edges.  */
232       if (has_abnormal_or_eh_outgoing_edge_p (bb))
233         continue;
234
235       /* First look for a PHI which sets a pointer to NULL and which
236          is then dereferenced within BB.  This is somewhat overly
237          conservative, but probably catches most of the interesting
238          cases.   */
239       for (si = gsi_start_phis (bb); !gsi_end_p (si); gsi_next (&si))
240         {
241           gimple phi = gsi_stmt (si);
242           tree lhs = gimple_phi_result (phi);
243
244           /* If the result is not a pointer, then there is no need to
245              examine the arguments.  */
246           if (!POINTER_TYPE_P (TREE_TYPE (lhs)))
247             continue;
248
249           /* PHI produces a pointer result.  See if any of the PHI's
250              arguments are NULL. 
251
252              When we remove an edge, we want to reprocess the current
253              index, hence the ugly way we update I for each iteration.  */
254           basic_block duplicate = NULL;
255           for (unsigned i = 0, next_i = 0;
256                i < gimple_phi_num_args (phi);
257                i = next_i)
258             {
259               tree op = gimple_phi_arg_def (phi, i);
260
261               next_i = i + 1;
262         
263               if (!integer_zerop (op))
264                 continue;
265
266               edge e = gimple_phi_arg_edge (phi, i);
267               imm_use_iterator iter;
268               gimple use_stmt;
269
270               /* We've got a NULL PHI argument.  Now see if the
271                  PHI's result is dereferenced within BB.  */
272               FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
273                 {
274                   /* We only care about uses in BB.  Catching cases in
275                      in other blocks would require more complex path
276                      isolation code.   */
277                   if (gimple_bb (use_stmt) != bb)
278                     continue;
279
280                   if (infer_nonnull_range (use_stmt, lhs))
281                     {
282                       duplicate = isolate_path (bb, duplicate,
283                                                 e, use_stmt, lhs);
284
285                       /* When we remove an incoming edge, we need to
286                          reprocess the Ith element.  */
287                       next_i = i;
288                       cfg_altered = true;
289                     }
290                 }
291             }
292         }
293     }
294 }
295
296 /* Look for statements which exhibit erroneous behaviour.  For example
297    a NULL pointer dereference. 
298
299    When found, optimize the block containing the erroneous behaviour.  */
300 static void
301 find_explicit_erroneous_behaviour (void)
302 {
303   basic_block bb;
304
305   FOR_EACH_BB (bb)
306     {
307       gimple_stmt_iterator si;
308
309       /* Out of an abundance of caution, do not isolate paths to a
310          block where the block has any abnormal outgoing edges.
311
312          We might be able to relax this in the future.  We have to detect
313          when we have to split the block with the NULL dereference and
314          the trap we insert.  We have to preserve abnormal edges out
315          of the isolated block which in turn means updating PHIs at
316          the targets of those abnormal outgoing edges.  */
317       if (has_abnormal_or_eh_outgoing_edge_p (bb))
318         continue;
319
320       /* Now look at the statements in the block and see if any of
321          them explicitly dereference a NULL pointer.  This happens
322          because of jump threading and constant propagation.  */
323       for (si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
324         {
325           gimple stmt = gsi_stmt (si);
326
327           /* By passing null_pointer_node, we can use infer_nonnull_range
328              to detect explicit NULL pointer dereferences and other uses
329              where a non-NULL value is required.  */
330           if (infer_nonnull_range (stmt, null_pointer_node))
331             {
332               insert_trap_and_remove_trailing_statements (&si,
333                                                           null_pointer_node);
334
335               /* And finally, remove all outgoing edges from BB.  */
336               edge e;
337               for (edge_iterator ei = ei_start (bb->succs);
338                    (e = ei_safe_edge (ei)); )
339                 remove_edge (e);
340
341               /* Ignore any more operands on this statement and
342                  continue the statement iterator (which should
343                  terminate its loop immediately.  */
344               cfg_altered = true;
345               break;
346             }
347         }
348     }
349 }
350 /* Search the function for statements which, if executed, would cause
351    the program to fault such as a dereference of a NULL pointer.
352
353    Such a program can't be valid if such a statement was to execute
354    according to ISO standards.
355
356    We detect explicit NULL pointer dereferences as well as those implied
357    by a PHI argument having a NULL value which unconditionally flows into
358    a dereference in the same block as the PHI.
359
360    In the former case we replace the offending statement with an
361    unconditional trap and eliminate the outgoing edges from the statement's
362    basic block.  This may expose secondary optimization opportunities.
363
364    In the latter case, we isolate the path(s) with the NULL PHI 
365    feeding the dereference.  We can then replace the offending statement
366    and eliminate the outgoing edges in the duplicate.  Again, this may
367    expose secondary optimization opportunities.
368
369    A warning for both cases may be advisable as well.
370
371    Other statically detectable violations of the ISO standard could be
372    handled in a similar way, such as out-of-bounds array indexing.  */
373
374 static unsigned int
375 gimple_ssa_isolate_erroneous_paths (void)
376 {
377   initialize_original_copy_tables ();
378
379   /* Search all the blocks for edges which, if traversed, will
380      result in undefined behaviour.  */
381   cfg_altered = false;
382
383   /* First handle cases where traversal of a particular edge
384      triggers undefined behaviour.  These cases require creating
385      duplicate blocks and thus new SSA_NAMEs.
386
387      We want that process complete prior to the phase where we start
388      removing edges from the CFG.  Edge removal may ultimately result in
389      removal of PHI nodes and thus releasing SSA_NAMEs back to the
390      name manager.
391
392      If the two processes run in parallel we could release an SSA_NAME
393      back to the manager but we could still have dangling references
394      to the released SSA_NAME in unreachable blocks.
395      that any released names not have dangling references in the IL.  */
396   find_implicit_erroneous_behaviour ();
397   find_explicit_erroneous_behaviour ();
398
399   free_original_copy_tables ();
400
401   /* We scramble the CFG and loop structures a bit, clean up 
402      appropriately.  We really should incrementally update the
403      loop structures, in theory it shouldn't be that hard.  */
404   if (cfg_altered)
405     {
406       free_dominance_info (CDI_DOMINATORS);
407       free_dominance_info (CDI_POST_DOMINATORS);
408       loops_state_set (LOOPS_NEED_FIXUP);
409       return TODO_cleanup_cfg | TODO_update_ssa;
410     }
411   return 0;
412 }
413
414 static bool
415 gate_isolate_erroneous_paths (void)
416 {
417   /* If we do not have a suitable builtin function for the trap statement,
418      then do not perform the optimization.  */
419   return (flag_isolate_erroneous_paths != 0);
420 }
421
422 namespace {
423 const pass_data pass_data_isolate_erroneous_paths =
424 {
425   GIMPLE_PASS, /* type */
426   "isolate-paths", /* name */
427   OPTGROUP_NONE, /* optinfo_flags */
428   true, /* has_gate */
429   true, /* has_execute */
430   TV_ISOLATE_ERRONEOUS_PATHS, /* tv_id */
431   ( PROP_cfg | PROP_ssa ), /* properties_required */
432   0, /* properties_provided */
433   0, /* properties_destroyed */
434   0, /* todo_flags_start */
435   TODO_verify_ssa, /* todo_flags_finish */
436 };
437
438 class pass_isolate_erroneous_paths : public gimple_opt_pass
439 {
440 public:
441   pass_isolate_erroneous_paths (gcc::context *ctxt)
442     : gimple_opt_pass (pass_data_isolate_erroneous_paths, ctxt)
443   {}
444
445   /* opt_pass methods: */
446   opt_pass * clone () { return new pass_isolate_erroneous_paths (m_ctxt); }
447   bool gate () { return gate_isolate_erroneous_paths (); }
448   unsigned int execute () { return gimple_ssa_isolate_erroneous_paths (); }
449
450 }; // class pass_isolate_erroneous_paths
451 }
452
453 gimple_opt_pass *
454 make_pass_isolate_erroneous_paths (gcc::context *ctxt)
455 {
456   return new pass_isolate_erroneous_paths (ctxt);
457 }