* gcc.dg/ipa/inlinehint-4.c: Also pass --param inline-unit-growth=20.
[official-gcc.git] / gcc / sanopt.c
blobcd94638c869230c96ee63b78394658161430748b
1 /* Optimize and expand sanitizer functions.
2 Copyright (C) 2014-2018 Free Software Foundation, Inc.
3 Contributed by Marek Polacek <polacek@redhat.com>
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 3, or (at your option) any later
10 version.
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "backend.h"
25 #include "tree.h"
26 #include "gimple.h"
27 #include "ssa.h"
28 #include "tree-pass.h"
29 #include "tree-ssa-operands.h"
30 #include "gimple-pretty-print.h"
31 #include "fold-const.h"
32 #include "gimple-iterator.h"
33 #include "stringpool.h"
34 #include "attribs.h"
35 #include "asan.h"
36 #include "ubsan.h"
37 #include "params.h"
38 #include "tree-hash-traits.h"
39 #include "gimple-ssa.h"
40 #include "tree-phinodes.h"
41 #include "ssa-iterators.h"
42 #include "gimplify.h"
43 #include "gimple-iterator.h"
44 #include "gimple-walk.h"
45 #include "cfghooks.h"
46 #include "tree-dfa.h"
47 #include "tree-ssa.h"
48 #include "varasm.h"
50 /* This is used to carry information about basic blocks. It is
51 attached to the AUX field of the standard CFG block. */
53 struct sanopt_info
55 /* True if this BB might call (directly or indirectly) free/munmap
56 or similar operation. */
57 bool has_freeing_call_p;
59 /* True if HAS_FREEING_CALL_P flag has been computed. */
60 bool has_freeing_call_computed_p;
62 /* True if there is a block with HAS_FREEING_CALL_P flag set
63 on any path between an immediate dominator of BB, denoted
64 imm(BB), and BB. */
65 bool imm_dom_path_with_freeing_call_p;
67 /* True if IMM_DOM_PATH_WITH_FREEING_CALL_P has been computed. */
68 bool imm_dom_path_with_freeing_call_computed_p;
70 /* Number of possibly freeing calls encountered in this bb
71 (so far). */
72 uint64_t freeing_call_events;
74 /* True if BB is currently being visited during computation
75 of IMM_DOM_PATH_WITH_FREEING_CALL_P flag. */
76 bool being_visited_p;
78 /* True if this BB has been visited in the dominator walk. */
79 bool visited_p;
82 /* If T has a single definition of form T = T2, return T2. */
84 static tree
85 maybe_get_single_definition (tree t)
87 if (TREE_CODE (t) == SSA_NAME)
89 gimple *g = SSA_NAME_DEF_STMT (t);
90 if (gimple_assign_single_p (g))
91 return gimple_assign_rhs1 (g);
93 return NULL_TREE;
96 /* Tree triplet for vptr_check_map. */
97 struct sanopt_tree_triplet
99 tree t1, t2, t3;
102 /* Traits class for tree triplet hash maps below. */
104 struct sanopt_tree_triplet_hash : typed_noop_remove <sanopt_tree_triplet>
106 typedef sanopt_tree_triplet value_type;
107 typedef sanopt_tree_triplet compare_type;
109 static hashval_t
110 hash (const sanopt_tree_triplet &ref)
112 inchash::hash hstate (0);
113 inchash::add_expr (ref.t1, hstate);
114 inchash::add_expr (ref.t2, hstate);
115 inchash::add_expr (ref.t3, hstate);
116 return hstate.end ();
119 static bool
120 equal (const sanopt_tree_triplet &ref1, const sanopt_tree_triplet &ref2)
122 return operand_equal_p (ref1.t1, ref2.t1, 0)
123 && operand_equal_p (ref1.t2, ref2.t2, 0)
124 && operand_equal_p (ref1.t3, ref2.t3, 0);
127 static void
128 mark_deleted (sanopt_tree_triplet &ref)
130 ref.t1 = reinterpret_cast<tree> (1);
133 static void
134 mark_empty (sanopt_tree_triplet &ref)
136 ref.t1 = NULL;
139 static bool
140 is_deleted (const sanopt_tree_triplet &ref)
142 return ref.t1 == reinterpret_cast<tree> (1);
145 static bool
146 is_empty (const sanopt_tree_triplet &ref)
148 return ref.t1 == NULL;
152 /* Tree couple for ptr_check_map. */
153 struct sanopt_tree_couple
155 tree ptr;
156 bool pos_p;
159 /* Traits class for tree triplet hash maps below. */
161 struct sanopt_tree_couple_hash : typed_noop_remove <sanopt_tree_couple>
163 typedef sanopt_tree_couple value_type;
164 typedef sanopt_tree_couple compare_type;
166 static hashval_t
167 hash (const sanopt_tree_couple &ref)
169 inchash::hash hstate (0);
170 inchash::add_expr (ref.ptr, hstate);
171 hstate.add_int (ref.pos_p);
172 return hstate.end ();
175 static bool
176 equal (const sanopt_tree_couple &ref1, const sanopt_tree_couple &ref2)
178 return operand_equal_p (ref1.ptr, ref2.ptr, 0)
179 && ref1.pos_p == ref2.pos_p;
182 static void
183 mark_deleted (sanopt_tree_couple &ref)
185 ref.ptr = reinterpret_cast<tree> (1);
188 static void
189 mark_empty (sanopt_tree_couple &ref)
191 ref.ptr = NULL;
194 static bool
195 is_deleted (const sanopt_tree_couple &ref)
197 return ref.ptr == reinterpret_cast<tree> (1);
200 static bool
201 is_empty (const sanopt_tree_couple &ref)
203 return ref.ptr == NULL;
207 /* This is used to carry various hash maps and variables used
208 in sanopt_optimize_walker. */
210 struct sanopt_ctx
212 /* This map maps a pointer (the first argument of UBSAN_NULL) to
213 a vector of UBSAN_NULL call statements that check this pointer. */
214 hash_map<tree, auto_vec<gimple *> > null_check_map;
216 /* This map maps a pointer (the second argument of ASAN_CHECK) to
217 a vector of ASAN_CHECK call statements that check the access. */
218 hash_map<tree_operand_hash, auto_vec<gimple *> > asan_check_map;
220 /* This map maps a tree triplet (the first, second and fourth argument
221 of UBSAN_VPTR) to a vector of UBSAN_VPTR call statements that check
222 that virtual table pointer. */
223 hash_map<sanopt_tree_triplet_hash, auto_vec<gimple *> > vptr_check_map;
225 /* This map maps a couple (tree and boolean) to a vector of UBSAN_PTR
226 call statements that check that pointer overflow. */
227 hash_map<sanopt_tree_couple_hash, auto_vec<gimple *> > ptr_check_map;
229 /* Number of IFN_ASAN_CHECK statements. */
230 int asan_num_accesses;
232 /* True when the current functions constains an ASAN_MARK. */
233 bool contains_asan_mark;
236 /* Return true if there might be any call to free/munmap operation
237 on any path in between DOM (which should be imm(BB)) and BB. */
239 static bool
240 imm_dom_path_with_freeing_call (basic_block bb, basic_block dom)
242 sanopt_info *info = (sanopt_info *) bb->aux;
243 edge e;
244 edge_iterator ei;
246 if (info->imm_dom_path_with_freeing_call_computed_p)
247 return info->imm_dom_path_with_freeing_call_p;
249 info->being_visited_p = true;
251 FOR_EACH_EDGE (e, ei, bb->preds)
253 sanopt_info *pred_info = (sanopt_info *) e->src->aux;
255 if (e->src == dom)
256 continue;
258 if ((pred_info->imm_dom_path_with_freeing_call_computed_p
259 && pred_info->imm_dom_path_with_freeing_call_p)
260 || (pred_info->has_freeing_call_computed_p
261 && pred_info->has_freeing_call_p))
263 info->imm_dom_path_with_freeing_call_computed_p = true;
264 info->imm_dom_path_with_freeing_call_p = true;
265 info->being_visited_p = false;
266 return true;
270 FOR_EACH_EDGE (e, ei, bb->preds)
272 sanopt_info *pred_info = (sanopt_info *) e->src->aux;
274 if (e->src == dom)
275 continue;
277 if (pred_info->has_freeing_call_computed_p)
278 continue;
280 gimple_stmt_iterator gsi;
281 for (gsi = gsi_start_bb (e->src); !gsi_end_p (gsi); gsi_next (&gsi))
283 gimple *stmt = gsi_stmt (gsi);
284 gasm *asm_stmt;
286 if ((is_gimple_call (stmt) && !nonfreeing_call_p (stmt))
287 || ((asm_stmt = dyn_cast <gasm *> (stmt))
288 && (gimple_asm_clobbers_memory_p (asm_stmt)
289 || gimple_asm_volatile_p (asm_stmt))))
291 pred_info->has_freeing_call_p = true;
292 break;
296 pred_info->has_freeing_call_computed_p = true;
297 if (pred_info->has_freeing_call_p)
299 info->imm_dom_path_with_freeing_call_computed_p = true;
300 info->imm_dom_path_with_freeing_call_p = true;
301 info->being_visited_p = false;
302 return true;
306 FOR_EACH_EDGE (e, ei, bb->preds)
308 if (e->src == dom)
309 continue;
311 basic_block src;
312 for (src = e->src; src != dom; )
314 sanopt_info *pred_info = (sanopt_info *) src->aux;
315 if (pred_info->being_visited_p)
316 break;
317 basic_block imm = get_immediate_dominator (CDI_DOMINATORS, src);
318 if (imm_dom_path_with_freeing_call (src, imm))
320 info->imm_dom_path_with_freeing_call_computed_p = true;
321 info->imm_dom_path_with_freeing_call_p = true;
322 info->being_visited_p = false;
323 return true;
325 src = imm;
329 info->imm_dom_path_with_freeing_call_computed_p = true;
330 info->imm_dom_path_with_freeing_call_p = false;
331 info->being_visited_p = false;
332 return false;
335 /* Get the first dominating check from the list of stored checks.
336 Non-dominating checks are silently dropped. */
338 static gimple *
339 maybe_get_dominating_check (auto_vec<gimple *> &v)
341 for (; !v.is_empty (); v.pop ())
343 gimple *g = v.last ();
344 sanopt_info *si = (sanopt_info *) gimple_bb (g)->aux;
345 if (!si->visited_p)
346 /* At this point we shouldn't have any statements
347 that aren't dominating the current BB. */
348 return g;
350 return NULL;
353 /* Optimize away redundant UBSAN_NULL calls. */
355 static bool
356 maybe_optimize_ubsan_null_ifn (struct sanopt_ctx *ctx, gimple *stmt)
358 gcc_assert (gimple_call_num_args (stmt) == 3);
359 tree ptr = gimple_call_arg (stmt, 0);
360 tree cur_align = gimple_call_arg (stmt, 2);
361 gcc_assert (TREE_CODE (cur_align) == INTEGER_CST);
362 bool remove = false;
364 auto_vec<gimple *> &v = ctx->null_check_map.get_or_insert (ptr);
365 gimple *g = maybe_get_dominating_check (v);
366 if (!g)
368 /* For this PTR we don't have any UBSAN_NULL stmts recorded, so there's
369 nothing to optimize yet. */
370 v.safe_push (stmt);
371 return false;
374 /* We already have recorded a UBSAN_NULL check for this pointer. Perhaps we
375 can drop this one. But only if this check doesn't specify stricter
376 alignment. */
378 tree align = gimple_call_arg (g, 2);
379 int kind = tree_to_shwi (gimple_call_arg (g, 1));
380 /* If this is a NULL pointer check where we had segv anyway, we can
381 remove it. */
382 if (integer_zerop (align)
383 && (kind == UBSAN_LOAD_OF
384 || kind == UBSAN_STORE_OF
385 || kind == UBSAN_MEMBER_ACCESS))
386 remove = true;
387 /* Otherwise remove the check in non-recovering mode, or if the
388 stmts have same location. */
389 else if (integer_zerop (align))
390 remove = (flag_sanitize_recover & SANITIZE_NULL) == 0
391 || flag_sanitize_undefined_trap_on_error
392 || gimple_location (g) == gimple_location (stmt);
393 else if (tree_int_cst_le (cur_align, align))
394 remove = (flag_sanitize_recover & SANITIZE_ALIGNMENT) == 0
395 || flag_sanitize_undefined_trap_on_error
396 || gimple_location (g) == gimple_location (stmt);
398 if (!remove && gimple_bb (g) == gimple_bb (stmt)
399 && tree_int_cst_compare (cur_align, align) == 0)
400 v.pop ();
402 if (!remove)
403 v.safe_push (stmt);
404 return remove;
407 /* Return true when pointer PTR for a given CUR_OFFSET is already sanitized
408 in a given sanitization context CTX. */
410 static bool
411 has_dominating_ubsan_ptr_check (sanopt_ctx *ctx, tree ptr,
412 offset_int &cur_offset)
414 bool pos_p = !wi::neg_p (cur_offset);
415 sanopt_tree_couple couple;
416 couple.ptr = ptr;
417 couple.pos_p = pos_p;
419 auto_vec<gimple *> &v = ctx->ptr_check_map.get_or_insert (couple);
420 gimple *g = maybe_get_dominating_check (v);
421 if (!g)
422 return false;
424 /* We already have recorded a UBSAN_PTR check for this pointer. Perhaps we
425 can drop this one. But only if this check doesn't specify larger offset.
427 tree offset = gimple_call_arg (g, 1);
428 gcc_assert (TREE_CODE (offset) == INTEGER_CST);
429 offset_int ooffset = wi::sext (wi::to_offset (offset), POINTER_SIZE);
431 if (pos_p)
433 if (wi::les_p (cur_offset, ooffset))
434 return true;
436 else if (!pos_p && wi::les_p (ooffset, cur_offset))
437 return true;
439 return false;
442 /* Record UBSAN_PTR check of given context CTX. Register pointer PTR on
443 a given OFFSET that it's handled by GIMPLE STMT. */
445 static void
446 record_ubsan_ptr_check_stmt (sanopt_ctx *ctx, gimple *stmt, tree ptr,
447 const offset_int &offset)
449 sanopt_tree_couple couple;
450 couple.ptr = ptr;
451 couple.pos_p = !wi::neg_p (offset);
453 auto_vec<gimple *> &v = ctx->ptr_check_map.get_or_insert (couple);
454 v.safe_push (stmt);
457 /* Optimize away redundant UBSAN_PTR calls. */
459 static bool
460 maybe_optimize_ubsan_ptr_ifn (sanopt_ctx *ctx, gimple *stmt)
462 poly_int64 bitsize, pbitpos;
463 machine_mode mode;
464 int volatilep = 0, reversep, unsignedp = 0;
465 tree offset;
467 gcc_assert (gimple_call_num_args (stmt) == 2);
468 tree ptr = gimple_call_arg (stmt, 0);
469 tree off = gimple_call_arg (stmt, 1);
471 if (TREE_CODE (off) != INTEGER_CST)
472 return false;
474 if (integer_zerop (off))
475 return true;
477 offset_int cur_offset = wi::sext (wi::to_offset (off), POINTER_SIZE);
478 if (has_dominating_ubsan_ptr_check (ctx, ptr, cur_offset))
479 return true;
481 tree base = ptr;
482 if (TREE_CODE (base) == ADDR_EXPR)
484 base = TREE_OPERAND (base, 0);
486 HOST_WIDE_INT bitpos;
487 base = get_inner_reference (base, &bitsize, &pbitpos, &offset, &mode,
488 &unsignedp, &reversep, &volatilep);
489 if (offset == NULL_TREE
490 && DECL_P (base)
491 && pbitpos.is_constant (&bitpos))
493 gcc_assert (!DECL_REGISTER (base));
494 offset_int expr_offset = bitpos / BITS_PER_UNIT;
495 offset_int total_offset = expr_offset + cur_offset;
496 if (total_offset != wi::sext (total_offset, POINTER_SIZE))
498 record_ubsan_ptr_check_stmt (ctx, stmt, ptr, cur_offset);
499 return false;
502 /* If BASE is a fixed size automatic variable or
503 global variable defined in the current TU, we don't have
504 to instrument anything if offset is within address
505 of the variable. */
506 if ((VAR_P (base)
507 || TREE_CODE (base) == PARM_DECL
508 || TREE_CODE (base) == RESULT_DECL)
509 && DECL_SIZE_UNIT (base)
510 && TREE_CODE (DECL_SIZE_UNIT (base)) == INTEGER_CST
511 && (!is_global_var (base) || decl_binds_to_current_def_p (base)))
513 offset_int base_size = wi::to_offset (DECL_SIZE_UNIT (base));
514 if (bitpos >= 0
515 && wi::les_p (total_offset, base_size))
517 if (!wi::neg_p (total_offset)
518 && wi::les_p (total_offset, base_size))
519 return true;
523 /* Following expression: UBSAN_PTR (&MEM_REF[ptr + x], y) can be
524 handled as follows:
526 1) sign (x) == sign (y), then check for dominating check of (x + y)
527 2) sign (x) != sign (y), then first check if we have a dominating
528 check for ptr + x. If so, then we have 2 situations:
529 a) sign (x) == sign (x + y), here we are done, example:
530 UBSAN_PTR (&MEM_REF[ptr + 100], -50)
531 b) check for dominating check of ptr + x + y.
534 bool sign_cur_offset = !wi::neg_p (cur_offset);
535 bool sign_expr_offset = bitpos >= 0;
537 tree base_addr
538 = build1 (ADDR_EXPR, build_pointer_type (TREE_TYPE (base)), base);
540 bool add = false;
541 if (sign_cur_offset == sign_expr_offset)
543 if (has_dominating_ubsan_ptr_check (ctx, base_addr, total_offset))
544 return true;
545 else
546 add = true;
548 else
550 if (!has_dominating_ubsan_ptr_check (ctx, base_addr, expr_offset))
551 ; /* Don't record base_addr + expr_offset, it's not a guarding
552 check. */
553 else
555 bool sign_total_offset = !wi::neg_p (total_offset);
556 if (sign_expr_offset == sign_total_offset)
557 return true;
558 else
560 if (has_dominating_ubsan_ptr_check (ctx, base_addr,
561 total_offset))
562 return true;
563 else
564 add = true;
569 /* Record a new dominating check for base_addr + total_offset. */
570 if (add && !operand_equal_p (base, base_addr, 0))
571 record_ubsan_ptr_check_stmt (ctx, stmt, base_addr,
572 total_offset);
576 /* For this PTR we don't have any UBSAN_PTR stmts recorded, so there's
577 nothing to optimize yet. */
578 record_ubsan_ptr_check_stmt (ctx, stmt, ptr, cur_offset);
580 return false;
583 /* Optimize away redundant UBSAN_VPTR calls. The second argument
584 is the value loaded from the virtual table, so rely on FRE to find out
585 when we can actually optimize. */
587 static bool
588 maybe_optimize_ubsan_vptr_ifn (struct sanopt_ctx *ctx, gimple *stmt)
590 gcc_assert (gimple_call_num_args (stmt) == 5);
591 sanopt_tree_triplet triplet;
592 triplet.t1 = gimple_call_arg (stmt, 0);
593 triplet.t2 = gimple_call_arg (stmt, 1);
594 triplet.t3 = gimple_call_arg (stmt, 3);
596 auto_vec<gimple *> &v = ctx->vptr_check_map.get_or_insert (triplet);
597 gimple *g = maybe_get_dominating_check (v);
598 if (!g)
600 /* For this PTR we don't have any UBSAN_VPTR stmts recorded, so there's
601 nothing to optimize yet. */
602 v.safe_push (stmt);
603 return false;
606 return true;
609 /* Returns TRUE if ASan check of length LEN in block BB can be removed
610 if preceded by checks in V. */
612 static bool
613 can_remove_asan_check (auto_vec<gimple *> &v, tree len, basic_block bb)
615 unsigned int i;
616 gimple *g;
617 gimple *to_pop = NULL;
618 bool remove = false;
619 basic_block last_bb = bb;
620 bool cleanup = false;
622 FOR_EACH_VEC_ELT_REVERSE (v, i, g)
624 basic_block gbb = gimple_bb (g);
625 sanopt_info *si = (sanopt_info *) gbb->aux;
626 if (gimple_uid (g) < si->freeing_call_events)
628 /* If there is a potentially freeing call after g in gbb, we should
629 remove it from the vector, can't use in optimization. */
630 cleanup = true;
631 continue;
634 tree glen = gimple_call_arg (g, 2);
635 gcc_assert (TREE_CODE (glen) == INTEGER_CST);
637 /* If we've checked only smaller length than we want to check now,
638 we can't remove the current stmt. If g is in the same basic block,
639 we want to remove it though, as the current stmt is better. */
640 if (tree_int_cst_lt (glen, len))
642 if (gbb == bb)
644 to_pop = g;
645 cleanup = true;
647 continue;
650 while (last_bb != gbb)
652 /* Paths from last_bb to bb have been checked before.
653 gbb is necessarily a dominator of last_bb, but not necessarily
654 immediate dominator. */
655 if (((sanopt_info *) last_bb->aux)->freeing_call_events)
656 break;
658 basic_block imm = get_immediate_dominator (CDI_DOMINATORS, last_bb);
659 gcc_assert (imm);
660 if (imm_dom_path_with_freeing_call (last_bb, imm))
661 break;
663 last_bb = imm;
665 if (last_bb == gbb)
666 remove = true;
667 break;
670 if (cleanup)
672 unsigned int j = 0, l = v.length ();
673 for (i = 0; i < l; i++)
674 if (v[i] != to_pop
675 && (gimple_uid (v[i])
676 == ((sanopt_info *)
677 gimple_bb (v[i])->aux)->freeing_call_events))
679 if (i != j)
680 v[j] = v[i];
681 j++;
683 v.truncate (j);
686 return remove;
689 /* Optimize away redundant ASAN_CHECK calls. */
691 static bool
692 maybe_optimize_asan_check_ifn (struct sanopt_ctx *ctx, gimple *stmt)
694 gcc_assert (gimple_call_num_args (stmt) == 4);
695 tree ptr = gimple_call_arg (stmt, 1);
696 tree len = gimple_call_arg (stmt, 2);
697 basic_block bb = gimple_bb (stmt);
698 sanopt_info *info = (sanopt_info *) bb->aux;
700 if (TREE_CODE (len) != INTEGER_CST)
701 return false;
702 if (integer_zerop (len))
703 return false;
705 gimple_set_uid (stmt, info->freeing_call_events);
707 auto_vec<gimple *> *ptr_checks = &ctx->asan_check_map.get_or_insert (ptr);
709 tree base_addr = maybe_get_single_definition (ptr);
710 auto_vec<gimple *> *base_checks = NULL;
711 if (base_addr)
713 base_checks = &ctx->asan_check_map.get_or_insert (base_addr);
714 /* Original pointer might have been invalidated. */
715 ptr_checks = ctx->asan_check_map.get (ptr);
718 gimple *g = maybe_get_dominating_check (*ptr_checks);
719 gimple *g2 = NULL;
721 if (base_checks)
722 /* Try with base address as well. */
723 g2 = maybe_get_dominating_check (*base_checks);
725 if (g == NULL && g2 == NULL)
727 /* For this PTR we don't have any ASAN_CHECK stmts recorded, so there's
728 nothing to optimize yet. */
729 ptr_checks->safe_push (stmt);
730 if (base_checks)
731 base_checks->safe_push (stmt);
732 return false;
735 bool remove = false;
737 if (ptr_checks)
738 remove = can_remove_asan_check (*ptr_checks, len, bb);
740 if (!remove && base_checks)
741 /* Try with base address as well. */
742 remove = can_remove_asan_check (*base_checks, len, bb);
744 if (!remove)
746 ptr_checks->safe_push (stmt);
747 if (base_checks)
748 base_checks->safe_push (stmt);
751 return remove;
754 /* Try to optimize away redundant UBSAN_NULL and ASAN_CHECK calls.
756 We walk blocks in the CFG via a depth first search of the dominator
757 tree; we push unique UBSAN_NULL or ASAN_CHECK statements into a vector
758 in the NULL_CHECK_MAP or ASAN_CHECK_MAP hash maps as we enter the
759 blocks. When leaving a block, we mark the block as visited; then
760 when checking the statements in the vector, we ignore statements that
761 are coming from already visited blocks, because these cannot dominate
762 anything anymore. CTX is a sanopt context. */
764 static void
765 sanopt_optimize_walker (basic_block bb, struct sanopt_ctx *ctx)
767 basic_block son;
768 gimple_stmt_iterator gsi;
769 sanopt_info *info = (sanopt_info *) bb->aux;
770 bool asan_check_optimize = (flag_sanitize & SANITIZE_ADDRESS) != 0;
772 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi);)
774 gimple *stmt = gsi_stmt (gsi);
775 bool remove = false;
777 if (!is_gimple_call (stmt))
779 /* Handle asm volatile or asm with "memory" clobber
780 the same as potentionally freeing call. */
781 gasm *asm_stmt = dyn_cast <gasm *> (stmt);
782 if (asm_stmt
783 && asan_check_optimize
784 && (gimple_asm_clobbers_memory_p (asm_stmt)
785 || gimple_asm_volatile_p (asm_stmt)))
786 info->freeing_call_events++;
787 gsi_next (&gsi);
788 continue;
791 if (asan_check_optimize && !nonfreeing_call_p (stmt))
792 info->freeing_call_events++;
794 /* If __asan_before_dynamic_init ("module"); is followed by
795 __asan_after_dynamic_init (); without intervening memory loads/stores,
796 there is nothing to guard, so optimize both away. */
797 if (asan_check_optimize
798 && gimple_call_builtin_p (stmt, BUILT_IN_ASAN_BEFORE_DYNAMIC_INIT))
800 use_operand_p use;
801 gimple *use_stmt;
802 if (single_imm_use (gimple_vdef (stmt), &use, &use_stmt))
804 if (is_gimple_call (use_stmt)
805 && gimple_call_builtin_p (use_stmt,
806 BUILT_IN_ASAN_AFTER_DYNAMIC_INIT))
808 unlink_stmt_vdef (use_stmt);
809 gimple_stmt_iterator gsi2 = gsi_for_stmt (use_stmt);
810 gsi_remove (&gsi2, true);
811 remove = true;
816 if (gimple_call_internal_p (stmt))
817 switch (gimple_call_internal_fn (stmt))
819 case IFN_UBSAN_NULL:
820 remove = maybe_optimize_ubsan_null_ifn (ctx, stmt);
821 break;
822 case IFN_UBSAN_VPTR:
823 remove = maybe_optimize_ubsan_vptr_ifn (ctx, stmt);
824 break;
825 case IFN_UBSAN_PTR:
826 remove = maybe_optimize_ubsan_ptr_ifn (ctx, stmt);
827 break;
828 case IFN_ASAN_CHECK:
829 if (asan_check_optimize)
830 remove = maybe_optimize_asan_check_ifn (ctx, stmt);
831 if (!remove)
832 ctx->asan_num_accesses++;
833 break;
834 case IFN_ASAN_MARK:
835 ctx->contains_asan_mark = true;
836 break;
837 default:
838 break;
841 if (remove)
843 /* Drop this check. */
844 if (dump_file && (dump_flags & TDF_DETAILS))
846 fprintf (dump_file, "Optimizing out: ");
847 print_gimple_stmt (dump_file, stmt, 0, dump_flags);
849 unlink_stmt_vdef (stmt);
850 gsi_remove (&gsi, true);
852 else
854 if (dump_file && (dump_flags & TDF_DETAILS))
856 fprintf (dump_file, "Leaving: ");
857 print_gimple_stmt (dump_file, stmt, 0, dump_flags);
860 gsi_next (&gsi);
864 if (asan_check_optimize)
866 info->has_freeing_call_p = info->freeing_call_events != 0;
867 info->has_freeing_call_computed_p = true;
870 for (son = first_dom_son (CDI_DOMINATORS, bb);
871 son;
872 son = next_dom_son (CDI_DOMINATORS, son))
873 sanopt_optimize_walker (son, ctx);
875 /* We're leaving this BB, so mark it to that effect. */
876 info->visited_p = true;
879 /* Try to remove redundant sanitizer checks in function FUN. */
881 static int
882 sanopt_optimize (function *fun, bool *contains_asan_mark)
884 struct sanopt_ctx ctx;
885 ctx.asan_num_accesses = 0;
886 ctx.contains_asan_mark = false;
888 /* Set up block info for each basic block. */
889 alloc_aux_for_blocks (sizeof (sanopt_info));
891 /* We're going to do a dominator walk, so ensure that we have
892 dominance information. */
893 calculate_dominance_info (CDI_DOMINATORS);
895 /* Recursively walk the dominator tree optimizing away
896 redundant checks. */
897 sanopt_optimize_walker (ENTRY_BLOCK_PTR_FOR_FN (fun), &ctx);
899 free_aux_for_blocks ();
901 *contains_asan_mark = ctx.contains_asan_mark;
902 return ctx.asan_num_accesses;
905 /* Perform optimization of sanitize functions. */
907 namespace {
909 const pass_data pass_data_sanopt =
911 GIMPLE_PASS, /* type */
912 "sanopt", /* name */
913 OPTGROUP_NONE, /* optinfo_flags */
914 TV_NONE, /* tv_id */
915 ( PROP_ssa | PROP_cfg | PROP_gimple_leh ), /* properties_required */
916 0, /* properties_provided */
917 0, /* properties_destroyed */
918 0, /* todo_flags_start */
919 TODO_update_ssa, /* todo_flags_finish */
922 class pass_sanopt : public gimple_opt_pass
924 public:
925 pass_sanopt (gcc::context *ctxt)
926 : gimple_opt_pass (pass_data_sanopt, ctxt)
929 /* opt_pass methods: */
930 virtual bool gate (function *) { return flag_sanitize; }
931 virtual unsigned int execute (function *);
933 }; // class pass_sanopt
935 /* Sanitize all ASAN_MARK unpoison calls that are not reachable by a BB
936 that contains an ASAN_MARK poison. All these ASAN_MARK unpoison call
937 can be removed as all variables are unpoisoned in a function prologue. */
939 static void
940 sanitize_asan_mark_unpoison (void)
942 /* 1) Find all BBs that contain an ASAN_MARK poison call. */
943 auto_sbitmap with_poison (last_basic_block_for_fn (cfun) + 1);
944 bitmap_clear (with_poison);
945 basic_block bb;
947 FOR_EACH_BB_FN (bb, cfun)
949 if (bitmap_bit_p (with_poison, bb->index))
950 continue;
952 gimple_stmt_iterator gsi;
953 for (gsi = gsi_last_bb (bb); !gsi_end_p (gsi); gsi_prev (&gsi))
955 gimple *stmt = gsi_stmt (gsi);
956 if (asan_mark_p (stmt, ASAN_MARK_POISON))
958 bitmap_set_bit (with_poison, bb->index);
959 break;
964 auto_sbitmap poisoned (last_basic_block_for_fn (cfun) + 1);
965 bitmap_clear (poisoned);
966 auto_sbitmap worklist (last_basic_block_for_fn (cfun) + 1);
967 bitmap_copy (worklist, with_poison);
969 /* 2) Propagate the information to all reachable blocks. */
970 while (!bitmap_empty_p (worklist))
972 unsigned i = bitmap_first_set_bit (worklist);
973 bitmap_clear_bit (worklist, i);
974 basic_block bb = BASIC_BLOCK_FOR_FN (cfun, i);
975 gcc_assert (bb);
977 edge e;
978 edge_iterator ei;
979 FOR_EACH_EDGE (e, ei, bb->succs)
980 if (!bitmap_bit_p (poisoned, e->dest->index))
982 bitmap_set_bit (poisoned, e->dest->index);
983 bitmap_set_bit (worklist, e->dest->index);
987 /* 3) Iterate all BBs not included in POISONED BBs and remove unpoison
988 ASAN_MARK preceding an ASAN_MARK poison (which can still happen). */
989 FOR_EACH_BB_FN (bb, cfun)
991 if (bitmap_bit_p (poisoned, bb->index))
992 continue;
994 gimple_stmt_iterator gsi;
995 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi);)
997 gimple *stmt = gsi_stmt (gsi);
998 if (gimple_call_internal_p (stmt, IFN_ASAN_MARK))
1000 if (asan_mark_p (stmt, ASAN_MARK_POISON))
1001 break;
1002 else
1004 if (dump_file)
1005 fprintf (dump_file, "Removing ASAN_MARK unpoison\n");
1006 unlink_stmt_vdef (stmt);
1007 release_defs (stmt);
1008 gsi_remove (&gsi, true);
1009 continue;
1013 gsi_next (&gsi);
1018 /* Return true when STMT is either ASAN_CHECK call or a call of a function
1019 that can contain an ASAN_CHECK. */
1021 static bool
1022 maybe_contains_asan_check (gimple *stmt)
1024 if (is_gimple_call (stmt))
1026 if (gimple_call_internal_p (stmt, IFN_ASAN_MARK))
1027 return false;
1028 else
1029 return !(gimple_call_flags (stmt) & ECF_CONST);
1031 else if (is_a<gasm *> (stmt))
1032 return true;
1034 return false;
1037 /* Sanitize all ASAN_MARK poison calls that are not followed by an ASAN_CHECK
1038 call. These calls can be removed. */
1040 static void
1041 sanitize_asan_mark_poison (void)
1043 /* 1) Find all BBs that possibly contain an ASAN_CHECK. */
1044 auto_sbitmap with_check (last_basic_block_for_fn (cfun) + 1);
1045 bitmap_clear (with_check);
1046 basic_block bb;
1048 FOR_EACH_BB_FN (bb, cfun)
1050 gimple_stmt_iterator gsi;
1051 for (gsi = gsi_last_bb (bb); !gsi_end_p (gsi); gsi_prev (&gsi))
1053 gimple *stmt = gsi_stmt (gsi);
1054 if (maybe_contains_asan_check (stmt))
1056 bitmap_set_bit (with_check, bb->index);
1057 break;
1062 auto_sbitmap can_reach_check (last_basic_block_for_fn (cfun) + 1);
1063 bitmap_clear (can_reach_check);
1064 auto_sbitmap worklist (last_basic_block_for_fn (cfun) + 1);
1065 bitmap_copy (worklist, with_check);
1067 /* 2) Propagate the information to all definitions blocks. */
1068 while (!bitmap_empty_p (worklist))
1070 unsigned i = bitmap_first_set_bit (worklist);
1071 bitmap_clear_bit (worklist, i);
1072 basic_block bb = BASIC_BLOCK_FOR_FN (cfun, i);
1073 gcc_assert (bb);
1075 edge e;
1076 edge_iterator ei;
1077 FOR_EACH_EDGE (e, ei, bb->preds)
1078 if (!bitmap_bit_p (can_reach_check, e->src->index))
1080 bitmap_set_bit (can_reach_check, e->src->index);
1081 bitmap_set_bit (worklist, e->src->index);
1085 /* 3) Iterate all BBs not included in CAN_REACH_CHECK BBs and remove poison
1086 ASAN_MARK not followed by a call to function having an ASAN_CHECK. */
1087 FOR_EACH_BB_FN (bb, cfun)
1089 if (bitmap_bit_p (can_reach_check, bb->index))
1090 continue;
1092 gimple_stmt_iterator gsi;
1093 for (gsi = gsi_last_bb (bb); !gsi_end_p (gsi);)
1095 gimple *stmt = gsi_stmt (gsi);
1096 if (maybe_contains_asan_check (stmt))
1097 break;
1098 else if (asan_mark_p (stmt, ASAN_MARK_POISON))
1100 if (dump_file)
1101 fprintf (dump_file, "Removing ASAN_MARK poison\n");
1102 unlink_stmt_vdef (stmt);
1103 release_defs (stmt);
1104 gimple_stmt_iterator gsi2 = gsi;
1105 gsi_prev (&gsi);
1106 gsi_remove (&gsi2, true);
1107 continue;
1110 gsi_prev (&gsi);
1115 /* Rewrite all usages of tree OP which is a PARM_DECL with a VAR_DECL
1116 that is it's DECL_VALUE_EXPR. */
1118 static tree
1119 rewrite_usage_of_param (tree *op, int *walk_subtrees, void *)
1121 if (TREE_CODE (*op) == PARM_DECL && DECL_HAS_VALUE_EXPR_P (*op))
1123 *op = DECL_VALUE_EXPR (*op);
1124 *walk_subtrees = 0;
1127 return NULL;
1130 /* For a given function FUN, rewrite all addressable parameters so that
1131 a new automatic variable is introduced. Right after function entry
1132 a parameter is assigned to the variable. */
1134 static void
1135 sanitize_rewrite_addressable_params (function *fun)
1137 gimple *g;
1138 gimple_seq stmts = NULL;
1139 bool has_any_addressable_param = false;
1140 auto_vec<tree> clear_value_expr_list;
1142 for (tree arg = DECL_ARGUMENTS (current_function_decl);
1143 arg; arg = DECL_CHAIN (arg))
1145 tree type = TREE_TYPE (arg);
1146 if (TREE_ADDRESSABLE (arg) && !TREE_ADDRESSABLE (type)
1147 && TREE_CODE (TYPE_SIZE (type)) == INTEGER_CST)
1149 TREE_ADDRESSABLE (arg) = 0;
1150 /* The parameter is no longer addressable. */
1151 has_any_addressable_param = true;
1153 /* Create a new automatic variable. */
1154 tree var = build_decl (DECL_SOURCE_LOCATION (arg),
1155 VAR_DECL, DECL_NAME (arg), type);
1156 TREE_ADDRESSABLE (var) = 1;
1157 DECL_IGNORED_P (var) = 1;
1159 gimple_add_tmp_var (var);
1161 if (dump_file)
1162 fprintf (dump_file,
1163 "Rewriting parameter whose address is taken: %s\n",
1164 IDENTIFIER_POINTER (DECL_NAME (arg)));
1166 gcc_assert (!DECL_HAS_VALUE_EXPR_P (arg));
1168 SET_DECL_PT_UID (var, DECL_PT_UID (arg));
1170 /* Assign value of parameter to newly created variable. */
1171 if ((TREE_CODE (type) == COMPLEX_TYPE
1172 || TREE_CODE (type) == VECTOR_TYPE))
1174 /* We need to create a SSA name that will be used for the
1175 assignment. */
1176 DECL_GIMPLE_REG_P (arg) = 1;
1177 tree tmp = get_or_create_ssa_default_def (cfun, arg);
1178 g = gimple_build_assign (var, tmp);
1179 gimple_set_location (g, DECL_SOURCE_LOCATION (arg));
1180 gimple_seq_add_stmt (&stmts, g);
1182 else
1184 g = gimple_build_assign (var, arg);
1185 gimple_set_location (g, DECL_SOURCE_LOCATION (arg));
1186 gimple_seq_add_stmt (&stmts, g);
1189 if (target_for_debug_bind (arg))
1191 g = gimple_build_debug_bind (arg, var, NULL);
1192 gimple_seq_add_stmt (&stmts, g);
1193 clear_value_expr_list.safe_push (arg);
1196 DECL_HAS_VALUE_EXPR_P (arg) = 1;
1197 SET_DECL_VALUE_EXPR (arg, var);
1201 if (!has_any_addressable_param)
1202 return;
1204 /* Replace all usages of PARM_DECLs with the newly
1205 created variable VAR. */
1206 basic_block bb;
1207 FOR_EACH_BB_FN (bb, fun)
1209 gimple_stmt_iterator gsi;
1210 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1212 gimple *stmt = gsi_stmt (gsi);
1213 gimple_stmt_iterator it = gsi_for_stmt (stmt);
1214 walk_gimple_stmt (&it, NULL, rewrite_usage_of_param, NULL);
1216 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1218 gphi *phi = dyn_cast<gphi *> (gsi_stmt (gsi));
1219 for (unsigned i = 0; i < gimple_phi_num_args (phi); ++i)
1221 hash_set<tree> visited_nodes;
1222 walk_tree (gimple_phi_arg_def_ptr (phi, i),
1223 rewrite_usage_of_param, NULL, &visited_nodes);
1228 /* Unset value expr for parameters for which we created debug bind
1229 expressions. */
1230 unsigned i;
1231 tree arg;
1232 FOR_EACH_VEC_ELT (clear_value_expr_list, i, arg)
1234 DECL_HAS_VALUE_EXPR_P (arg) = 0;
1235 SET_DECL_VALUE_EXPR (arg, NULL_TREE);
1238 /* Insert default assignments at the beginning of a function. */
1239 basic_block entry_bb = ENTRY_BLOCK_PTR_FOR_FN (fun);
1240 entry_bb = split_edge (single_succ_edge (entry_bb));
1242 gimple_stmt_iterator gsi = gsi_start_bb (entry_bb);
1243 gsi_insert_seq_before (&gsi, stmts, GSI_NEW_STMT);
1246 unsigned int
1247 pass_sanopt::execute (function *fun)
1249 basic_block bb;
1250 int asan_num_accesses = 0;
1251 bool contains_asan_mark = false;
1253 /* Try to remove redundant checks. */
1254 if (optimize
1255 && (flag_sanitize
1256 & (SANITIZE_NULL | SANITIZE_ALIGNMENT
1257 | SANITIZE_ADDRESS | SANITIZE_VPTR | SANITIZE_POINTER_OVERFLOW)))
1258 asan_num_accesses = sanopt_optimize (fun, &contains_asan_mark);
1259 else if (flag_sanitize & SANITIZE_ADDRESS)
1261 gimple_stmt_iterator gsi;
1262 FOR_EACH_BB_FN (bb, fun)
1263 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1265 gimple *stmt = gsi_stmt (gsi);
1266 if (gimple_call_internal_p (stmt, IFN_ASAN_CHECK))
1267 ++asan_num_accesses;
1268 else if (gimple_call_internal_p (stmt, IFN_ASAN_MARK))
1269 contains_asan_mark = true;
1273 if (contains_asan_mark)
1275 sanitize_asan_mark_unpoison ();
1276 sanitize_asan_mark_poison ();
1279 if (asan_sanitize_stack_p ())
1280 sanitize_rewrite_addressable_params (fun);
1282 bool use_calls = ASAN_INSTRUMENTATION_WITH_CALL_THRESHOLD < INT_MAX
1283 && asan_num_accesses >= ASAN_INSTRUMENTATION_WITH_CALL_THRESHOLD;
1285 hash_map<tree, tree> shadow_vars_mapping;
1286 bool need_commit_edge_insert = false;
1287 FOR_EACH_BB_FN (bb, fun)
1289 gimple_stmt_iterator gsi;
1290 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); )
1292 gimple *stmt = gsi_stmt (gsi);
1293 bool no_next = false;
1295 if (!is_gimple_call (stmt))
1297 gsi_next (&gsi);
1298 continue;
1301 if (gimple_call_internal_p (stmt))
1303 enum internal_fn ifn = gimple_call_internal_fn (stmt);
1304 switch (ifn)
1306 case IFN_UBSAN_NULL:
1307 no_next = ubsan_expand_null_ifn (&gsi);
1308 break;
1309 case IFN_UBSAN_BOUNDS:
1310 no_next = ubsan_expand_bounds_ifn (&gsi);
1311 break;
1312 case IFN_UBSAN_OBJECT_SIZE:
1313 no_next = ubsan_expand_objsize_ifn (&gsi);
1314 break;
1315 case IFN_UBSAN_PTR:
1316 no_next = ubsan_expand_ptr_ifn (&gsi);
1317 break;
1318 case IFN_UBSAN_VPTR:
1319 no_next = ubsan_expand_vptr_ifn (&gsi);
1320 break;
1321 case IFN_ASAN_CHECK:
1322 no_next = asan_expand_check_ifn (&gsi, use_calls);
1323 break;
1324 case IFN_ASAN_MARK:
1325 no_next = asan_expand_mark_ifn (&gsi);
1326 break;
1327 case IFN_ASAN_POISON:
1328 no_next = asan_expand_poison_ifn (&gsi,
1329 &need_commit_edge_insert,
1330 shadow_vars_mapping);
1331 break;
1332 default:
1333 break;
1336 else if (gimple_call_builtin_p (stmt, BUILT_IN_NORMAL))
1338 tree callee = gimple_call_fndecl (stmt);
1339 switch (DECL_FUNCTION_CODE (callee))
1341 case BUILT_IN_UNREACHABLE:
1342 if (sanitize_flags_p (SANITIZE_UNREACHABLE))
1343 no_next = ubsan_instrument_unreachable (&gsi);
1344 break;
1345 default:
1346 break;
1350 if (dump_file && (dump_flags & TDF_DETAILS))
1352 fprintf (dump_file, "Expanded: ");
1353 print_gimple_stmt (dump_file, stmt, 0, dump_flags);
1356 if (!no_next)
1357 gsi_next (&gsi);
1361 if (need_commit_edge_insert)
1362 gsi_commit_edge_inserts ();
1364 return 0;
1367 } // anon namespace
1369 gimple_opt_pass *
1370 make_pass_sanopt (gcc::context *ctxt)
1372 return new pass_sanopt (ctxt);