gimple-ssa-isolate-paths.c 18 KB

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