kernel - support dummy reallocblks in devfs
[dragonfly.git] / contrib / gcc-5.0 / gcc / tree-chkp.c
blob218c7eb40aba71068e65d40ec2d4f6cfcea96ca9
1 /* Pointer Bounds Checker insrumentation pass.
2 Copyright (C) 2014-2015 Free Software Foundation, Inc.
3 Contributed by Ilya Enkovich (ilya.enkovich@intel.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 "hash-set.h"
25 #include "machmode.h"
26 #include "vec.h"
27 #include "double-int.h"
28 #include "input.h"
29 #include "alias.h"
30 #include "symtab.h"
31 #include "options.h"
32 #include "wide-int.h"
33 #include "inchash.h"
34 #include "tree.h"
35 #include "fold-const.h"
36 #include "stor-layout.h"
37 #include "varasm.h"
38 #include "target.h"
39 #include "tree-iterator.h"
40 #include "tree-cfg.h"
41 #include "langhooks.h"
42 #include "tree-pass.h"
43 #include "diagnostic.h"
44 #include "ggc.h"
45 #include "is-a.h"
46 #include "cfgloop.h"
47 #include "stringpool.h"
48 #include "tree-ssa-alias.h"
49 #include "tree-ssanames.h"
50 #include "tree-ssa-operands.h"
51 #include "tree-ssa-address.h"
52 #include "tree-ssa.h"
53 #include "predict.h"
54 #include "dominance.h"
55 #include "cfg.h"
56 #include "basic-block.h"
57 #include "tree-ssa-loop-niter.h"
58 #include "gimple-expr.h"
59 #include "gimple.h"
60 #include "tree-phinodes.h"
61 #include "gimple-ssa.h"
62 #include "ssa-iterators.h"
63 #include "gimple-pretty-print.h"
64 #include "gimple-iterator.h"
65 #include "gimplify.h"
66 #include "gimplify-me.h"
67 #include "print-tree.h"
68 #include "hashtab.h"
69 #include "tm.h"
70 #include "hard-reg-set.h"
71 #include "function.h"
72 #include "rtl.h"
73 #include "flags.h"
74 #include "statistics.h"
75 #include "real.h"
76 #include "fixed-value.h"
77 #include "insn-config.h"
78 #include "expmed.h"
79 #include "dojump.h"
80 #include "explow.h"
81 #include "calls.h"
82 #include "emit-rtl.h"
83 #include "stmt.h"
84 #include "expr.h"
85 #include "tree-ssa-propagate.h"
86 #include "gimple-fold.h"
87 #include "tree-chkp.h"
88 #include "gimple-walk.h"
89 #include "rtl.h" /* For MEM_P, assign_temp. */
90 #include "tree-dfa.h"
91 #include "ipa-ref.h"
92 #include "lto-streamer.h"
93 #include "cgraph.h"
94 #include "ipa-chkp.h"
95 #include "params.h"
97 /* Pointer Bounds Checker instruments code with memory checks to find
98 out-of-bounds memory accesses. Checks are performed by computing
99 bounds for each pointer and then comparing address of accessed
100 memory before pointer dereferencing.
102 1. Function clones.
104 See ipa-chkp.c.
106 2. Instrumentation.
108 There are few things to instrument:
110 a) Memory accesses - add checker calls to check address of accessed memory
111 against bounds of dereferenced pointer. Obviously safe memory
112 accesses like static variable access does not have to be instrumented
113 with checks.
115 Example:
117 val_2 = *p_1;
119 with 4 bytes access is transformed into:
121 __builtin___chkp_bndcl (__bound_tmp.1_3, p_1);
122 D.1_4 = p_1 + 3;
123 __builtin___chkp_bndcu (__bound_tmp.1_3, D.1_4);
124 val_2 = *p_1;
126 where __bound_tmp.1_3 are bounds computed for pointer p_1,
127 __builtin___chkp_bndcl is a lower bound check and
128 __builtin___chkp_bndcu is an upper bound check.
130 b) Pointer stores.
132 When pointer is stored in memory we need to store its bounds. To
133 achieve compatibility of instrumented code with regular codes
134 we have to keep data layout and store bounds in special bound tables
135 via special checker call. Implementation of bounds table may vary for
136 different platforms. It has to associate pointer value and its
137 location (it is required because we may have two equal pointers
138 with different bounds stored in different places) with bounds.
139 Another checker builtin allows to get bounds for specified pointer
140 loaded from specified location.
142 Example:
144 buf1[i_1] = &buf2;
146 is transformed into:
148 buf1[i_1] = &buf2;
149 D.1_2 = &buf1[i_1];
150 __builtin___chkp_bndstx (D.1_2, &buf2, __bound_tmp.1_2);
152 where __bound_tmp.1_2 are bounds of &buf2.
154 c) Static initialization.
156 The special case of pointer store is static pointer initialization.
157 Bounds initialization is performed in a few steps:
158 - register all static initializations in front-end using
159 chkp_register_var_initializer
160 - when file compilation finishes we create functions with special
161 attribute 'chkp ctor' and put explicit initialization code
162 (assignments) for all statically initialized pointers.
163 - when checker constructor is compiled checker pass adds required
164 bounds initialization for all statically initialized pointers
165 - since we do not actually need excess pointers initialization
166 in checker constructor we remove such assignments from them
168 d) Calls.
170 For each call in the code we add additional arguments to pass
171 bounds for pointer arguments. We determine type of call arguments
172 using arguments list from function declaration; if function
173 declaration is not available we use function type; otherwise
174 (e.g. for unnamed arguments) we use type of passed value. Function
175 declaration/type is replaced with the instrumented one.
177 Example:
179 val_1 = foo (&buf1, &buf2, &buf1, 0);
181 is translated into:
183 val_1 = foo.chkp (&buf1, __bound_tmp.1_2, &buf2, __bound_tmp.1_3,
184 &buf1, __bound_tmp.1_2, 0);
186 e) Returns.
188 If function returns a pointer value we have to return bounds also.
189 A new operand was added for return statement to hold returned bounds.
191 Example:
193 return &_buf1;
195 is transformed into
197 return &_buf1, __bound_tmp.1_1;
199 3. Bounds computation.
201 Compiler is fully responsible for computing bounds to be used for each
202 memory access. The first step for bounds computation is to find the
203 origin of pointer dereferenced for memory access. Basing on pointer
204 origin we define a way to compute its bounds. There are just few
205 possible cases:
207 a) Pointer is returned by call.
209 In this case we use corresponding checker builtin method to obtain returned
210 bounds.
212 Example:
214 buf_1 = malloc (size_2);
215 foo (buf_1);
217 is translated into:
219 buf_1 = malloc (size_2);
220 __bound_tmp.1_3 = __builtin___chkp_bndret (buf_1);
221 foo (buf_1, __bound_tmp.1_3);
223 b) Pointer is an address of an object.
225 In this case compiler tries to compute objects size and create corresponding
226 bounds. If object has incomplete type then special checker builtin is used to
227 obtain its size at runtime.
229 Example:
231 foo ()
233 <unnamed type> __bound_tmp.3;
234 static int buf[100];
236 <bb 3>:
237 __bound_tmp.3_2 = __builtin___chkp_bndmk (&buf, 400);
239 <bb 2>:
240 return &buf, __bound_tmp.3_2;
243 Example:
245 Address of an object 'extern int buf[]' with incomplete type is
246 returned.
248 foo ()
250 <unnamed type> __bound_tmp.4;
251 long unsigned int __size_tmp.3;
253 <bb 3>:
254 __size_tmp.3_4 = __builtin_ia32_sizeof (buf);
255 __bound_tmp.4_3 = __builtin_ia32_bndmk (&buf, __size_tmp.3_4);
257 <bb 2>:
258 return &buf, __bound_tmp.4_3;
261 c) Pointer is the result of object narrowing.
263 It happens when we use pointer to an object to compute pointer to a part
264 of an object. E.g. we take pointer to a field of a structure. In this
265 case we perform bounds intersection using bounds of original object and
266 bounds of object's part (which are computed basing on its type).
268 There may be some debatable questions about when narrowing should occur
269 and when it should not. To avoid false bound violations in correct
270 programs we do not perform narrowing when address of an array element is
271 obtained (it has address of the whole array) and when address of the first
272 structure field is obtained (because it is guaranteed to be equal to
273 address of the whole structure and it is legal to cast it back to structure).
275 Default narrowing behavior may be changed using compiler flags.
277 Example:
279 In this example address of the second structure field is returned.
281 foo (struct A * p, __bounds_type __bounds_of_p)
283 <unnamed type> __bound_tmp.3;
284 int * _2;
285 int * _5;
287 <bb 2>:
288 _5 = &p_1(D)->second_field;
289 __bound_tmp.3_6 = __builtin___chkp_bndmk (_5, 4);
290 __bound_tmp.3_8 = __builtin___chkp_intersect (__bound_tmp.3_6,
291 __bounds_of_p_3(D));
292 _2 = &p_1(D)->second_field;
293 return _2, __bound_tmp.3_8;
296 Example:
298 In this example address of the first field of array element is returned.
300 foo (struct A * p, __bounds_type __bounds_of_p, int i)
302 long unsigned int _3;
303 long unsigned int _4;
304 struct A * _6;
305 int * _7;
307 <bb 2>:
308 _3 = (long unsigned int) i_1(D);
309 _4 = _3 * 8;
310 _6 = p_5(D) + _4;
311 _7 = &_6->first_field;
312 return _7, __bounds_of_p_2(D);
316 d) Pointer is the result of pointer arithmetic or type cast.
318 In this case bounds of the base pointer are used. In case of binary
319 operation producing a pointer we are analyzing data flow further
320 looking for operand's bounds. One operand is considered as a base
321 if it has some valid bounds. If we fall into a case when none of
322 operands (or both of them) has valid bounds, a default bounds value
323 is used.
325 Trying to find out bounds for binary operations we may fall into
326 cyclic dependencies for pointers. To avoid infinite recursion all
327 walked phi nodes instantly obtain corresponding bounds but created
328 bounds are marked as incomplete. It helps us to stop DF walk during
329 bounds search.
331 When we reach pointer source, some args of incomplete bounds phi obtain
332 valid bounds and those values are propagated further through phi nodes.
333 If no valid bounds were found for phi node then we mark its result as
334 invalid bounds. Process stops when all incomplete bounds become either
335 valid or invalid and we are able to choose a pointer base.
337 e) Pointer is loaded from the memory.
339 In this case we just need to load bounds from the bounds table.
341 Example:
343 foo ()
345 <unnamed type> __bound_tmp.3;
346 static int * buf;
347 int * _2;
349 <bb 2>:
350 _2 = buf;
351 __bound_tmp.3_4 = __builtin___chkp_bndldx (&buf, _2);
352 return _2, __bound_tmp.3_4;
357 typedef void (*assign_handler)(tree, tree, void *);
359 static tree chkp_get_zero_bounds ();
360 static tree chkp_find_bounds (tree ptr, gimple_stmt_iterator *iter);
361 static tree chkp_find_bounds_loaded (tree ptr, tree ptr_src,
362 gimple_stmt_iterator *iter);
363 static void chkp_parse_array_and_component_ref (tree node, tree *ptr,
364 tree *elt, bool *safe,
365 bool *bitfield,
366 tree *bounds,
367 gimple_stmt_iterator *iter,
368 bool innermost_bounds);
370 #define chkp_bndldx_fndecl \
371 (targetm.builtin_chkp_function (BUILT_IN_CHKP_BNDLDX))
372 #define chkp_bndstx_fndecl \
373 (targetm.builtin_chkp_function (BUILT_IN_CHKP_BNDSTX))
374 #define chkp_checkl_fndecl \
375 (targetm.builtin_chkp_function (BUILT_IN_CHKP_BNDCL))
376 #define chkp_checku_fndecl \
377 (targetm.builtin_chkp_function (BUILT_IN_CHKP_BNDCU))
378 #define chkp_bndmk_fndecl \
379 (targetm.builtin_chkp_function (BUILT_IN_CHKP_BNDMK))
380 #define chkp_ret_bnd_fndecl \
381 (targetm.builtin_chkp_function (BUILT_IN_CHKP_BNDRET))
382 #define chkp_intersect_fndecl \
383 (targetm.builtin_chkp_function (BUILT_IN_CHKP_INTERSECT))
384 #define chkp_narrow_bounds_fndecl \
385 (targetm.builtin_chkp_function (BUILT_IN_CHKP_NARROW))
386 #define chkp_sizeof_fndecl \
387 (targetm.builtin_chkp_function (BUILT_IN_CHKP_SIZEOF))
388 #define chkp_extract_lower_fndecl \
389 (targetm.builtin_chkp_function (BUILT_IN_CHKP_EXTRACT_LOWER))
390 #define chkp_extract_upper_fndecl \
391 (targetm.builtin_chkp_function (BUILT_IN_CHKP_EXTRACT_UPPER))
393 static GTY (()) tree chkp_uintptr_type;
395 static GTY (()) tree chkp_zero_bounds_var;
396 static GTY (()) tree chkp_none_bounds_var;
398 static GTY (()) basic_block entry_block;
399 static GTY (()) tree zero_bounds;
400 static GTY (()) tree none_bounds;
401 static GTY (()) tree incomplete_bounds;
402 static GTY (()) tree tmp_var;
403 static GTY (()) tree size_tmp_var;
404 static GTY (()) bitmap chkp_abnormal_copies;
406 struct hash_set<tree> *chkp_invalid_bounds;
407 struct hash_set<tree> *chkp_completed_bounds_set;
408 struct hash_map<tree, tree> *chkp_reg_bounds;
409 struct hash_map<tree, tree> *chkp_bound_vars;
410 struct hash_map<tree, tree> *chkp_reg_addr_bounds;
411 struct hash_map<tree, tree> *chkp_incomplete_bounds_map;
412 struct hash_map<tree, tree> *chkp_bounds_map;
413 struct hash_map<tree, tree> *chkp_static_var_bounds;
415 static bool in_chkp_pass;
417 #define CHKP_BOUND_TMP_NAME "__bound_tmp"
418 #define CHKP_SIZE_TMP_NAME "__size_tmp"
419 #define CHKP_BOUNDS_OF_SYMBOL_PREFIX "__chkp_bounds_of_"
420 #define CHKP_STRING_BOUNDS_PREFIX "__chkp_string_bounds_"
421 #define CHKP_VAR_BOUNDS_PREFIX "__chkp_var_bounds_"
422 #define CHKP_ZERO_BOUNDS_VAR_NAME "__chkp_zero_bounds"
423 #define CHKP_NONE_BOUNDS_VAR_NAME "__chkp_none_bounds"
425 /* Static checker constructors may become very large and their
426 compilation with optimization may take too much time.
427 Therefore we put a limit to number of statements in one
428 constructor. Tests with 100 000 statically initialized
429 pointers showed following compilation times on Sandy Bridge
430 server (used -O2):
431 limit 100 => ~18 sec.
432 limit 300 => ~22 sec.
433 limit 1000 => ~30 sec.
434 limit 3000 => ~49 sec.
435 limit 5000 => ~55 sec.
436 limit 10000 => ~76 sec.
437 limit 100000 => ~532 sec. */
438 #define MAX_STMTS_IN_STATIC_CHKP_CTOR (PARAM_VALUE (PARAM_CHKP_MAX_CTOR_SIZE))
440 struct chkp_ctor_stmt_list
442 tree stmts;
443 int avail;
446 /* Return 1 if function FNDECL is instrumented by Pointer
447 Bounds Checker. */
448 bool
449 chkp_function_instrumented_p (tree fndecl)
451 return fndecl
452 && lookup_attribute ("chkp instrumented", DECL_ATTRIBUTES (fndecl));
455 /* Mark function FNDECL as instrumented. */
456 void
457 chkp_function_mark_instrumented (tree fndecl)
459 if (chkp_function_instrumented_p (fndecl))
460 return;
462 DECL_ATTRIBUTES (fndecl)
463 = tree_cons (get_identifier ("chkp instrumented"), NULL,
464 DECL_ATTRIBUTES (fndecl));
467 /* Return true when STMT is builtin call to instrumentation function
468 corresponding to CODE. */
470 bool
471 chkp_gimple_call_builtin_p (gimple call,
472 enum built_in_function code)
474 tree fndecl;
475 if (is_gimple_call (call)
476 && (fndecl = targetm.builtin_chkp_function (code))
477 && gimple_call_fndecl (call) == fndecl)
478 return true;
479 return false;
482 /* Emit code to build zero bounds and return RTL holding
483 the result. */
485 chkp_expand_zero_bounds ()
487 tree zero_bnd;
489 if (flag_chkp_use_static_const_bounds)
490 zero_bnd = chkp_get_zero_bounds_var ();
491 else
492 zero_bnd = chkp_build_make_bounds_call (integer_zero_node,
493 integer_zero_node);
494 return expand_normal (zero_bnd);
497 /* Emit code to store zero bounds for PTR located at MEM. */
498 void
499 chkp_expand_bounds_reset_for_mem (tree mem, tree ptr)
501 tree zero_bnd, bnd, addr, bndstx;
503 if (flag_chkp_use_static_const_bounds)
504 zero_bnd = chkp_get_zero_bounds_var ();
505 else
506 zero_bnd = chkp_build_make_bounds_call (integer_zero_node,
507 integer_zero_node);
508 bnd = make_tree (pointer_bounds_type_node,
509 assign_temp (pointer_bounds_type_node, 0, 1));
510 addr = build1 (ADDR_EXPR,
511 build_pointer_type (TREE_TYPE (mem)), mem);
512 bndstx = chkp_build_bndstx_call (addr, ptr, bnd);
514 expand_assignment (bnd, zero_bnd, false);
515 expand_normal (bndstx);
518 /* Build retbnd call for returned value RETVAL.
520 If BNDVAL is not NULL then result is stored
521 in it. Otherwise a temporary is created to
522 hold returned value.
524 GSI points to a position for a retbnd call
525 and is set to created stmt.
527 Cgraph edge is created for a new call if
528 UPDATE_EDGE is 1.
530 Obtained bounds are returned. */
531 tree
532 chkp_insert_retbnd_call (tree bndval, tree retval,
533 gimple_stmt_iterator *gsi)
535 gimple call;
537 if (!bndval)
538 bndval = create_tmp_reg (pointer_bounds_type_node, "retbnd");
540 call = gimple_build_call (chkp_ret_bnd_fndecl, 1, retval);
541 gimple_call_set_lhs (call, bndval);
542 gsi_insert_after (gsi, call, GSI_CONTINUE_LINKING);
544 return bndval;
547 /* Build a GIMPLE_CALL identical to CALL but skipping bounds
548 arguments. */
550 gcall *
551 chkp_copy_call_skip_bounds (gcall *call)
553 bitmap bounds;
554 unsigned i;
556 bitmap_obstack_initialize (NULL);
557 bounds = BITMAP_ALLOC (NULL);
559 for (i = 0; i < gimple_call_num_args (call); i++)
560 if (POINTER_BOUNDS_P (gimple_call_arg (call, i)))
561 bitmap_set_bit (bounds, i);
563 if (!bitmap_empty_p (bounds))
564 call = gimple_call_copy_skip_args (call, bounds);
565 gimple_call_set_with_bounds (call, false);
567 BITMAP_FREE (bounds);
568 bitmap_obstack_release (NULL);
570 return call;
573 /* Redirect edge E to the correct node according to call_stmt.
574 Return 1 if bounds removal from call_stmt should be done
575 instead of redirection. */
577 bool
578 chkp_redirect_edge (cgraph_edge *e)
580 bool instrumented = false;
581 tree decl = e->callee->decl;
583 if (e->callee->instrumentation_clone
584 || chkp_function_instrumented_p (decl))
585 instrumented = true;
587 if (instrumented
588 && !gimple_call_with_bounds_p (e->call_stmt))
589 e->redirect_callee (cgraph_node::get_create (e->callee->orig_decl));
590 else if (!instrumented
591 && gimple_call_with_bounds_p (e->call_stmt)
592 && !chkp_gimple_call_builtin_p (e->call_stmt, BUILT_IN_CHKP_BNDCL)
593 && !chkp_gimple_call_builtin_p (e->call_stmt, BUILT_IN_CHKP_BNDCU)
594 && !chkp_gimple_call_builtin_p (e->call_stmt, BUILT_IN_CHKP_BNDSTX))
596 if (e->callee->instrumented_version)
597 e->redirect_callee (e->callee->instrumented_version);
598 else
600 tree args = TYPE_ARG_TYPES (TREE_TYPE (decl));
601 /* Avoid bounds removal if all args will be removed. */
602 if (!args || TREE_VALUE (args) != void_type_node)
603 return true;
604 else
605 gimple_call_set_with_bounds (e->call_stmt, false);
609 return false;
612 /* Mark statement S to not be instrumented. */
613 static void
614 chkp_mark_stmt (gimple s)
616 gimple_set_plf (s, GF_PLF_1, true);
619 /* Mark statement S to be instrumented. */
620 static void
621 chkp_unmark_stmt (gimple s)
623 gimple_set_plf (s, GF_PLF_1, false);
626 /* Return 1 if statement S should not be instrumented. */
627 static bool
628 chkp_marked_stmt_p (gimple s)
630 return gimple_plf (s, GF_PLF_1);
633 /* Get var to be used for bound temps. */
634 static tree
635 chkp_get_tmp_var (void)
637 if (!tmp_var)
638 tmp_var = create_tmp_reg (pointer_bounds_type_node, CHKP_BOUND_TMP_NAME);
640 return tmp_var;
643 /* Get SSA_NAME to be used as temp. */
644 static tree
645 chkp_get_tmp_reg (gimple stmt)
647 if (in_chkp_pass)
648 return make_ssa_name (chkp_get_tmp_var (), stmt);
650 return make_temp_ssa_name (pointer_bounds_type_node, stmt,
651 CHKP_BOUND_TMP_NAME);
654 /* Get var to be used for size temps. */
655 static tree
656 chkp_get_size_tmp_var (void)
658 if (!size_tmp_var)
659 size_tmp_var = create_tmp_reg (chkp_uintptr_type, CHKP_SIZE_TMP_NAME);
661 return size_tmp_var;
664 /* Register bounds BND for address of OBJ. */
665 static void
666 chkp_register_addr_bounds (tree obj, tree bnd)
668 if (bnd == incomplete_bounds)
669 return;
671 chkp_reg_addr_bounds->put (obj, bnd);
673 if (dump_file && (dump_flags & TDF_DETAILS))
675 fprintf (dump_file, "Regsitered bound ");
676 print_generic_expr (dump_file, bnd, 0);
677 fprintf (dump_file, " for address of ");
678 print_generic_expr (dump_file, obj, 0);
679 fprintf (dump_file, "\n");
683 /* Return bounds registered for address of OBJ. */
684 static tree
685 chkp_get_registered_addr_bounds (tree obj)
687 tree *slot = chkp_reg_addr_bounds->get (obj);
688 return slot ? *slot : NULL_TREE;
691 /* Mark BOUNDS as completed. */
692 static void
693 chkp_mark_completed_bounds (tree bounds)
695 chkp_completed_bounds_set->add (bounds);
697 if (dump_file && (dump_flags & TDF_DETAILS))
699 fprintf (dump_file, "Marked bounds ");
700 print_generic_expr (dump_file, bounds, 0);
701 fprintf (dump_file, " as completed\n");
705 /* Return 1 if BOUNDS were marked as completed and 0 otherwise. */
706 static bool
707 chkp_completed_bounds (tree bounds)
709 return chkp_completed_bounds_set->contains (bounds);
712 /* Clear comleted bound marks. */
713 static void
714 chkp_erase_completed_bounds (void)
716 delete chkp_completed_bounds_set;
717 chkp_completed_bounds_set = new hash_set<tree>;
720 /* Mark BOUNDS associated with PTR as incomplete. */
721 static void
722 chkp_register_incomplete_bounds (tree bounds, tree ptr)
724 chkp_incomplete_bounds_map->put (bounds, ptr);
726 if (dump_file && (dump_flags & TDF_DETAILS))
728 fprintf (dump_file, "Regsitered incomplete bounds ");
729 print_generic_expr (dump_file, bounds, 0);
730 fprintf (dump_file, " for ");
731 print_generic_expr (dump_file, ptr, 0);
732 fprintf (dump_file, "\n");
736 /* Return 1 if BOUNDS are incomplete and 0 otherwise. */
737 static bool
738 chkp_incomplete_bounds (tree bounds)
740 if (bounds == incomplete_bounds)
741 return true;
743 if (chkp_completed_bounds (bounds))
744 return false;
746 return chkp_incomplete_bounds_map->get (bounds) != NULL;
749 /* Clear incomleted bound marks. */
750 static void
751 chkp_erase_incomplete_bounds (void)
753 delete chkp_incomplete_bounds_map;
754 chkp_incomplete_bounds_map = new hash_map<tree, tree>;
757 /* Build and return bndmk call which creates bounds for structure
758 pointed by PTR. Structure should have complete type. */
759 tree
760 chkp_make_bounds_for_struct_addr (tree ptr)
762 tree type = TREE_TYPE (ptr);
763 tree size;
765 gcc_assert (POINTER_TYPE_P (type));
767 size = TYPE_SIZE (TREE_TYPE (type));
769 gcc_assert (size);
771 return build_call_nary (pointer_bounds_type_node,
772 build_fold_addr_expr (chkp_bndmk_fndecl),
773 2, ptr, size);
776 /* Traversal function for chkp_may_finish_incomplete_bounds.
777 Set RES to 0 if at least one argument of phi statement
778 defining bounds (passed in KEY arg) is unknown.
779 Traversal stops when first unknown phi argument is found. */
780 bool
781 chkp_may_complete_phi_bounds (tree const &bounds, tree *slot ATTRIBUTE_UNUSED,
782 bool *res)
784 gimple phi;
785 unsigned i;
787 gcc_assert (TREE_CODE (bounds) == SSA_NAME);
789 phi = SSA_NAME_DEF_STMT (bounds);
791 gcc_assert (phi && gimple_code (phi) == GIMPLE_PHI);
793 for (i = 0; i < gimple_phi_num_args (phi); i++)
795 tree phi_arg = gimple_phi_arg_def (phi, i);
796 if (!phi_arg)
798 *res = false;
799 /* Do not need to traverse further. */
800 return false;
804 return true;
807 /* Return 1 if all phi nodes created for bounds have their
808 arguments computed. */
809 static bool
810 chkp_may_finish_incomplete_bounds (void)
812 bool res = true;
814 chkp_incomplete_bounds_map
815 ->traverse<bool *, chkp_may_complete_phi_bounds> (&res);
817 return res;
820 /* Helper function for chkp_finish_incomplete_bounds.
821 Recompute args for bounds phi node. */
822 bool
823 chkp_recompute_phi_bounds (tree const &bounds, tree *slot,
824 void *res ATTRIBUTE_UNUSED)
826 tree ptr = *slot;
827 gphi *bounds_phi;
828 gphi *ptr_phi;
829 unsigned i;
831 gcc_assert (TREE_CODE (bounds) == SSA_NAME);
832 gcc_assert (TREE_CODE (ptr) == SSA_NAME);
834 bounds_phi = as_a <gphi *> (SSA_NAME_DEF_STMT (bounds));
835 ptr_phi = as_a <gphi *> (SSA_NAME_DEF_STMT (ptr));
837 for (i = 0; i < gimple_phi_num_args (bounds_phi); i++)
839 tree ptr_arg = gimple_phi_arg_def (ptr_phi, i);
840 tree bound_arg = chkp_find_bounds (ptr_arg, NULL);
842 add_phi_arg (bounds_phi, bound_arg,
843 gimple_phi_arg_edge (ptr_phi, i),
844 UNKNOWN_LOCATION);
847 return true;
850 /* Mark BOUNDS as invalid. */
851 static void
852 chkp_mark_invalid_bounds (tree bounds)
854 chkp_invalid_bounds->add (bounds);
856 if (dump_file && (dump_flags & TDF_DETAILS))
858 fprintf (dump_file, "Marked bounds ");
859 print_generic_expr (dump_file, bounds, 0);
860 fprintf (dump_file, " as invalid\n");
864 /* Return 1 if BOUNDS were marked as invalid and 0 otherwise. */
865 static bool
866 chkp_valid_bounds (tree bounds)
868 if (bounds == zero_bounds || bounds == none_bounds)
869 return false;
871 return !chkp_invalid_bounds->contains (bounds);
874 /* Helper function for chkp_finish_incomplete_bounds.
875 Check all arguments of phi nodes trying to find
876 valid completed bounds. If there is at least one
877 such arg then bounds produced by phi node are marked
878 as valid completed bounds and all phi args are
879 recomputed. */
880 bool
881 chkp_find_valid_phi_bounds (tree const &bounds, tree *slot, bool *res)
883 gimple phi;
884 unsigned i;
886 gcc_assert (TREE_CODE (bounds) == SSA_NAME);
888 if (chkp_completed_bounds (bounds))
889 return true;
891 phi = SSA_NAME_DEF_STMT (bounds);
893 gcc_assert (phi && gimple_code (phi) == GIMPLE_PHI);
895 for (i = 0; i < gimple_phi_num_args (phi); i++)
897 tree phi_arg = gimple_phi_arg_def (phi, i);
899 gcc_assert (phi_arg);
901 if (chkp_valid_bounds (phi_arg) && !chkp_incomplete_bounds (phi_arg))
903 *res = true;
904 chkp_mark_completed_bounds (bounds);
905 chkp_recompute_phi_bounds (bounds, slot, NULL);
906 return true;
910 return true;
913 /* Helper function for chkp_finish_incomplete_bounds.
914 Marks all incompleted bounds as invalid. */
915 bool
916 chkp_mark_invalid_bounds_walker (tree const &bounds,
917 tree *slot ATTRIBUTE_UNUSED,
918 void *res ATTRIBUTE_UNUSED)
920 if (!chkp_completed_bounds (bounds))
922 chkp_mark_invalid_bounds (bounds);
923 chkp_mark_completed_bounds (bounds);
925 return true;
928 /* When all bound phi nodes have all their args computed
929 we have enough info to find valid bounds. We iterate
930 through all incompleted bounds searching for valid
931 bounds. Found valid bounds are marked as completed
932 and all remaining incompleted bounds are recomputed.
933 Process continues until no new valid bounds may be
934 found. All remained incompleted bounds are marked as
935 invalid (i.e. have no valid source of bounds). */
936 static void
937 chkp_finish_incomplete_bounds (void)
939 bool found_valid;
941 while (found_valid)
943 found_valid = false;
945 chkp_incomplete_bounds_map->
946 traverse<bool *, chkp_find_valid_phi_bounds> (&found_valid);
948 if (found_valid)
949 chkp_incomplete_bounds_map->
950 traverse<void *, chkp_recompute_phi_bounds> (NULL);
953 chkp_incomplete_bounds_map->
954 traverse<void *, chkp_mark_invalid_bounds_walker> (NULL);
955 chkp_incomplete_bounds_map->
956 traverse<void *, chkp_recompute_phi_bounds> (NULL);
958 chkp_erase_completed_bounds ();
959 chkp_erase_incomplete_bounds ();
962 /* Return 1 if type TYPE is a pointer type or a
963 structure having a pointer type as one of its fields.
964 Otherwise return 0. */
965 bool
966 chkp_type_has_pointer (const_tree type)
968 bool res = false;
970 if (BOUNDED_TYPE_P (type))
971 res = true;
972 else if (RECORD_OR_UNION_TYPE_P (type))
974 tree field;
976 for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
977 if (TREE_CODE (field) == FIELD_DECL)
978 res = res || chkp_type_has_pointer (TREE_TYPE (field));
980 else if (TREE_CODE (type) == ARRAY_TYPE)
981 res = chkp_type_has_pointer (TREE_TYPE (type));
983 return res;
986 unsigned
987 chkp_type_bounds_count (const_tree type)
989 unsigned res = 0;
991 if (!type)
992 res = 0;
993 else if (BOUNDED_TYPE_P (type))
994 res = 1;
995 else if (RECORD_OR_UNION_TYPE_P (type))
997 bitmap have_bound;
999 bitmap_obstack_initialize (NULL);
1000 have_bound = BITMAP_ALLOC (NULL);
1001 chkp_find_bound_slots (type, have_bound);
1002 res = bitmap_count_bits (have_bound);
1003 BITMAP_FREE (have_bound);
1004 bitmap_obstack_release (NULL);
1007 return res;
1010 /* Get bounds associated with NODE via
1011 chkp_set_bounds call. */
1012 tree
1013 chkp_get_bounds (tree node)
1015 tree *slot;
1017 if (!chkp_bounds_map)
1018 return NULL_TREE;
1020 slot = chkp_bounds_map->get (node);
1021 return slot ? *slot : NULL_TREE;
1024 /* Associate bounds VAL with NODE. */
1025 void
1026 chkp_set_bounds (tree node, tree val)
1028 if (!chkp_bounds_map)
1029 chkp_bounds_map = new hash_map<tree, tree>;
1031 chkp_bounds_map->put (node, val);
1034 /* Check if statically initialized variable VAR require
1035 static bounds initialization. If VAR is added into
1036 bounds initlization list then 1 is returned. Otherwise
1037 return 0. */
1038 extern bool
1039 chkp_register_var_initializer (tree var)
1041 if (!flag_check_pointer_bounds
1042 || DECL_INITIAL (var) == error_mark_node)
1043 return false;
1045 gcc_assert (TREE_CODE (var) == VAR_DECL);
1046 gcc_assert (DECL_INITIAL (var));
1048 if (TREE_STATIC (var)
1049 && chkp_type_has_pointer (TREE_TYPE (var)))
1051 varpool_node::get_create (var)->need_bounds_init = 1;
1052 return true;
1055 return false;
1058 /* Helper function for chkp_finish_file.
1060 Add new modification statement (RHS is assigned to LHS)
1061 into list of static initializer statementes (passed in ARG).
1062 If statements list becomes too big, emit checker constructor
1063 and start the new one. */
1064 static void
1065 chkp_add_modification_to_stmt_list (tree lhs,
1066 tree rhs,
1067 void *arg)
1069 struct chkp_ctor_stmt_list *stmts = (struct chkp_ctor_stmt_list *)arg;
1070 tree modify;
1072 if (!useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (rhs)))
1073 rhs = build1 (CONVERT_EXPR, TREE_TYPE (lhs), rhs);
1075 modify = build2 (MODIFY_EXPR, TREE_TYPE (lhs), lhs, rhs);
1076 append_to_statement_list (modify, &stmts->stmts);
1078 stmts->avail--;
1081 /* Build and return ADDR_EXPR for specified object OBJ. */
1082 static tree
1083 chkp_build_addr_expr (tree obj)
1085 return TREE_CODE (obj) == TARGET_MEM_REF
1086 ? tree_mem_ref_addr (ptr_type_node, obj)
1087 : build_fold_addr_expr (obj);
1090 /* Helper function for chkp_finish_file.
1091 Initialize bound variable BND_VAR with bounds of variable
1092 VAR to statements list STMTS. If statements list becomes
1093 too big, emit checker constructor and start the new one. */
1094 static void
1095 chkp_output_static_bounds (tree bnd_var, tree var,
1096 struct chkp_ctor_stmt_list *stmts)
1098 tree lb, ub, size;
1100 if (TREE_CODE (var) == STRING_CST)
1102 lb = build1 (CONVERT_EXPR, size_type_node, chkp_build_addr_expr (var));
1103 size = build_int_cst (size_type_node, TREE_STRING_LENGTH (var) - 1);
1105 else if (DECL_SIZE (var)
1106 && !chkp_variable_size_type (TREE_TYPE (var)))
1108 /* Compute bounds using statically known size. */
1109 lb = build1 (CONVERT_EXPR, size_type_node, chkp_build_addr_expr (var));
1110 size = size_binop (MINUS_EXPR, DECL_SIZE_UNIT (var), size_one_node);
1112 else
1114 /* Compute bounds using dynamic size. */
1115 tree call;
1117 lb = build1 (CONVERT_EXPR, size_type_node, chkp_build_addr_expr (var));
1118 call = build1 (ADDR_EXPR,
1119 build_pointer_type (TREE_TYPE (chkp_sizeof_fndecl)),
1120 chkp_sizeof_fndecl);
1121 size = build_call_nary (TREE_TYPE (TREE_TYPE (chkp_sizeof_fndecl)),
1122 call, 1, var);
1124 if (flag_chkp_zero_dynamic_size_as_infinite)
1126 tree max_size, cond;
1128 max_size = build2 (MINUS_EXPR, size_type_node, size_zero_node, lb);
1129 cond = build2 (NE_EXPR, boolean_type_node, size, size_zero_node);
1130 size = build3 (COND_EXPR, size_type_node, cond, size, max_size);
1133 size = size_binop (MINUS_EXPR, size, size_one_node);
1136 ub = size_binop (PLUS_EXPR, lb, size);
1137 stmts->avail -= targetm.chkp_initialize_bounds (bnd_var, lb, ub,
1138 &stmts->stmts);
1139 if (stmts->avail <= 0)
1141 cgraph_build_static_cdtor ('B', stmts->stmts,
1142 MAX_RESERVED_INIT_PRIORITY + 2);
1143 stmts->avail = MAX_STMTS_IN_STATIC_CHKP_CTOR;
1144 stmts->stmts = NULL;
1148 /* Return entry block to be used for checker initilization code.
1149 Create new block if required. */
1150 static basic_block
1151 chkp_get_entry_block (void)
1153 if (!entry_block)
1154 entry_block = split_block (ENTRY_BLOCK_PTR_FOR_FN (cfun), NULL)->dest;
1156 return entry_block;
1159 /* Return a bounds var to be used for pointer var PTR_VAR. */
1160 static tree
1161 chkp_get_bounds_var (tree ptr_var)
1163 tree bnd_var;
1164 tree *slot;
1166 slot = chkp_bound_vars->get (ptr_var);
1167 if (slot)
1168 bnd_var = *slot;
1169 else
1171 bnd_var = create_tmp_reg (pointer_bounds_type_node,
1172 CHKP_BOUND_TMP_NAME);
1173 chkp_bound_vars->put (ptr_var, bnd_var);
1176 return bnd_var;
1179 /* If BND is an abnormal bounds copy, return a copied value.
1180 Otherwise return BND. */
1181 static tree
1182 chkp_get_orginal_bounds_for_abnormal_copy (tree bnd)
1184 if (bitmap_bit_p (chkp_abnormal_copies, SSA_NAME_VERSION (bnd)))
1186 gimple bnd_def = SSA_NAME_DEF_STMT (bnd);
1187 gcc_checking_assert (gimple_code (bnd_def) == GIMPLE_ASSIGN);
1188 bnd = gimple_assign_rhs1 (bnd_def);
1191 return bnd;
1194 /* Register bounds BND for object PTR in global bounds table.
1195 A copy of bounds may be created for abnormal ssa names.
1196 Returns bounds to use for PTR. */
1197 static tree
1198 chkp_maybe_copy_and_register_bounds (tree ptr, tree bnd)
1200 bool abnormal_ptr;
1202 if (!chkp_reg_bounds)
1203 return bnd;
1205 /* Do nothing if bounds are incomplete_bounds
1206 because it means bounds will be recomputed. */
1207 if (bnd == incomplete_bounds)
1208 return bnd;
1210 abnormal_ptr = (TREE_CODE (ptr) == SSA_NAME
1211 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (ptr)
1212 && gimple_code (SSA_NAME_DEF_STMT (ptr)) != GIMPLE_PHI);
1214 /* A single bounds value may be reused multiple times for
1215 different pointer values. It may cause coalescing issues
1216 for abnormal SSA names. To avoid it we create a bounds
1217 copy in case it is computed for abnormal SSA name.
1219 We also cannot reuse such created copies for other pointers */
1220 if (abnormal_ptr
1221 || bitmap_bit_p (chkp_abnormal_copies, SSA_NAME_VERSION (bnd)))
1223 tree bnd_var = NULL_TREE;
1225 if (abnormal_ptr)
1227 if (SSA_NAME_VAR (ptr))
1228 bnd_var = chkp_get_bounds_var (SSA_NAME_VAR (ptr));
1230 else
1231 bnd_var = chkp_get_tmp_var ();
1233 /* For abnormal copies we may just find original
1234 bounds and use them. */
1235 if (!abnormal_ptr && !SSA_NAME_IS_DEFAULT_DEF (bnd))
1236 bnd = chkp_get_orginal_bounds_for_abnormal_copy (bnd);
1237 /* For undefined values we usually use none bounds
1238 value but in case of abnormal edge it may cause
1239 coalescing failures. Use default definition of
1240 bounds variable instead to avoid it. */
1241 else if (SSA_NAME_IS_DEFAULT_DEF (ptr)
1242 && TREE_CODE (SSA_NAME_VAR (ptr)) != PARM_DECL)
1244 bnd = get_or_create_ssa_default_def (cfun, bnd_var);
1246 if (dump_file && (dump_flags & TDF_DETAILS))
1248 fprintf (dump_file, "Using default def bounds ");
1249 print_generic_expr (dump_file, bnd, 0);
1250 fprintf (dump_file, " for abnormal default def SSA name ");
1251 print_generic_expr (dump_file, ptr, 0);
1252 fprintf (dump_file, "\n");
1255 else
1257 tree copy;
1258 gimple def = SSA_NAME_DEF_STMT (ptr);
1259 gimple assign;
1260 gimple_stmt_iterator gsi;
1262 if (bnd_var)
1263 copy = make_ssa_name (bnd_var, gimple_build_nop ());
1264 else
1265 copy = make_temp_ssa_name (pointer_bounds_type_node,
1266 gimple_build_nop (),
1267 CHKP_BOUND_TMP_NAME);
1268 bnd = chkp_get_orginal_bounds_for_abnormal_copy (bnd);
1269 assign = gimple_build_assign (copy, bnd);
1271 if (dump_file && (dump_flags & TDF_DETAILS))
1273 fprintf (dump_file, "Creating a copy of bounds ");
1274 print_generic_expr (dump_file, bnd, 0);
1275 fprintf (dump_file, " for abnormal SSA name ");
1276 print_generic_expr (dump_file, ptr, 0);
1277 fprintf (dump_file, "\n");
1280 if (gimple_code (def) == GIMPLE_NOP)
1282 gsi = gsi_last_bb (chkp_get_entry_block ());
1283 if (!gsi_end_p (gsi) && is_ctrl_stmt (gsi_stmt (gsi)))
1284 gsi_insert_before (&gsi, assign, GSI_CONTINUE_LINKING);
1285 else
1286 gsi_insert_after (&gsi, assign, GSI_CONTINUE_LINKING);
1288 else
1290 gimple bnd_def = SSA_NAME_DEF_STMT (bnd);
1291 /* Sometimes (e.g. when we load a pointer from a
1292 memory) bounds are produced later than a pointer.
1293 We need to insert bounds copy appropriately. */
1294 if (gimple_code (bnd_def) != GIMPLE_NOP
1295 && stmt_dominates_stmt_p (def, bnd_def))
1296 gsi = gsi_for_stmt (bnd_def);
1297 else
1298 gsi = gsi_for_stmt (def);
1299 gsi_insert_after (&gsi, assign, GSI_CONTINUE_LINKING);
1302 bnd = copy;
1305 if (abnormal_ptr)
1306 bitmap_set_bit (chkp_abnormal_copies, SSA_NAME_VERSION (bnd));
1309 chkp_reg_bounds->put (ptr, bnd);
1311 if (dump_file && (dump_flags & TDF_DETAILS))
1313 fprintf (dump_file, "Regsitered bound ");
1314 print_generic_expr (dump_file, bnd, 0);
1315 fprintf (dump_file, " for pointer ");
1316 print_generic_expr (dump_file, ptr, 0);
1317 fprintf (dump_file, "\n");
1320 return bnd;
1323 /* Get bounds registered for object PTR in global bounds table. */
1324 static tree
1325 chkp_get_registered_bounds (tree ptr)
1327 tree *slot;
1329 if (!chkp_reg_bounds)
1330 return NULL_TREE;
1332 slot = chkp_reg_bounds->get (ptr);
1333 return slot ? *slot : NULL_TREE;
1336 /* Add bound retvals to return statement pointed by GSI. */
1338 static void
1339 chkp_add_bounds_to_ret_stmt (gimple_stmt_iterator *gsi)
1341 greturn *ret = as_a <greturn *> (gsi_stmt (*gsi));
1342 tree retval = gimple_return_retval (ret);
1343 tree ret_decl = DECL_RESULT (cfun->decl);
1344 tree bounds;
1346 if (!retval)
1347 return;
1349 if (BOUNDED_P (ret_decl))
1351 bounds = chkp_find_bounds (retval, gsi);
1352 bounds = chkp_maybe_copy_and_register_bounds (ret_decl, bounds);
1353 gimple_return_set_retbnd (ret, bounds);
1356 update_stmt (ret);
1359 /* Force OP to be suitable for using as an argument for call.
1360 New statements (if any) go to SEQ. */
1361 static tree
1362 chkp_force_gimple_call_op (tree op, gimple_seq *seq)
1364 gimple_seq stmts;
1365 gimple_stmt_iterator si;
1367 op = force_gimple_operand (unshare_expr (op), &stmts, true, NULL_TREE);
1369 for (si = gsi_start (stmts); !gsi_end_p (si); gsi_next (&si))
1370 chkp_mark_stmt (gsi_stmt (si));
1372 gimple_seq_add_seq (seq, stmts);
1374 return op;
1377 /* Generate lower bound check for memory access by ADDR.
1378 Check is inserted before the position pointed by ITER.
1379 DIRFLAG indicates whether memory access is load or store. */
1380 static void
1381 chkp_check_lower (tree addr, tree bounds,
1382 gimple_stmt_iterator iter,
1383 location_t location,
1384 tree dirflag)
1386 gimple_seq seq;
1387 gimple check;
1388 tree node;
1390 if (!chkp_function_instrumented_p (current_function_decl)
1391 && bounds == chkp_get_zero_bounds ())
1392 return;
1394 if (dirflag == integer_zero_node
1395 && !flag_chkp_check_read)
1396 return;
1398 if (dirflag == integer_one_node
1399 && !flag_chkp_check_write)
1400 return;
1402 seq = NULL;
1404 node = chkp_force_gimple_call_op (addr, &seq);
1406 check = gimple_build_call (chkp_checkl_fndecl, 2, node, bounds);
1407 chkp_mark_stmt (check);
1408 gimple_call_set_with_bounds (check, true);
1409 gimple_set_location (check, location);
1410 gimple_seq_add_stmt (&seq, check);
1412 gsi_insert_seq_before (&iter, seq, GSI_SAME_STMT);
1414 if (dump_file && (dump_flags & TDF_DETAILS))
1416 gimple before = gsi_stmt (iter);
1417 fprintf (dump_file, "Generated lower bound check for statement ");
1418 print_gimple_stmt (dump_file, before, 0, TDF_VOPS|TDF_MEMSYMS);
1419 fprintf (dump_file, " ");
1420 print_gimple_stmt (dump_file, check, 0, TDF_VOPS|TDF_MEMSYMS);
1424 /* Generate upper bound check for memory access by ADDR.
1425 Check is inserted before the position pointed by ITER.
1426 DIRFLAG indicates whether memory access is load or store. */
1427 static void
1428 chkp_check_upper (tree addr, tree bounds,
1429 gimple_stmt_iterator iter,
1430 location_t location,
1431 tree dirflag)
1433 gimple_seq seq;
1434 gimple check;
1435 tree node;
1437 if (!chkp_function_instrumented_p (current_function_decl)
1438 && bounds == chkp_get_zero_bounds ())
1439 return;
1441 if (dirflag == integer_zero_node
1442 && !flag_chkp_check_read)
1443 return;
1445 if (dirflag == integer_one_node
1446 && !flag_chkp_check_write)
1447 return;
1449 seq = NULL;
1451 node = chkp_force_gimple_call_op (addr, &seq);
1453 check = gimple_build_call (chkp_checku_fndecl, 2, node, bounds);
1454 chkp_mark_stmt (check);
1455 gimple_call_set_with_bounds (check, true);
1456 gimple_set_location (check, location);
1457 gimple_seq_add_stmt (&seq, check);
1459 gsi_insert_seq_before (&iter, seq, GSI_SAME_STMT);
1461 if (dump_file && (dump_flags & TDF_DETAILS))
1463 gimple before = gsi_stmt (iter);
1464 fprintf (dump_file, "Generated upper bound check for statement ");
1465 print_gimple_stmt (dump_file, before, 0, TDF_VOPS|TDF_MEMSYMS);
1466 fprintf (dump_file, " ");
1467 print_gimple_stmt (dump_file, check, 0, TDF_VOPS|TDF_MEMSYMS);
1471 /* Generate lower and upper bound checks for memory access
1472 to memory slot [FIRST, LAST] againsr BOUNDS. Checks
1473 are inserted before the position pointed by ITER.
1474 DIRFLAG indicates whether memory access is load or store. */
1475 void
1476 chkp_check_mem_access (tree first, tree last, tree bounds,
1477 gimple_stmt_iterator iter,
1478 location_t location,
1479 tree dirflag)
1481 chkp_check_lower (first, bounds, iter, location, dirflag);
1482 chkp_check_upper (last, bounds, iter, location, dirflag);
1485 /* Replace call to _bnd_chk_* pointed by GSI with
1486 bndcu and bndcl calls. DIRFLAG determines whether
1487 check is for read or write. */
1489 void
1490 chkp_replace_address_check_builtin (gimple_stmt_iterator *gsi,
1491 tree dirflag)
1493 gimple_stmt_iterator call_iter = *gsi;
1494 gimple call = gsi_stmt (*gsi);
1495 tree fndecl = gimple_call_fndecl (call);
1496 tree addr = gimple_call_arg (call, 0);
1497 tree bounds = chkp_find_bounds (addr, gsi);
1499 if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CHKP_CHECK_PTR_LBOUNDS
1500 || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CHKP_CHECK_PTR_BOUNDS)
1501 chkp_check_lower (addr, bounds, *gsi, gimple_location (call), dirflag);
1503 if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CHKP_CHECK_PTR_UBOUNDS)
1504 chkp_check_upper (addr, bounds, *gsi, gimple_location (call), dirflag);
1506 if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CHKP_CHECK_PTR_BOUNDS)
1508 tree size = gimple_call_arg (call, 1);
1509 addr = fold_build_pointer_plus (addr, size);
1510 addr = fold_build_pointer_plus_hwi (addr, -1);
1511 chkp_check_upper (addr, bounds, *gsi, gimple_location (call), dirflag);
1514 gsi_remove (&call_iter, true);
1517 /* Replace call to _bnd_get_ptr_* pointed by GSI with
1518 corresponding bounds extract call. */
1520 void
1521 chkp_replace_extract_builtin (gimple_stmt_iterator *gsi)
1523 gimple call = gsi_stmt (*gsi);
1524 tree fndecl = gimple_call_fndecl (call);
1525 tree addr = gimple_call_arg (call, 0);
1526 tree bounds = chkp_find_bounds (addr, gsi);
1527 gimple extract;
1529 if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CHKP_GET_PTR_LBOUND)
1530 fndecl = chkp_extract_lower_fndecl;
1531 else if (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CHKP_GET_PTR_UBOUND)
1532 fndecl = chkp_extract_upper_fndecl;
1533 else
1534 gcc_unreachable ();
1536 extract = gimple_build_call (fndecl, 1, bounds);
1537 gimple_call_set_lhs (extract, gimple_call_lhs (call));
1538 chkp_mark_stmt (extract);
1540 gsi_replace (gsi, extract, false);
1543 /* Return COMPONENT_REF accessing FIELD in OBJ. */
1544 static tree
1545 chkp_build_component_ref (tree obj, tree field)
1547 tree res;
1549 /* If object is TMR then we do not use component_ref but
1550 add offset instead. We need it to be able to get addr
1551 of the reasult later. */
1552 if (TREE_CODE (obj) == TARGET_MEM_REF)
1554 tree offs = TMR_OFFSET (obj);
1555 offs = fold_binary_to_constant (PLUS_EXPR, TREE_TYPE (offs),
1556 offs, DECL_FIELD_OFFSET (field));
1558 gcc_assert (offs);
1560 res = copy_node (obj);
1561 TREE_TYPE (res) = TREE_TYPE (field);
1562 TMR_OFFSET (res) = offs;
1564 else
1565 res = build3 (COMPONENT_REF, TREE_TYPE (field), obj, field, NULL_TREE);
1567 return res;
1570 /* Return ARRAY_REF for array ARR and index IDX with
1571 specified element type ETYPE and element size ESIZE. */
1572 static tree
1573 chkp_build_array_ref (tree arr, tree etype, tree esize,
1574 unsigned HOST_WIDE_INT idx)
1576 tree index = build_int_cst (size_type_node, idx);
1577 tree res;
1579 /* If object is TMR then we do not use array_ref but
1580 add offset instead. We need it to be able to get addr
1581 of the reasult later. */
1582 if (TREE_CODE (arr) == TARGET_MEM_REF)
1584 tree offs = TMR_OFFSET (arr);
1586 esize = fold_binary_to_constant (MULT_EXPR, TREE_TYPE (esize),
1587 esize, index);
1588 gcc_assert(esize);
1590 offs = fold_binary_to_constant (PLUS_EXPR, TREE_TYPE (offs),
1591 offs, esize);
1592 gcc_assert (offs);
1594 res = copy_node (arr);
1595 TREE_TYPE (res) = etype;
1596 TMR_OFFSET (res) = offs;
1598 else
1599 res = build4 (ARRAY_REF, etype, arr, index, NULL_TREE, NULL_TREE);
1601 return res;
1604 /* Helper function for chkp_add_bounds_to_call_stmt.
1605 Fill ALL_BOUNDS output array with created bounds.
1607 OFFS is used for recursive calls and holds basic
1608 offset of TYPE in outer structure in bits.
1610 ITER points a position where bounds are searched.
1612 ALL_BOUNDS[i] is filled with elem bounds if there
1613 is a field in TYPE which has pointer type and offset
1614 equal to i * POINTER_SIZE in bits. */
1615 static void
1616 chkp_find_bounds_for_elem (tree elem, tree *all_bounds,
1617 HOST_WIDE_INT offs,
1618 gimple_stmt_iterator *iter)
1620 tree type = TREE_TYPE (elem);
1622 if (BOUNDED_TYPE_P (type))
1624 if (!all_bounds[offs / POINTER_SIZE])
1626 tree temp = make_temp_ssa_name (type, gimple_build_nop (), "");
1627 gimple assign = gimple_build_assign (temp, elem);
1628 gimple_stmt_iterator gsi;
1630 gsi_insert_before (iter, assign, GSI_SAME_STMT);
1631 gsi = gsi_for_stmt (assign);
1633 all_bounds[offs / POINTER_SIZE] = chkp_find_bounds (temp, &gsi);
1636 else if (RECORD_OR_UNION_TYPE_P (type))
1638 tree field;
1640 for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
1641 if (TREE_CODE (field) == FIELD_DECL)
1643 tree base = unshare_expr (elem);
1644 tree field_ref = chkp_build_component_ref (base, field);
1645 HOST_WIDE_INT field_offs
1646 = TREE_INT_CST_LOW (DECL_FIELD_BIT_OFFSET (field));
1647 if (DECL_FIELD_OFFSET (field))
1648 field_offs += TREE_INT_CST_LOW (DECL_FIELD_OFFSET (field)) * 8;
1650 chkp_find_bounds_for_elem (field_ref, all_bounds,
1651 offs + field_offs, iter);
1654 else if (TREE_CODE (type) == ARRAY_TYPE)
1656 tree maxval = TYPE_MAX_VALUE (TYPE_DOMAIN (type));
1657 tree etype = TREE_TYPE (type);
1658 HOST_WIDE_INT esize = TREE_INT_CST_LOW (TYPE_SIZE (etype));
1659 unsigned HOST_WIDE_INT cur;
1661 if (!maxval || integer_minus_onep (maxval))
1662 return;
1664 for (cur = 0; cur <= TREE_INT_CST_LOW (maxval); cur++)
1666 tree base = unshare_expr (elem);
1667 tree arr_elem = chkp_build_array_ref (base, etype,
1668 TYPE_SIZE (etype),
1669 cur);
1670 chkp_find_bounds_for_elem (arr_elem, all_bounds, offs + cur * esize,
1671 iter);
1676 /* Fill HAVE_BOUND output bitmap with information about
1677 bounds requred for object of type TYPE.
1679 OFFS is used for recursive calls and holds basic
1680 offset of TYPE in outer structure in bits.
1682 HAVE_BOUND[i] is set to 1 if there is a field
1683 in TYPE which has pointer type and offset
1684 equal to i * POINTER_SIZE - OFFS in bits. */
1685 void
1686 chkp_find_bound_slots_1 (const_tree type, bitmap have_bound,
1687 HOST_WIDE_INT offs)
1689 if (BOUNDED_TYPE_P (type))
1690 bitmap_set_bit (have_bound, offs / POINTER_SIZE);
1691 else if (RECORD_OR_UNION_TYPE_P (type))
1693 tree field;
1695 for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
1696 if (TREE_CODE (field) == FIELD_DECL)
1698 HOST_WIDE_INT field_offs
1699 = TREE_INT_CST_LOW (DECL_FIELD_BIT_OFFSET (field));
1700 if (DECL_FIELD_OFFSET (field))
1701 field_offs += TREE_INT_CST_LOW (DECL_FIELD_OFFSET (field)) * 8;
1702 chkp_find_bound_slots_1 (TREE_TYPE (field), have_bound,
1703 offs + field_offs);
1706 else if (TREE_CODE (type) == ARRAY_TYPE)
1708 tree maxval = TYPE_MAX_VALUE (TYPE_DOMAIN (type));
1709 tree etype = TREE_TYPE (type);
1710 HOST_WIDE_INT esize = TREE_INT_CST_LOW (TYPE_SIZE (etype));
1711 unsigned HOST_WIDE_INT cur;
1713 if (!maxval
1714 || TREE_CODE (maxval) != INTEGER_CST
1715 || integer_minus_onep (maxval))
1716 return;
1718 for (cur = 0; cur <= TREE_INT_CST_LOW (maxval); cur++)
1719 chkp_find_bound_slots_1 (etype, have_bound, offs + cur * esize);
1723 /* Fill bitmap RES with information about bounds for
1724 type TYPE. See chkp_find_bound_slots_1 for more
1725 details. */
1726 void
1727 chkp_find_bound_slots (const_tree type, bitmap res)
1729 bitmap_clear (res);
1730 chkp_find_bound_slots_1 (type, res, 0);
1733 /* Return 1 if call to FNDECL should be instrumented
1734 and 0 otherwise. */
1736 static bool
1737 chkp_instrument_normal_builtin (tree fndecl)
1739 switch (DECL_FUNCTION_CODE (fndecl))
1741 case BUILT_IN_STRLEN:
1742 case BUILT_IN_STRCPY:
1743 case BUILT_IN_STRNCPY:
1744 case BUILT_IN_STPCPY:
1745 case BUILT_IN_STPNCPY:
1746 case BUILT_IN_STRCAT:
1747 case BUILT_IN_STRNCAT:
1748 case BUILT_IN_MEMCPY:
1749 case BUILT_IN_MEMPCPY:
1750 case BUILT_IN_MEMSET:
1751 case BUILT_IN_MEMMOVE:
1752 case BUILT_IN_BZERO:
1753 case BUILT_IN_STRCMP:
1754 case BUILT_IN_STRNCMP:
1755 case BUILT_IN_BCMP:
1756 case BUILT_IN_MEMCMP:
1757 case BUILT_IN_MEMCPY_CHK:
1758 case BUILT_IN_MEMPCPY_CHK:
1759 case BUILT_IN_MEMMOVE_CHK:
1760 case BUILT_IN_MEMSET_CHK:
1761 case BUILT_IN_STRCPY_CHK:
1762 case BUILT_IN_STRNCPY_CHK:
1763 case BUILT_IN_STPCPY_CHK:
1764 case BUILT_IN_STPNCPY_CHK:
1765 case BUILT_IN_STRCAT_CHK:
1766 case BUILT_IN_STRNCAT_CHK:
1767 case BUILT_IN_MALLOC:
1768 case BUILT_IN_CALLOC:
1769 case BUILT_IN_REALLOC:
1770 return 1;
1772 default:
1773 return 0;
1777 /* Add bound arguments to call statement pointed by GSI.
1778 Also performs a replacement of user checker builtins calls
1779 with internal ones. */
1781 static void
1782 chkp_add_bounds_to_call_stmt (gimple_stmt_iterator *gsi)
1784 gcall *call = as_a <gcall *> (gsi_stmt (*gsi));
1785 unsigned arg_no = 0;
1786 tree fndecl = gimple_call_fndecl (call);
1787 tree fntype;
1788 tree first_formal_arg;
1789 tree arg;
1790 bool use_fntype = false;
1791 tree op;
1792 ssa_op_iter iter;
1793 gcall *new_call;
1795 /* Do nothing for internal functions. */
1796 if (gimple_call_internal_p (call))
1797 return;
1799 fntype = TREE_TYPE (TREE_TYPE (gimple_call_fn (call)));
1801 /* Do nothing if back-end builtin is called. */
1802 if (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
1803 return;
1805 /* Do nothing for some middle-end builtins. */
1806 if (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
1807 && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_OBJECT_SIZE)
1808 return;
1810 /* Do nothing for calls to not instrumentable functions. */
1811 if (fndecl && !chkp_instrumentable_p (fndecl))
1812 return;
1814 /* Ignore CHKP_INIT_PTR_BOUNDS, CHKP_NULL_PTR_BOUNDS
1815 and CHKP_COPY_PTR_BOUNDS. */
1816 if (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
1817 && (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CHKP_INIT_PTR_BOUNDS
1818 || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CHKP_NULL_PTR_BOUNDS
1819 || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CHKP_COPY_PTR_BOUNDS
1820 || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CHKP_SET_PTR_BOUNDS))
1821 return;
1823 /* Check user builtins are replaced with checks. */
1824 if (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
1825 && (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CHKP_CHECK_PTR_LBOUNDS
1826 || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CHKP_CHECK_PTR_UBOUNDS
1827 || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CHKP_CHECK_PTR_BOUNDS))
1829 chkp_replace_address_check_builtin (gsi, integer_minus_one_node);
1830 return;
1833 /* Check user builtins are replaced with bound extract. */
1834 if (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
1835 && (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CHKP_GET_PTR_LBOUND
1836 || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CHKP_GET_PTR_UBOUND))
1838 chkp_replace_extract_builtin (gsi);
1839 return;
1842 /* BUILT_IN_CHKP_NARROW_PTR_BOUNDS call is replaced with
1843 target narrow bounds call. */
1844 if (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
1845 && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CHKP_NARROW_PTR_BOUNDS)
1847 tree arg = gimple_call_arg (call, 1);
1848 tree bounds = chkp_find_bounds (arg, gsi);
1850 gimple_call_set_fndecl (call, chkp_narrow_bounds_fndecl);
1851 gimple_call_set_arg (call, 1, bounds);
1852 update_stmt (call);
1854 return;
1857 /* BUILT_IN_CHKP_STORE_PTR_BOUNDS call is replaced with
1858 bndstx call. */
1859 if (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
1860 && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CHKP_STORE_PTR_BOUNDS)
1862 tree addr = gimple_call_arg (call, 0);
1863 tree ptr = gimple_call_arg (call, 1);
1864 tree bounds = chkp_find_bounds (ptr, gsi);
1865 gimple_stmt_iterator iter = gsi_for_stmt (call);
1867 chkp_build_bndstx (addr, ptr, bounds, gsi);
1868 gsi_remove (&iter, true);
1870 return;
1873 if (!flag_chkp_instrument_calls)
1874 return;
1876 /* We instrument only some subset of builtins. We also instrument
1877 builtin calls to be inlined. */
1878 if (fndecl
1879 && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
1880 && !chkp_instrument_normal_builtin (fndecl))
1882 if (!lookup_attribute ("always_inline", DECL_ATTRIBUTES (fndecl)))
1883 return;
1885 struct cgraph_node *clone = chkp_maybe_create_clone (fndecl);
1886 if (!clone
1887 || !gimple_has_body_p (clone->decl))
1888 return;
1891 /* If function decl is available then use it for
1892 formal arguments list. Otherwise use function type. */
1893 if (fndecl && DECL_ARGUMENTS (fndecl))
1894 first_formal_arg = DECL_ARGUMENTS (fndecl);
1895 else
1897 first_formal_arg = TYPE_ARG_TYPES (fntype);
1898 use_fntype = true;
1901 /* Fill vector of new call args. */
1902 vec<tree> new_args = vNULL;
1903 new_args.create (gimple_call_num_args (call));
1904 arg = first_formal_arg;
1905 for (arg_no = 0; arg_no < gimple_call_num_args (call); arg_no++)
1907 tree call_arg = gimple_call_arg (call, arg_no);
1908 tree type;
1910 /* Get arg type using formal argument description
1911 or actual argument type. */
1912 if (arg)
1913 if (use_fntype)
1914 if (TREE_VALUE (arg) != void_type_node)
1916 type = TREE_VALUE (arg);
1917 arg = TREE_CHAIN (arg);
1919 else
1920 type = TREE_TYPE (call_arg);
1921 else
1923 type = TREE_TYPE (arg);
1924 arg = TREE_CHAIN (arg);
1926 else
1927 type = TREE_TYPE (call_arg);
1929 new_args.safe_push (call_arg);
1931 if (BOUNDED_TYPE_P (type)
1932 || pass_by_reference (NULL, TYPE_MODE (type), type, true))
1933 new_args.safe_push (chkp_find_bounds (call_arg, gsi));
1934 else if (chkp_type_has_pointer (type))
1936 HOST_WIDE_INT max_bounds
1937 = TREE_INT_CST_LOW (TYPE_SIZE (type)) / POINTER_SIZE;
1938 tree *all_bounds = (tree *)xmalloc (sizeof (tree) * max_bounds);
1939 HOST_WIDE_INT bnd_no;
1941 memset (all_bounds, 0, sizeof (tree) * max_bounds);
1943 chkp_find_bounds_for_elem (call_arg, all_bounds, 0, gsi);
1945 for (bnd_no = 0; bnd_no < max_bounds; bnd_no++)
1946 if (all_bounds[bnd_no])
1947 new_args.safe_push (all_bounds[bnd_no]);
1949 free (all_bounds);
1953 if (new_args.length () == gimple_call_num_args (call))
1954 new_call = call;
1955 else
1957 new_call = gimple_build_call_vec (gimple_op (call, 1), new_args);
1958 gimple_call_set_lhs (new_call, gimple_call_lhs (call));
1959 gimple_call_copy_flags (new_call, call);
1960 gimple_call_set_chain (new_call, gimple_call_chain (call));
1962 new_args.release ();
1964 /* For direct calls fndecl is replaced with instrumented version. */
1965 if (fndecl)
1967 tree new_decl = chkp_maybe_create_clone (fndecl)->decl;
1968 gimple_call_set_fndecl (new_call, new_decl);
1969 gimple_call_set_fntype (new_call, TREE_TYPE (new_decl));
1971 /* For indirect call we should fix function pointer type if
1972 pass some bounds. */
1973 else if (new_call != call)
1975 tree type = gimple_call_fntype (call);
1976 type = chkp_copy_function_type_adding_bounds (type);
1977 gimple_call_set_fntype (new_call, type);
1980 /* replace old call statement with the new one. */
1981 if (call != new_call)
1983 FOR_EACH_SSA_TREE_OPERAND (op, call, iter, SSA_OP_ALL_DEFS)
1985 SSA_NAME_DEF_STMT (op) = new_call;
1987 gsi_replace (gsi, new_call, true);
1989 else
1990 update_stmt (new_call);
1992 gimple_call_set_with_bounds (new_call, true);
1995 /* Return constant static bounds var with specified bounds LB and UB.
1996 If such var does not exists then new var is created with specified NAME. */
1997 static tree
1998 chkp_make_static_const_bounds (HOST_WIDE_INT lb,
1999 HOST_WIDE_INT ub,
2000 const char *name)
2002 tree id = get_identifier (name);
2003 tree var;
2004 varpool_node *node;
2005 symtab_node *snode;
2007 var = build_decl (UNKNOWN_LOCATION, VAR_DECL, id,
2008 pointer_bounds_type_node);
2009 TREE_STATIC (var) = 1;
2010 TREE_PUBLIC (var) = 1;
2012 /* With LTO we may have constant bounds already in varpool.
2013 Try to find it. */
2014 if ((snode = symtab_node::get_for_asmname (DECL_ASSEMBLER_NAME (var))))
2016 /* We don't allow this symbol usage for non bounds. */
2017 if (snode->type != SYMTAB_VARIABLE
2018 || !POINTER_BOUNDS_P (snode->decl))
2019 sorry ("-fcheck-pointer-bounds requires '%s' "
2020 "name for internal usage",
2021 IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (var)));
2023 return snode->decl;
2026 TREE_USED (var) = 1;
2027 TREE_READONLY (var) = 1;
2028 TREE_ADDRESSABLE (var) = 0;
2029 DECL_ARTIFICIAL (var) = 1;
2030 DECL_READ_P (var) = 1;
2031 DECL_INITIAL (var) = targetm.chkp_make_bounds_constant (lb, ub);
2032 make_decl_one_only (var, DECL_ASSEMBLER_NAME (var));
2033 /* We may use this symbol during ctors generation in chkp_finish_file
2034 when all symbols are emitted. Force output to avoid undefined
2035 symbols in ctors. */
2036 node = varpool_node::get_create (var);
2037 node->force_output = 1;
2039 varpool_node::finalize_decl (var);
2041 return var;
2044 /* Generate code to make bounds with specified lower bound LB and SIZE.
2045 if AFTER is 1 then code is inserted after position pointed by ITER
2046 otherwise code is inserted before position pointed by ITER.
2047 If ITER is NULL then code is added to entry block. */
2048 static tree
2049 chkp_make_bounds (tree lb, tree size, gimple_stmt_iterator *iter, bool after)
2051 gimple_seq seq;
2052 gimple_stmt_iterator gsi;
2053 gimple stmt;
2054 tree bounds;
2056 if (iter)
2057 gsi = *iter;
2058 else
2059 gsi = gsi_start_bb (chkp_get_entry_block ());
2061 seq = NULL;
2063 lb = chkp_force_gimple_call_op (lb, &seq);
2064 size = chkp_force_gimple_call_op (size, &seq);
2066 stmt = gimple_build_call (chkp_bndmk_fndecl, 2, lb, size);
2067 chkp_mark_stmt (stmt);
2069 bounds = chkp_get_tmp_reg (stmt);
2070 gimple_call_set_lhs (stmt, bounds);
2072 gimple_seq_add_stmt (&seq, stmt);
2074 if (iter && after)
2075 gsi_insert_seq_after (&gsi, seq, GSI_SAME_STMT);
2076 else
2077 gsi_insert_seq_before (&gsi, seq, GSI_SAME_STMT);
2079 if (dump_file && (dump_flags & TDF_DETAILS))
2081 fprintf (dump_file, "Made bounds: ");
2082 print_gimple_stmt (dump_file, stmt, 0, TDF_VOPS|TDF_MEMSYMS);
2083 if (iter)
2085 fprintf (dump_file, " inserted before statement: ");
2086 print_gimple_stmt (dump_file, gsi_stmt (*iter), 0, TDF_VOPS|TDF_MEMSYMS);
2088 else
2089 fprintf (dump_file, " at function entry\n");
2092 /* update_stmt (stmt); */
2094 return bounds;
2097 /* Return var holding zero bounds. */
2098 tree
2099 chkp_get_zero_bounds_var (void)
2101 if (!chkp_zero_bounds_var)
2102 chkp_zero_bounds_var
2103 = chkp_make_static_const_bounds (0, -1,
2104 CHKP_ZERO_BOUNDS_VAR_NAME);
2105 return chkp_zero_bounds_var;
2108 /* Return var holding none bounds. */
2109 tree
2110 chkp_get_none_bounds_var (void)
2112 if (!chkp_none_bounds_var)
2113 chkp_none_bounds_var
2114 = chkp_make_static_const_bounds (-1, 0,
2115 CHKP_NONE_BOUNDS_VAR_NAME);
2116 return chkp_none_bounds_var;
2119 /* Return SSA_NAME used to represent zero bounds. */
2120 static tree
2121 chkp_get_zero_bounds (void)
2123 if (zero_bounds)
2124 return zero_bounds;
2126 if (dump_file && (dump_flags & TDF_DETAILS))
2127 fprintf (dump_file, "Creating zero bounds...");
2129 if ((flag_chkp_use_static_bounds && flag_chkp_use_static_const_bounds)
2130 || flag_chkp_use_static_const_bounds > 0)
2132 gimple_stmt_iterator gsi = gsi_start_bb (chkp_get_entry_block ());
2133 gimple stmt;
2135 zero_bounds = chkp_get_tmp_reg (gimple_build_nop ());
2136 stmt = gimple_build_assign (zero_bounds, chkp_get_zero_bounds_var ());
2137 gsi_insert_before (&gsi, stmt, GSI_SAME_STMT);
2139 else
2140 zero_bounds = chkp_make_bounds (integer_zero_node,
2141 integer_zero_node,
2142 NULL,
2143 false);
2145 return zero_bounds;
2148 /* Return SSA_NAME used to represent none bounds. */
2149 static tree
2150 chkp_get_none_bounds (void)
2152 if (none_bounds)
2153 return none_bounds;
2155 if (dump_file && (dump_flags & TDF_DETAILS))
2156 fprintf (dump_file, "Creating none bounds...");
2159 if ((flag_chkp_use_static_bounds && flag_chkp_use_static_const_bounds)
2160 || flag_chkp_use_static_const_bounds > 0)
2162 gimple_stmt_iterator gsi = gsi_start_bb (chkp_get_entry_block ());
2163 gimple stmt;
2165 none_bounds = chkp_get_tmp_reg (gimple_build_nop ());
2166 stmt = gimple_build_assign (none_bounds, chkp_get_none_bounds_var ());
2167 gsi_insert_before (&gsi, stmt, GSI_SAME_STMT);
2169 else
2170 none_bounds = chkp_make_bounds (integer_minus_one_node,
2171 build_int_cst (size_type_node, 2),
2172 NULL,
2173 false);
2175 return none_bounds;
2178 /* Return bounds to be used as a result of operation which
2179 should not create poiunter (e.g. MULT_EXPR). */
2180 static tree
2181 chkp_get_invalid_op_bounds (void)
2183 return chkp_get_zero_bounds ();
2186 /* Return bounds to be used for loads of non-pointer values. */
2187 static tree
2188 chkp_get_nonpointer_load_bounds (void)
2190 return chkp_get_zero_bounds ();
2193 /* Return 1 if may use bndret call to get bounds for pointer
2194 returned by CALL. */
2195 static bool
2196 chkp_call_returns_bounds_p (gcall *call)
2198 if (gimple_call_internal_p (call))
2199 return false;
2201 if (gimple_call_builtin_p (call, BUILT_IN_CHKP_NARROW_PTR_BOUNDS)
2202 || chkp_gimple_call_builtin_p (call, BUILT_IN_CHKP_NARROW))
2203 return true;
2205 if (gimple_call_with_bounds_p (call))
2206 return true;
2208 tree fndecl = gimple_call_fndecl (call);
2210 if (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_MD)
2211 return false;
2213 if (fndecl && !chkp_instrumentable_p (fndecl))
2214 return false;
2216 if (fndecl && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL)
2218 if (chkp_instrument_normal_builtin (fndecl))
2219 return true;
2221 if (!lookup_attribute ("always_inline", DECL_ATTRIBUTES (fndecl)))
2222 return false;
2224 struct cgraph_node *clone = chkp_maybe_create_clone (fndecl);
2225 return (clone && gimple_has_body_p (clone->decl));
2228 return true;
2231 /* Build bounds returned by CALL. */
2232 static tree
2233 chkp_build_returned_bound (gcall *call)
2235 gimple_stmt_iterator gsi;
2236 tree bounds;
2237 gimple stmt;
2238 tree fndecl = gimple_call_fndecl (call);
2239 unsigned int retflags;
2241 /* To avoid fixing alloca expands in targets we handle
2242 it separately. */
2243 if (fndecl
2244 && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
2245 && (DECL_FUNCTION_CODE (fndecl) == BUILT_IN_ALLOCA
2246 || DECL_FUNCTION_CODE (fndecl) == BUILT_IN_ALLOCA_WITH_ALIGN))
2248 tree size = gimple_call_arg (call, 0);
2249 tree lb = gimple_call_lhs (call);
2250 gimple_stmt_iterator iter = gsi_for_stmt (call);
2251 bounds = chkp_make_bounds (lb, size, &iter, true);
2253 /* We know bounds returned by set_bounds builtin call. */
2254 else if (fndecl
2255 && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
2256 && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CHKP_SET_PTR_BOUNDS)
2258 tree lb = gimple_call_arg (call, 0);
2259 tree size = gimple_call_arg (call, 1);
2260 gimple_stmt_iterator iter = gsi_for_stmt (call);
2261 bounds = chkp_make_bounds (lb, size, &iter, true);
2263 /* Detect bounds initialization calls. */
2264 else if (fndecl
2265 && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
2266 && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CHKP_INIT_PTR_BOUNDS)
2267 bounds = chkp_get_zero_bounds ();
2268 /* Detect bounds nullification calls. */
2269 else if (fndecl
2270 && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
2271 && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CHKP_NULL_PTR_BOUNDS)
2272 bounds = chkp_get_none_bounds ();
2273 /* Detect bounds copy calls. */
2274 else if (fndecl
2275 && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
2276 && DECL_FUNCTION_CODE (fndecl) == BUILT_IN_CHKP_COPY_PTR_BOUNDS)
2278 gimple_stmt_iterator iter = gsi_for_stmt (call);
2279 bounds = chkp_find_bounds (gimple_call_arg (call, 1), &iter);
2281 /* Do not use retbnd when returned bounds are equal to some
2282 of passed bounds. */
2283 else if (((retflags = gimple_call_return_flags (call)) & ERF_RETURNS_ARG)
2284 && (retflags & ERF_RETURN_ARG_MASK) < gimple_call_num_args (call))
2286 gimple_stmt_iterator iter = gsi_for_stmt (call);
2287 unsigned int retarg = retflags & ERF_RETURN_ARG_MASK, argno;
2288 if (gimple_call_with_bounds_p (call))
2290 for (argno = 0; argno < gimple_call_num_args (call); argno++)
2291 if (!POINTER_BOUNDS_P (gimple_call_arg (call, argno)))
2293 if (retarg)
2294 retarg--;
2295 else
2296 break;
2299 else
2300 argno = retarg;
2302 bounds = chkp_find_bounds (gimple_call_arg (call, argno), &iter);
2304 else if (chkp_call_returns_bounds_p (call))
2306 gcc_assert (TREE_CODE (gimple_call_lhs (call)) == SSA_NAME);
2308 /* In general case build checker builtin call to
2309 obtain returned bounds. */
2310 stmt = gimple_build_call (chkp_ret_bnd_fndecl, 1,
2311 gimple_call_lhs (call));
2312 chkp_mark_stmt (stmt);
2314 gsi = gsi_for_stmt (call);
2315 gsi_insert_after (&gsi, stmt, GSI_SAME_STMT);
2317 bounds = chkp_get_tmp_reg (stmt);
2318 gimple_call_set_lhs (stmt, bounds);
2320 update_stmt (stmt);
2322 else
2323 bounds = chkp_get_zero_bounds ();
2325 if (dump_file && (dump_flags & TDF_DETAILS))
2327 fprintf (dump_file, "Built returned bounds (");
2328 print_generic_expr (dump_file, bounds, 0);
2329 fprintf (dump_file, ") for call: ");
2330 print_gimple_stmt (dump_file, call, 0, TDF_VOPS|TDF_MEMSYMS);
2333 bounds = chkp_maybe_copy_and_register_bounds (gimple_call_lhs (call), bounds);
2335 return bounds;
2338 /* Return bounds used as returned by call
2339 which produced SSA name VAL. */
2340 gcall *
2341 chkp_retbnd_call_by_val (tree val)
2343 if (TREE_CODE (val) != SSA_NAME)
2344 return NULL;
2346 gcc_assert (gimple_code (SSA_NAME_DEF_STMT (val)) == GIMPLE_CALL);
2348 imm_use_iterator use_iter;
2349 use_operand_p use_p;
2350 FOR_EACH_IMM_USE_FAST (use_p, use_iter, val)
2351 if (gimple_code (USE_STMT (use_p)) == GIMPLE_CALL
2352 && gimple_call_fndecl (USE_STMT (use_p)) == chkp_ret_bnd_fndecl)
2353 return as_a <gcall *> (USE_STMT (use_p));
2355 return NULL;
2358 /* Check the next parameter for the given PARM is bounds
2359 and return it's default SSA_NAME (create if required). */
2360 static tree
2361 chkp_get_next_bounds_parm (tree parm)
2363 tree bounds = TREE_CHAIN (parm);
2364 gcc_assert (POINTER_BOUNDS_P (bounds));
2365 bounds = ssa_default_def (cfun, bounds);
2366 if (!bounds)
2368 bounds = make_ssa_name (TREE_CHAIN (parm), gimple_build_nop ());
2369 set_ssa_default_def (cfun, TREE_CHAIN (parm), bounds);
2371 return bounds;
2374 /* Return bounds to be used for input argument PARM. */
2375 static tree
2376 chkp_get_bound_for_parm (tree parm)
2378 tree decl = SSA_NAME_VAR (parm);
2379 tree bounds;
2381 gcc_assert (TREE_CODE (decl) == PARM_DECL);
2383 bounds = chkp_get_registered_bounds (parm);
2385 if (!bounds)
2386 bounds = chkp_get_registered_bounds (decl);
2388 if (!bounds)
2390 tree orig_decl = cgraph_node::get (cfun->decl)->orig_decl;
2392 /* For static chain param we return zero bounds
2393 because currently we do not check dereferences
2394 of this pointer. */
2395 if (cfun->static_chain_decl == decl)
2396 bounds = chkp_get_zero_bounds ();
2397 /* If non instrumented runtime is used then it may be useful
2398 to use zero bounds for input arguments of main
2399 function. */
2400 else if (flag_chkp_zero_input_bounds_for_main
2401 && strcmp (IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (orig_decl)),
2402 "main") == 0)
2403 bounds = chkp_get_zero_bounds ();
2404 else if (BOUNDED_P (parm))
2406 bounds = chkp_get_next_bounds_parm (decl);
2407 bounds = chkp_maybe_copy_and_register_bounds (decl, bounds);
2409 if (dump_file && (dump_flags & TDF_DETAILS))
2411 fprintf (dump_file, "Built arg bounds (");
2412 print_generic_expr (dump_file, bounds, 0);
2413 fprintf (dump_file, ") for arg: ");
2414 print_node (dump_file, "", decl, 0);
2417 else
2418 bounds = chkp_get_zero_bounds ();
2421 if (!chkp_get_registered_bounds (parm))
2422 bounds = chkp_maybe_copy_and_register_bounds (parm, bounds);
2424 if (dump_file && (dump_flags & TDF_DETAILS))
2426 fprintf (dump_file, "Using bounds ");
2427 print_generic_expr (dump_file, bounds, 0);
2428 fprintf (dump_file, " for parm ");
2429 print_generic_expr (dump_file, parm, 0);
2430 fprintf (dump_file, " of type ");
2431 print_generic_expr (dump_file, TREE_TYPE (parm), 0);
2432 fprintf (dump_file, ".\n");
2435 return bounds;
2438 /* Build and return CALL_EXPR for bndstx builtin with specified
2439 arguments. */
2440 tree
2441 chkp_build_bndldx_call (tree addr, tree ptr)
2443 tree fn = build1 (ADDR_EXPR,
2444 build_pointer_type (TREE_TYPE (chkp_bndldx_fndecl)),
2445 chkp_bndldx_fndecl);
2446 tree call = build_call_nary (TREE_TYPE (TREE_TYPE (chkp_bndldx_fndecl)),
2447 fn, 2, addr, ptr);
2448 CALL_WITH_BOUNDS_P (call) = true;
2449 return call;
2452 /* Insert code to load bounds for PTR located by ADDR.
2453 Code is inserted after position pointed by GSI.
2454 Loaded bounds are returned. */
2455 static tree
2456 chkp_build_bndldx (tree addr, tree ptr, gimple_stmt_iterator *gsi)
2458 gimple_seq seq;
2459 gimple stmt;
2460 tree bounds;
2462 seq = NULL;
2464 addr = chkp_force_gimple_call_op (addr, &seq);
2465 ptr = chkp_force_gimple_call_op (ptr, &seq);
2467 stmt = gimple_build_call (chkp_bndldx_fndecl, 2, addr, ptr);
2468 chkp_mark_stmt (stmt);
2469 bounds = chkp_get_tmp_reg (stmt);
2470 gimple_call_set_lhs (stmt, bounds);
2472 gimple_seq_add_stmt (&seq, stmt);
2474 gsi_insert_seq_after (gsi, seq, GSI_CONTINUE_LINKING);
2476 if (dump_file && (dump_flags & TDF_DETAILS))
2478 fprintf (dump_file, "Generated bndldx for pointer ");
2479 print_generic_expr (dump_file, ptr, 0);
2480 fprintf (dump_file, ": ");
2481 print_gimple_stmt (dump_file, stmt, 0, TDF_VOPS|TDF_MEMSYMS);
2484 return bounds;
2487 /* Build and return CALL_EXPR for bndstx builtin with specified
2488 arguments. */
2489 tree
2490 chkp_build_bndstx_call (tree addr, tree ptr, tree bounds)
2492 tree fn = build1 (ADDR_EXPR,
2493 build_pointer_type (TREE_TYPE (chkp_bndstx_fndecl)),
2494 chkp_bndstx_fndecl);
2495 tree call = build_call_nary (TREE_TYPE (TREE_TYPE (chkp_bndstx_fndecl)),
2496 fn, 3, ptr, bounds, addr);
2497 CALL_WITH_BOUNDS_P (call) = true;
2498 return call;
2501 /* Insert code to store BOUNDS for PTR stored by ADDR.
2502 New statements are inserted after position pointed
2503 by GSI. */
2504 void
2505 chkp_build_bndstx (tree addr, tree ptr, tree bounds,
2506 gimple_stmt_iterator *gsi)
2508 gimple_seq seq;
2509 gimple stmt;
2511 seq = NULL;
2513 addr = chkp_force_gimple_call_op (addr, &seq);
2514 ptr = chkp_force_gimple_call_op (ptr, &seq);
2516 stmt = gimple_build_call (chkp_bndstx_fndecl, 3, ptr, bounds, addr);
2517 chkp_mark_stmt (stmt);
2518 gimple_call_set_with_bounds (stmt, true);
2520 gimple_seq_add_stmt (&seq, stmt);
2522 gsi_insert_seq_after (gsi, seq, GSI_CONTINUE_LINKING);
2524 if (dump_file && (dump_flags & TDF_DETAILS))
2526 fprintf (dump_file, "Generated bndstx for pointer store ");
2527 print_gimple_stmt (dump_file, gsi_stmt (*gsi), 0, TDF_VOPS|TDF_MEMSYMS);
2528 print_gimple_stmt (dump_file, stmt, 2, TDF_VOPS|TDF_MEMSYMS);
2532 /* Compute bounds for pointer NODE which was assigned in
2533 assignment statement ASSIGN. Return computed bounds. */
2534 static tree
2535 chkp_compute_bounds_for_assignment (tree node, gimple assign)
2537 enum tree_code rhs_code = gimple_assign_rhs_code (assign);
2538 tree rhs1 = gimple_assign_rhs1 (assign);
2539 tree bounds = NULL_TREE;
2540 gimple_stmt_iterator iter = gsi_for_stmt (assign);
2541 tree base = NULL;
2543 if (dump_file && (dump_flags & TDF_DETAILS))
2545 fprintf (dump_file, "Computing bounds for assignment: ");
2546 print_gimple_stmt (dump_file, assign, 0, TDF_VOPS|TDF_MEMSYMS);
2549 switch (rhs_code)
2551 case MEM_REF:
2552 case TARGET_MEM_REF:
2553 case COMPONENT_REF:
2554 case ARRAY_REF:
2555 /* We need to load bounds from the bounds table. */
2556 bounds = chkp_find_bounds_loaded (node, rhs1, &iter);
2557 break;
2559 case VAR_DECL:
2560 case SSA_NAME:
2561 case ADDR_EXPR:
2562 case POINTER_PLUS_EXPR:
2563 case NOP_EXPR:
2564 case CONVERT_EXPR:
2565 case INTEGER_CST:
2566 /* Bounds are just propagated from RHS. */
2567 bounds = chkp_find_bounds (rhs1, &iter);
2568 base = rhs1;
2569 break;
2571 case VIEW_CONVERT_EXPR:
2572 /* Bounds are just propagated from RHS. */
2573 bounds = chkp_find_bounds (TREE_OPERAND (rhs1, 0), &iter);
2574 break;
2576 case PARM_DECL:
2577 if (BOUNDED_P (rhs1))
2579 /* We need to load bounds from the bounds table. */
2580 bounds = chkp_build_bndldx (chkp_build_addr_expr (rhs1),
2581 node, &iter);
2582 TREE_ADDRESSABLE (rhs1) = 1;
2584 else
2585 bounds = chkp_get_nonpointer_load_bounds ();
2586 break;
2588 case MINUS_EXPR:
2589 case PLUS_EXPR:
2590 case BIT_AND_EXPR:
2591 case BIT_IOR_EXPR:
2592 case BIT_XOR_EXPR:
2594 tree rhs2 = gimple_assign_rhs2 (assign);
2595 tree bnd1 = chkp_find_bounds (rhs1, &iter);
2596 tree bnd2 = chkp_find_bounds (rhs2, &iter);
2598 /* First we try to check types of operands. If it
2599 does not help then look at bound values.
2601 If some bounds are incomplete and other are
2602 not proven to be valid (i.e. also incomplete
2603 or invalid because value is not pointer) then
2604 resulting value is incomplete and will be
2605 recomputed later in chkp_finish_incomplete_bounds. */
2606 if (BOUNDED_P (rhs1)
2607 && !BOUNDED_P (rhs2))
2608 bounds = bnd1;
2609 else if (BOUNDED_P (rhs2)
2610 && !BOUNDED_P (rhs1)
2611 && rhs_code != MINUS_EXPR)
2612 bounds = bnd2;
2613 else if (chkp_incomplete_bounds (bnd1))
2614 if (chkp_valid_bounds (bnd2) && rhs_code != MINUS_EXPR
2615 && !chkp_incomplete_bounds (bnd2))
2616 bounds = bnd2;
2617 else
2618 bounds = incomplete_bounds;
2619 else if (chkp_incomplete_bounds (bnd2))
2620 if (chkp_valid_bounds (bnd1)
2621 && !chkp_incomplete_bounds (bnd1))
2622 bounds = bnd1;
2623 else
2624 bounds = incomplete_bounds;
2625 else if (!chkp_valid_bounds (bnd1))
2626 if (chkp_valid_bounds (bnd2) && rhs_code != MINUS_EXPR)
2627 bounds = bnd2;
2628 else if (bnd2 == chkp_get_zero_bounds ())
2629 bounds = bnd2;
2630 else
2631 bounds = bnd1;
2632 else if (!chkp_valid_bounds (bnd2))
2633 bounds = bnd1;
2634 else
2635 /* Seems both operands may have valid bounds
2636 (e.g. pointer minus pointer). In such case
2637 use default invalid op bounds. */
2638 bounds = chkp_get_invalid_op_bounds ();
2640 base = (bounds == bnd1) ? rhs1 : (bounds == bnd2) ? rhs2 : NULL;
2642 break;
2644 case BIT_NOT_EXPR:
2645 case NEGATE_EXPR:
2646 case LSHIFT_EXPR:
2647 case RSHIFT_EXPR:
2648 case LROTATE_EXPR:
2649 case RROTATE_EXPR:
2650 case EQ_EXPR:
2651 case NE_EXPR:
2652 case LT_EXPR:
2653 case LE_EXPR:
2654 case GT_EXPR:
2655 case GE_EXPR:
2656 case MULT_EXPR:
2657 case RDIV_EXPR:
2658 case TRUNC_DIV_EXPR:
2659 case FLOOR_DIV_EXPR:
2660 case CEIL_DIV_EXPR:
2661 case ROUND_DIV_EXPR:
2662 case TRUNC_MOD_EXPR:
2663 case FLOOR_MOD_EXPR:
2664 case CEIL_MOD_EXPR:
2665 case ROUND_MOD_EXPR:
2666 case EXACT_DIV_EXPR:
2667 case FIX_TRUNC_EXPR:
2668 case FLOAT_EXPR:
2669 case REALPART_EXPR:
2670 case IMAGPART_EXPR:
2671 /* No valid bounds may be produced by these exprs. */
2672 bounds = chkp_get_invalid_op_bounds ();
2673 break;
2675 case COND_EXPR:
2677 tree val1 = gimple_assign_rhs2 (assign);
2678 tree val2 = gimple_assign_rhs3 (assign);
2679 tree bnd1 = chkp_find_bounds (val1, &iter);
2680 tree bnd2 = chkp_find_bounds (val2, &iter);
2681 gimple stmt;
2683 if (chkp_incomplete_bounds (bnd1) || chkp_incomplete_bounds (bnd2))
2684 bounds = incomplete_bounds;
2685 else if (bnd1 == bnd2)
2686 bounds = bnd1;
2687 else
2689 rhs1 = unshare_expr (rhs1);
2691 bounds = chkp_get_tmp_reg (assign);
2692 stmt = gimple_build_assign (bounds, COND_EXPR, rhs1, bnd1, bnd2);
2693 gsi_insert_after (&iter, stmt, GSI_SAME_STMT);
2695 if (!chkp_valid_bounds (bnd1) && !chkp_valid_bounds (bnd2))
2696 chkp_mark_invalid_bounds (bounds);
2699 break;
2701 case MAX_EXPR:
2702 case MIN_EXPR:
2704 tree rhs2 = gimple_assign_rhs2 (assign);
2705 tree bnd1 = chkp_find_bounds (rhs1, &iter);
2706 tree bnd2 = chkp_find_bounds (rhs2, &iter);
2708 if (chkp_incomplete_bounds (bnd1) || chkp_incomplete_bounds (bnd2))
2709 bounds = incomplete_bounds;
2710 else if (bnd1 == bnd2)
2711 bounds = bnd1;
2712 else
2714 gimple stmt;
2715 tree cond = build2 (rhs_code == MAX_EXPR ? GT_EXPR : LT_EXPR,
2716 boolean_type_node, rhs1, rhs2);
2717 bounds = chkp_get_tmp_reg (assign);
2718 stmt = gimple_build_assign (bounds, COND_EXPR, cond, bnd1, bnd2);
2720 gsi_insert_after (&iter, stmt, GSI_SAME_STMT);
2722 if (!chkp_valid_bounds (bnd1) && !chkp_valid_bounds (bnd2))
2723 chkp_mark_invalid_bounds (bounds);
2726 break;
2728 default:
2729 bounds = chkp_get_zero_bounds ();
2730 warning (0, "pointer bounds were lost due to unexpected expression %s",
2731 get_tree_code_name (rhs_code));
2734 gcc_assert (bounds);
2736 /* We may reuse bounds of other pointer we copy/modify. But it is not
2737 allowed for abnormal ssa names. If we produced a pointer using
2738 abnormal ssa name, we better make a bounds copy to avoid coalescing
2739 issues. */
2740 if (base
2741 && TREE_CODE (base) == SSA_NAME
2742 && SSA_NAME_OCCURS_IN_ABNORMAL_PHI (base))
2744 gimple stmt = gimple_build_assign (chkp_get_tmp_reg (NULL), bounds);
2745 gsi_insert_after (&iter, stmt, GSI_SAME_STMT);
2746 bounds = gimple_assign_lhs (stmt);
2749 if (node)
2750 bounds = chkp_maybe_copy_and_register_bounds (node, bounds);
2752 return bounds;
2755 /* Compute bounds for ssa name NODE defined by DEF_STMT pointed by ITER.
2757 There are just few statement codes allowed: NOP (for default ssa names),
2758 ASSIGN, CALL, PHI, ASM.
2760 Return computed bounds. */
2761 static tree
2762 chkp_get_bounds_by_definition (tree node, gimple def_stmt,
2763 gphi_iterator *iter)
2765 tree var, bounds;
2766 enum gimple_code code = gimple_code (def_stmt);
2767 gphi *stmt;
2769 if (dump_file && (dump_flags & TDF_DETAILS))
2771 fprintf (dump_file, "Searching for bounds for node: ");
2772 print_generic_expr (dump_file, node, 0);
2774 fprintf (dump_file, " using its definition: ");
2775 print_gimple_stmt (dump_file, def_stmt, 0, TDF_VOPS|TDF_MEMSYMS);
2778 switch (code)
2780 case GIMPLE_NOP:
2781 var = SSA_NAME_VAR (node);
2782 switch (TREE_CODE (var))
2784 case PARM_DECL:
2785 bounds = chkp_get_bound_for_parm (node);
2786 break;
2788 case VAR_DECL:
2789 /* For uninitialized pointers use none bounds. */
2790 bounds = chkp_get_none_bounds ();
2791 bounds = chkp_maybe_copy_and_register_bounds (node, bounds);
2792 break;
2794 case RESULT_DECL:
2796 tree base_type;
2798 gcc_assert (TREE_CODE (TREE_TYPE (node)) == REFERENCE_TYPE);
2800 base_type = TREE_TYPE (TREE_TYPE (node));
2802 gcc_assert (TYPE_SIZE (base_type)
2803 && TREE_CODE (TYPE_SIZE (base_type)) == INTEGER_CST
2804 && tree_to_uhwi (TYPE_SIZE (base_type)) != 0);
2806 bounds = chkp_make_bounds (node, TYPE_SIZE_UNIT (base_type),
2807 NULL, false);
2808 bounds = chkp_maybe_copy_and_register_bounds (node, bounds);
2810 break;
2812 default:
2813 if (dump_file && (dump_flags & TDF_DETAILS))
2815 fprintf (dump_file, "Unexpected var with no definition\n");
2816 print_generic_expr (dump_file, var, 0);
2818 internal_error ("chkp_get_bounds_by_definition: Unexpected var of type %s",
2819 get_tree_code_name (TREE_CODE (var)));
2821 break;
2823 case GIMPLE_ASSIGN:
2824 bounds = chkp_compute_bounds_for_assignment (node, def_stmt);
2825 break;
2827 case GIMPLE_CALL:
2828 bounds = chkp_build_returned_bound (as_a <gcall *> (def_stmt));
2829 break;
2831 case GIMPLE_PHI:
2832 if (SSA_NAME_OCCURS_IN_ABNORMAL_PHI (node))
2833 if (SSA_NAME_VAR (node))
2834 var = chkp_get_bounds_var (SSA_NAME_VAR (node));
2835 else
2836 var = make_temp_ssa_name (pointer_bounds_type_node,
2837 gimple_build_nop (),
2838 CHKP_BOUND_TMP_NAME);
2839 else
2840 var = chkp_get_tmp_var ();
2841 stmt = create_phi_node (var, gimple_bb (def_stmt));
2842 bounds = gimple_phi_result (stmt);
2843 *iter = gsi_for_phi (stmt);
2845 bounds = chkp_maybe_copy_and_register_bounds (node, bounds);
2847 /* Created bounds do not have all phi args computed and
2848 therefore we do not know if there is a valid source
2849 of bounds for that node. Therefore we mark bounds
2850 as incomplete and then recompute them when all phi
2851 args are computed. */
2852 chkp_register_incomplete_bounds (bounds, node);
2853 break;
2855 case GIMPLE_ASM:
2856 bounds = chkp_get_zero_bounds ();
2857 bounds = chkp_maybe_copy_and_register_bounds (node, bounds);
2858 break;
2860 default:
2861 internal_error ("chkp_get_bounds_by_definition: Unexpected GIMPLE code %s",
2862 gimple_code_name[code]);
2865 return bounds;
2868 /* Return CALL_EXPR for bndmk with specified LOWER_BOUND and SIZE. */
2869 tree
2870 chkp_build_make_bounds_call (tree lower_bound, tree size)
2872 tree call = build1 (ADDR_EXPR,
2873 build_pointer_type (TREE_TYPE (chkp_bndmk_fndecl)),
2874 chkp_bndmk_fndecl);
2875 return build_call_nary (TREE_TYPE (TREE_TYPE (chkp_bndmk_fndecl)),
2876 call, 2, lower_bound, size);
2879 /* Create static bounds var of specfified OBJ which is
2880 is either VAR_DECL or string constant. */
2881 static tree
2882 chkp_make_static_bounds (tree obj)
2884 static int string_id = 1;
2885 static int var_id = 1;
2886 tree *slot;
2887 const char *var_name;
2888 char *bnd_var_name;
2889 tree bnd_var;
2891 /* First check if we already have required var. */
2892 if (chkp_static_var_bounds)
2894 /* For vars we use assembler name as a key in
2895 chkp_static_var_bounds map. It allows to
2896 avoid duplicating bound vars for decls
2897 sharing assembler name. */
2898 if (TREE_CODE (obj) == VAR_DECL)
2900 tree name = DECL_ASSEMBLER_NAME (obj);
2901 slot = chkp_static_var_bounds->get (name);
2902 if (slot)
2903 return *slot;
2905 else
2907 slot = chkp_static_var_bounds->get (obj);
2908 if (slot)
2909 return *slot;
2913 /* Build decl for bounds var. */
2914 if (TREE_CODE (obj) == VAR_DECL)
2916 if (DECL_IGNORED_P (obj))
2918 bnd_var_name = (char *) xmalloc (strlen (CHKP_VAR_BOUNDS_PREFIX) + 10);
2919 sprintf (bnd_var_name, "%s%d", CHKP_VAR_BOUNDS_PREFIX, var_id++);
2921 else
2923 var_name = IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (obj));
2925 /* For hidden symbols we want to skip first '*' char. */
2926 if (*var_name == '*')
2927 var_name++;
2929 bnd_var_name = (char *) xmalloc (strlen (var_name)
2930 + strlen (CHKP_BOUNDS_OF_SYMBOL_PREFIX) + 1);
2931 strcpy (bnd_var_name, CHKP_BOUNDS_OF_SYMBOL_PREFIX);
2932 strcat (bnd_var_name, var_name);
2935 bnd_var = build_decl (UNKNOWN_LOCATION, VAR_DECL,
2936 get_identifier (bnd_var_name),
2937 pointer_bounds_type_node);
2939 /* Address of the obj will be used as lower bound. */
2940 TREE_ADDRESSABLE (obj) = 1;
2942 else
2944 bnd_var_name = (char *) xmalloc (strlen (CHKP_STRING_BOUNDS_PREFIX) + 10);
2945 sprintf (bnd_var_name, "%s%d", CHKP_STRING_BOUNDS_PREFIX, string_id++);
2947 bnd_var = build_decl (UNKNOWN_LOCATION, VAR_DECL,
2948 get_identifier (bnd_var_name),
2949 pointer_bounds_type_node);
2952 TREE_PUBLIC (bnd_var) = 0;
2953 TREE_USED (bnd_var) = 1;
2954 TREE_READONLY (bnd_var) = 0;
2955 TREE_STATIC (bnd_var) = 1;
2956 TREE_ADDRESSABLE (bnd_var) = 0;
2957 DECL_ARTIFICIAL (bnd_var) = 1;
2958 DECL_COMMON (bnd_var) = 1;
2959 DECL_COMDAT (bnd_var) = 1;
2960 DECL_READ_P (bnd_var) = 1;
2961 DECL_INITIAL (bnd_var) = chkp_build_addr_expr (obj);
2962 /* Force output similar to constant bounds.
2963 See chkp_make_static_const_bounds. */
2964 varpool_node::get_create (bnd_var)->force_output = 1;
2965 /* Mark symbol as requiring bounds initialization. */
2966 varpool_node::get_create (bnd_var)->need_bounds_init = 1;
2967 varpool_node::finalize_decl (bnd_var);
2969 /* Add created var to the map to use it for other references
2970 to obj. */
2971 if (!chkp_static_var_bounds)
2972 chkp_static_var_bounds = new hash_map<tree, tree>;
2974 if (TREE_CODE (obj) == VAR_DECL)
2976 tree name = DECL_ASSEMBLER_NAME (obj);
2977 chkp_static_var_bounds->put (name, bnd_var);
2979 else
2980 chkp_static_var_bounds->put (obj, bnd_var);
2982 return bnd_var;
2985 /* When var has incomplete type we cannot get size to
2986 compute its bounds. In such cases we use checker
2987 builtin call which determines object size at runtime. */
2988 static tree
2989 chkp_generate_extern_var_bounds (tree var)
2991 tree bounds, size_reloc, lb, size, max_size, cond;
2992 gimple_stmt_iterator gsi;
2993 gimple_seq seq = NULL;
2994 gimple stmt;
2996 /* If instrumentation is not enabled for vars having
2997 incomplete type then just return zero bounds to avoid
2998 checks for this var. */
2999 if (!flag_chkp_incomplete_type)
3000 return chkp_get_zero_bounds ();
3002 if (dump_file && (dump_flags & TDF_DETAILS))
3004 fprintf (dump_file, "Generating bounds for extern symbol '");
3005 print_generic_expr (dump_file, var, 0);
3006 fprintf (dump_file, "'\n");
3009 stmt = gimple_build_call (chkp_sizeof_fndecl, 1, var);
3011 size_reloc = create_tmp_reg (chkp_uintptr_type, CHKP_SIZE_TMP_NAME);
3012 gimple_call_set_lhs (stmt, size_reloc);
3014 gimple_seq_add_stmt (&seq, stmt);
3016 lb = chkp_build_addr_expr (var);
3017 size = make_ssa_name (chkp_get_size_tmp_var (), gimple_build_nop ());
3019 if (flag_chkp_zero_dynamic_size_as_infinite)
3021 /* We should check that size relocation was resolved.
3022 If it was not then use maximum possible size for the var. */
3023 max_size = build2 (MINUS_EXPR, chkp_uintptr_type, integer_zero_node,
3024 fold_convert (chkp_uintptr_type, lb));
3025 max_size = chkp_force_gimple_call_op (max_size, &seq);
3027 cond = build2 (NE_EXPR, boolean_type_node,
3028 size_reloc, integer_zero_node);
3029 stmt = gimple_build_assign (size, COND_EXPR, cond, size_reloc, max_size);
3030 gimple_seq_add_stmt (&seq, stmt);
3032 else
3034 stmt = gimple_build_assign (size, size_reloc);
3035 gimple_seq_add_stmt (&seq, stmt);
3038 gsi = gsi_start_bb (chkp_get_entry_block ());
3039 gsi_insert_seq_after (&gsi, seq, GSI_CONTINUE_LINKING);
3041 bounds = chkp_make_bounds (lb, size, &gsi, true);
3043 return bounds;
3046 /* Return 1 if TYPE has fields with zero size or fields
3047 marked with chkp_variable_size attribute. */
3048 bool
3049 chkp_variable_size_type (tree type)
3051 bool res = false;
3052 tree field;
3054 if (RECORD_OR_UNION_TYPE_P (type))
3055 for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
3057 if (TREE_CODE (field) == FIELD_DECL)
3058 res = res
3059 || lookup_attribute ("bnd_variable_size", DECL_ATTRIBUTES (field))
3060 || chkp_variable_size_type (TREE_TYPE (field));
3062 else
3063 res = !TYPE_SIZE (type)
3064 || TREE_CODE (TYPE_SIZE (type)) != INTEGER_CST
3065 || tree_to_uhwi (TYPE_SIZE (type)) == 0;
3067 return res;
3070 /* Compute and return bounds for address of DECL which is
3071 one of VAR_DECL, PARM_DECL, RESULT_DECL. */
3072 static tree
3073 chkp_get_bounds_for_decl_addr (tree decl)
3075 tree bounds;
3077 gcc_assert (TREE_CODE (decl) == VAR_DECL
3078 || TREE_CODE (decl) == PARM_DECL
3079 || TREE_CODE (decl) == RESULT_DECL);
3081 bounds = chkp_get_registered_addr_bounds (decl);
3083 if (bounds)
3084 return bounds;
3086 if (dump_file && (dump_flags & TDF_DETAILS))
3088 fprintf (dump_file, "Building bounds for address of decl ");
3089 print_generic_expr (dump_file, decl, 0);
3090 fprintf (dump_file, "\n");
3093 /* Use zero bounds if size is unknown and checks for
3094 unknown sizes are restricted. */
3095 if ((!DECL_SIZE (decl)
3096 || (chkp_variable_size_type (TREE_TYPE (decl))
3097 && (TREE_STATIC (decl)
3098 || DECL_EXTERNAL (decl)
3099 || TREE_PUBLIC (decl))))
3100 && !flag_chkp_incomplete_type)
3101 return chkp_get_zero_bounds ();
3103 if (flag_chkp_use_static_bounds
3104 && TREE_CODE (decl) == VAR_DECL
3105 && (TREE_STATIC (decl)
3106 || DECL_EXTERNAL (decl)
3107 || TREE_PUBLIC (decl))
3108 && !DECL_THREAD_LOCAL_P (decl))
3110 tree bnd_var = chkp_make_static_bounds (decl);
3111 gimple_stmt_iterator gsi = gsi_start_bb (chkp_get_entry_block ());
3112 gimple stmt;
3114 bounds = chkp_get_tmp_reg (gimple_build_nop ());
3115 stmt = gimple_build_assign (bounds, bnd_var);
3116 gsi_insert_before (&gsi, stmt, GSI_SAME_STMT);
3118 else if (!DECL_SIZE (decl)
3119 || (chkp_variable_size_type (TREE_TYPE (decl))
3120 && (TREE_STATIC (decl)
3121 || DECL_EXTERNAL (decl)
3122 || TREE_PUBLIC (decl))))
3124 gcc_assert (TREE_CODE (decl) == VAR_DECL);
3125 bounds = chkp_generate_extern_var_bounds (decl);
3127 else
3129 tree lb = chkp_build_addr_expr (decl);
3130 bounds = chkp_make_bounds (lb, DECL_SIZE_UNIT (decl), NULL, false);
3133 return bounds;
3136 /* Compute and return bounds for constant string. */
3137 static tree
3138 chkp_get_bounds_for_string_cst (tree cst)
3140 tree bounds;
3141 tree lb;
3142 tree size;
3144 gcc_assert (TREE_CODE (cst) == STRING_CST);
3146 bounds = chkp_get_registered_bounds (cst);
3148 if (bounds)
3149 return bounds;
3151 if ((flag_chkp_use_static_bounds && flag_chkp_use_static_const_bounds)
3152 || flag_chkp_use_static_const_bounds > 0)
3154 tree bnd_var = chkp_make_static_bounds (cst);
3155 gimple_stmt_iterator gsi = gsi_start_bb (chkp_get_entry_block ());
3156 gimple stmt;
3158 bounds = chkp_get_tmp_reg (gimple_build_nop ());
3159 stmt = gimple_build_assign (bounds, bnd_var);
3160 gsi_insert_before (&gsi, stmt, GSI_SAME_STMT);
3162 else
3164 lb = chkp_build_addr_expr (cst);
3165 size = build_int_cst (chkp_uintptr_type, TREE_STRING_LENGTH (cst));
3166 bounds = chkp_make_bounds (lb, size, NULL, false);
3169 bounds = chkp_maybe_copy_and_register_bounds (cst, bounds);
3171 return bounds;
3174 /* Generate code to instersect bounds BOUNDS1 and BOUNDS2 and
3175 return the result. if ITER is not NULL then Code is inserted
3176 before position pointed by ITER. Otherwise code is added to
3177 entry block. */
3178 static tree
3179 chkp_intersect_bounds (tree bounds1, tree bounds2, gimple_stmt_iterator *iter)
3181 if (!bounds1 || bounds1 == chkp_get_zero_bounds ())
3182 return bounds2 ? bounds2 : bounds1;
3183 else if (!bounds2 || bounds2 == chkp_get_zero_bounds ())
3184 return bounds1;
3185 else
3187 gimple_seq seq;
3188 gimple stmt;
3189 tree bounds;
3191 seq = NULL;
3193 stmt = gimple_build_call (chkp_intersect_fndecl, 2, bounds1, bounds2);
3194 chkp_mark_stmt (stmt);
3196 bounds = chkp_get_tmp_reg (stmt);
3197 gimple_call_set_lhs (stmt, bounds);
3199 gimple_seq_add_stmt (&seq, stmt);
3201 /* We are probably doing narrowing for constant expression.
3202 In such case iter may be undefined. */
3203 if (!iter)
3205 gimple_stmt_iterator gsi = gsi_last_bb (chkp_get_entry_block ());
3206 iter = &gsi;
3207 gsi_insert_seq_after (iter, seq, GSI_SAME_STMT);
3209 else
3210 gsi_insert_seq_before (iter, seq, GSI_SAME_STMT);
3212 if (dump_file && (dump_flags & TDF_DETAILS))
3214 fprintf (dump_file, "Bounds intersection: ");
3215 print_gimple_stmt (dump_file, stmt, 0, TDF_VOPS|TDF_MEMSYMS);
3216 fprintf (dump_file, " inserted before statement: ");
3217 print_gimple_stmt (dump_file, gsi_stmt (*iter), 0,
3218 TDF_VOPS|TDF_MEMSYMS);
3221 return bounds;
3225 /* Return 1 if we are allowed to narrow bounds for addressed FIELD
3226 and 0 othersize. */
3227 static bool
3228 chkp_may_narrow_to_field (tree field)
3230 return DECL_SIZE (field) && TREE_CODE (DECL_SIZE (field)) == INTEGER_CST
3231 && tree_to_uhwi (DECL_SIZE (field)) != 0
3232 && (!DECL_FIELD_OFFSET (field)
3233 || TREE_CODE (DECL_FIELD_OFFSET (field)) == INTEGER_CST)
3234 && (!DECL_FIELD_BIT_OFFSET (field)
3235 || TREE_CODE (DECL_FIELD_BIT_OFFSET (field)) == INTEGER_CST)
3236 && !lookup_attribute ("bnd_variable_size", DECL_ATTRIBUTES (field))
3237 && !chkp_variable_size_type (TREE_TYPE (field));
3240 /* Return 1 if bounds for FIELD should be narrowed to
3241 field's own size. */
3242 static bool
3243 chkp_narrow_bounds_for_field (tree field)
3245 HOST_WIDE_INT offs;
3246 HOST_WIDE_INT bit_offs;
3248 if (!chkp_may_narrow_to_field (field))
3249 return false;
3251 /* Accesse to compiler generated fields should not cause
3252 bounds narrowing. */
3253 if (DECL_ARTIFICIAL (field))
3254 return false;
3256 offs = tree_to_uhwi (DECL_FIELD_OFFSET (field));
3257 bit_offs = tree_to_uhwi (DECL_FIELD_BIT_OFFSET (field));
3259 return (flag_chkp_narrow_bounds
3260 && (flag_chkp_first_field_has_own_bounds
3261 || offs
3262 || bit_offs));
3265 /* Perform narrowing for BOUNDS using bounds computed for field
3266 access COMPONENT. ITER meaning is the same as for
3267 chkp_intersect_bounds. */
3268 static tree
3269 chkp_narrow_bounds_to_field (tree bounds, tree component,
3270 gimple_stmt_iterator *iter)
3272 tree field = TREE_OPERAND (component, 1);
3273 tree size = DECL_SIZE_UNIT (field);
3274 tree field_ptr = chkp_build_addr_expr (component);
3275 tree field_bounds;
3277 field_bounds = chkp_make_bounds (field_ptr, size, iter, false);
3279 return chkp_intersect_bounds (field_bounds, bounds, iter);
3282 /* Parse field or array access NODE.
3284 PTR ouput parameter holds a pointer to the outermost
3285 object.
3287 BITFIELD output parameter is set to 1 if bitfield is
3288 accessed and to 0 otherwise. If it is 1 then ELT holds
3289 outer component for accessed bit field.
3291 SAFE outer parameter is set to 1 if access is safe and
3292 checks are not required.
3294 BOUNDS outer parameter holds bounds to be used to check
3295 access (may be NULL).
3297 If INNERMOST_BOUNDS is 1 then try to narrow bounds to the
3298 innermost accessed component. */
3299 static void
3300 chkp_parse_array_and_component_ref (tree node, tree *ptr,
3301 tree *elt, bool *safe,
3302 bool *bitfield,
3303 tree *bounds,
3304 gimple_stmt_iterator *iter,
3305 bool innermost_bounds)
3307 tree comp_to_narrow = NULL_TREE;
3308 tree last_comp = NULL_TREE;
3309 bool array_ref_found = false;
3310 tree *nodes;
3311 tree var;
3312 int len;
3313 int i;
3315 /* Compute tree height for expression. */
3316 var = node;
3317 len = 1;
3318 while (TREE_CODE (var) == COMPONENT_REF
3319 || TREE_CODE (var) == ARRAY_REF
3320 || TREE_CODE (var) == VIEW_CONVERT_EXPR)
3322 var = TREE_OPERAND (var, 0);
3323 len++;
3326 gcc_assert (len > 1);
3328 /* It is more convenient for us to scan left-to-right,
3329 so walk tree again and put all node to nodes vector
3330 in reversed order. */
3331 nodes = XALLOCAVEC (tree, len);
3332 nodes[len - 1] = node;
3333 for (i = len - 2; i >= 0; i--)
3334 nodes[i] = TREE_OPERAND (nodes[i + 1], 0);
3336 if (bounds)
3337 *bounds = NULL;
3338 *safe = true;
3339 *bitfield = (TREE_CODE (node) == COMPONENT_REF
3340 && DECL_BIT_FIELD_TYPE (TREE_OPERAND (node, 1)));
3341 /* To get bitfield address we will need outer elemnt. */
3342 if (*bitfield)
3343 *elt = nodes[len - 2];
3344 else
3345 *elt = NULL_TREE;
3347 /* If we have indirection in expression then compute
3348 outermost structure bounds. Computed bounds may be
3349 narrowed later. */
3350 if (TREE_CODE (nodes[0]) == MEM_REF || INDIRECT_REF_P (nodes[0]))
3352 *safe = false;
3353 *ptr = TREE_OPERAND (nodes[0], 0);
3354 if (bounds)
3355 *bounds = chkp_find_bounds (*ptr, iter);
3357 else
3359 gcc_assert (TREE_CODE (var) == VAR_DECL
3360 || TREE_CODE (var) == PARM_DECL
3361 || TREE_CODE (var) == RESULT_DECL
3362 || TREE_CODE (var) == STRING_CST
3363 || TREE_CODE (var) == SSA_NAME);
3365 *ptr = chkp_build_addr_expr (var);
3368 /* In this loop we are trying to find a field access
3369 requiring narrowing. There are two simple rules
3370 for search:
3371 1. Leftmost array_ref is chosen if any.
3372 2. Rightmost suitable component_ref is chosen if innermost
3373 bounds are required and no array_ref exists. */
3374 for (i = 1; i < len; i++)
3376 var = nodes[i];
3378 if (TREE_CODE (var) == ARRAY_REF)
3380 *safe = false;
3381 array_ref_found = true;
3382 if (flag_chkp_narrow_bounds
3383 && !flag_chkp_narrow_to_innermost_arrray
3384 && (!last_comp
3385 || chkp_may_narrow_to_field (TREE_OPERAND (last_comp, 1))))
3387 comp_to_narrow = last_comp;
3388 break;
3391 else if (TREE_CODE (var) == COMPONENT_REF)
3393 tree field = TREE_OPERAND (var, 1);
3395 if (innermost_bounds
3396 && !array_ref_found
3397 && chkp_narrow_bounds_for_field (field))
3398 comp_to_narrow = var;
3399 last_comp = var;
3401 if (flag_chkp_narrow_bounds
3402 && flag_chkp_narrow_to_innermost_arrray
3403 && TREE_CODE (TREE_TYPE (field)) == ARRAY_TYPE)
3405 if (bounds)
3406 *bounds = chkp_narrow_bounds_to_field (*bounds, var, iter);
3407 comp_to_narrow = NULL;
3410 else if (TREE_CODE (var) == VIEW_CONVERT_EXPR)
3411 /* Nothing to do for it. */
3413 else
3414 gcc_unreachable ();
3417 if (comp_to_narrow && DECL_SIZE (TREE_OPERAND (comp_to_narrow, 1)) && bounds)
3418 *bounds = chkp_narrow_bounds_to_field (*bounds, comp_to_narrow, iter);
3420 if (innermost_bounds && bounds && !*bounds)
3421 *bounds = chkp_find_bounds (*ptr, iter);
3424 /* Compute and return bounds for address of OBJ. */
3425 static tree
3426 chkp_make_addressed_object_bounds (tree obj, gimple_stmt_iterator *iter)
3428 tree bounds = chkp_get_registered_addr_bounds (obj);
3430 if (bounds)
3431 return bounds;
3433 switch (TREE_CODE (obj))
3435 case VAR_DECL:
3436 case PARM_DECL:
3437 case RESULT_DECL:
3438 bounds = chkp_get_bounds_for_decl_addr (obj);
3439 break;
3441 case STRING_CST:
3442 bounds = chkp_get_bounds_for_string_cst (obj);
3443 break;
3445 case ARRAY_REF:
3446 case COMPONENT_REF:
3448 tree elt;
3449 tree ptr;
3450 bool safe;
3451 bool bitfield;
3453 chkp_parse_array_and_component_ref (obj, &ptr, &elt, &safe,
3454 &bitfield, &bounds, iter, true);
3456 gcc_assert (bounds);
3458 break;
3460 case FUNCTION_DECL:
3461 case LABEL_DECL:
3462 bounds = chkp_get_zero_bounds ();
3463 break;
3465 case MEM_REF:
3466 bounds = chkp_find_bounds (TREE_OPERAND (obj, 0), iter);
3467 break;
3469 case REALPART_EXPR:
3470 case IMAGPART_EXPR:
3471 bounds = chkp_make_addressed_object_bounds (TREE_OPERAND (obj, 0), iter);
3472 break;
3474 default:
3475 if (dump_file && (dump_flags & TDF_DETAILS))
3477 fprintf (dump_file, "chkp_make_addressed_object_bounds: "
3478 "unexpected object of type %s\n",
3479 get_tree_code_name (TREE_CODE (obj)));
3480 print_node (dump_file, "", obj, 0);
3482 internal_error ("chkp_make_addressed_object_bounds: "
3483 "Unexpected tree code %s",
3484 get_tree_code_name (TREE_CODE (obj)));
3487 chkp_register_addr_bounds (obj, bounds);
3489 return bounds;
3492 /* Compute bounds for pointer PTR loaded from PTR_SRC. Generate statements
3493 to compute bounds if required. Computed bounds should be available at
3494 position pointed by ITER.
3496 If PTR_SRC is NULL_TREE then pointer definition is identified.
3498 If PTR_SRC is not NULL_TREE then ITER points to statements which loads
3499 PTR. If PTR is a any memory reference then ITER points to a statement
3500 after which bndldx will be inserterd. In both cases ITER will be updated
3501 to point to the inserted bndldx statement. */
3503 static tree
3504 chkp_find_bounds_1 (tree ptr, tree ptr_src, gimple_stmt_iterator *iter)
3506 tree addr = NULL_TREE;
3507 tree bounds = NULL_TREE;
3509 if (!ptr_src)
3510 ptr_src = ptr;
3512 bounds = chkp_get_registered_bounds (ptr_src);
3514 if (bounds)
3515 return bounds;
3517 switch (TREE_CODE (ptr_src))
3519 case MEM_REF:
3520 case VAR_DECL:
3521 if (BOUNDED_P (ptr_src))
3522 if (TREE_CODE (ptr) == VAR_DECL && DECL_REGISTER (ptr))
3523 bounds = chkp_get_zero_bounds ();
3524 else
3526 addr = chkp_build_addr_expr (ptr_src);
3527 bounds = chkp_build_bndldx (addr, ptr, iter);
3529 else
3530 bounds = chkp_get_nonpointer_load_bounds ();
3531 break;
3533 case ARRAY_REF:
3534 case COMPONENT_REF:
3535 addr = get_base_address (ptr_src);
3536 if (DECL_P (addr)
3537 || TREE_CODE (addr) == MEM_REF
3538 || TREE_CODE (addr) == TARGET_MEM_REF)
3540 if (BOUNDED_P (ptr_src))
3541 if (TREE_CODE (ptr) == VAR_DECL && DECL_REGISTER (ptr))
3542 bounds = chkp_get_zero_bounds ();
3543 else
3545 addr = chkp_build_addr_expr (ptr_src);
3546 bounds = chkp_build_bndldx (addr, ptr, iter);
3548 else
3549 bounds = chkp_get_nonpointer_load_bounds ();
3551 else
3553 gcc_assert (TREE_CODE (addr) == SSA_NAME);
3554 bounds = chkp_find_bounds (addr, iter);
3556 break;
3558 case PARM_DECL:
3559 gcc_unreachable ();
3560 bounds = chkp_get_bound_for_parm (ptr_src);
3561 break;
3563 case TARGET_MEM_REF:
3564 addr = chkp_build_addr_expr (ptr_src);
3565 bounds = chkp_build_bndldx (addr, ptr, iter);
3566 break;
3568 case SSA_NAME:
3569 bounds = chkp_get_registered_bounds (ptr_src);
3570 if (!bounds)
3572 gimple def_stmt = SSA_NAME_DEF_STMT (ptr_src);
3573 gphi_iterator phi_iter;
3575 bounds = chkp_get_bounds_by_definition (ptr_src, def_stmt, &phi_iter);
3577 gcc_assert (bounds);
3579 if (gphi *def_phi = dyn_cast <gphi *> (def_stmt))
3581 unsigned i;
3583 for (i = 0; i < gimple_phi_num_args (def_phi); i++)
3585 tree arg = gimple_phi_arg_def (def_phi, i);
3586 tree arg_bnd;
3587 gphi *phi_bnd;
3589 arg_bnd = chkp_find_bounds (arg, NULL);
3591 /* chkp_get_bounds_by_definition created new phi
3592 statement and phi_iter points to it.
3594 Previous call to chkp_find_bounds could create
3595 new basic block and therefore change phi statement
3596 phi_iter points to. */
3597 phi_bnd = phi_iter.phi ();
3599 add_phi_arg (phi_bnd, arg_bnd,
3600 gimple_phi_arg_edge (def_phi, i),
3601 UNKNOWN_LOCATION);
3604 /* If all bound phi nodes have their arg computed
3605 then we may finish its computation. See
3606 chkp_finish_incomplete_bounds for more details. */
3607 if (chkp_may_finish_incomplete_bounds ())
3608 chkp_finish_incomplete_bounds ();
3611 gcc_assert (bounds == chkp_get_registered_bounds (ptr_src)
3612 || chkp_incomplete_bounds (bounds));
3614 break;
3616 case ADDR_EXPR:
3617 bounds = chkp_make_addressed_object_bounds (TREE_OPERAND (ptr_src, 0), iter);
3618 break;
3620 case INTEGER_CST:
3621 if (integer_zerop (ptr_src))
3622 bounds = chkp_get_none_bounds ();
3623 else
3624 bounds = chkp_get_invalid_op_bounds ();
3625 break;
3627 default:
3628 if (dump_file && (dump_flags & TDF_DETAILS))
3630 fprintf (dump_file, "chkp_find_bounds: unexpected ptr of type %s\n",
3631 get_tree_code_name (TREE_CODE (ptr_src)));
3632 print_node (dump_file, "", ptr_src, 0);
3634 internal_error ("chkp_find_bounds: Unexpected tree code %s",
3635 get_tree_code_name (TREE_CODE (ptr_src)));
3638 if (!bounds)
3640 if (dump_file && (dump_flags & TDF_DETAILS))
3642 fprintf (stderr, "chkp_find_bounds: cannot find bounds for pointer\n");
3643 print_node (dump_file, "", ptr_src, 0);
3645 internal_error ("chkp_find_bounds: Cannot find bounds for pointer");
3648 return bounds;
3651 /* Normal case for bounds search without forced narrowing. */
3652 static tree
3653 chkp_find_bounds (tree ptr, gimple_stmt_iterator *iter)
3655 return chkp_find_bounds_1 (ptr, NULL_TREE, iter);
3658 /* Search bounds for pointer PTR loaded from PTR_SRC
3659 by statement *ITER points to. */
3660 static tree
3661 chkp_find_bounds_loaded (tree ptr, tree ptr_src, gimple_stmt_iterator *iter)
3663 return chkp_find_bounds_1 (ptr, ptr_src, iter);
3666 /* Helper function which checks type of RHS and finds all pointers in
3667 it. For each found pointer we build it's accesses in LHS and RHS
3668 objects and then call HANDLER for them. Function is used to copy
3669 or initilize bounds for copied object. */
3670 static void
3671 chkp_walk_pointer_assignments (tree lhs, tree rhs, void *arg,
3672 assign_handler handler)
3674 tree type = TREE_TYPE (lhs);
3676 /* We have nothing to do with clobbers. */
3677 if (TREE_CLOBBER_P (rhs))
3678 return;
3680 if (BOUNDED_TYPE_P (type))
3681 handler (lhs, rhs, arg);
3682 else if (RECORD_OR_UNION_TYPE_P (type))
3684 tree field;
3686 if (TREE_CODE (rhs) == CONSTRUCTOR)
3688 unsigned HOST_WIDE_INT cnt;
3689 tree val;
3691 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (rhs), cnt, field, val)
3693 if (chkp_type_has_pointer (TREE_TYPE (field)))
3695 tree lhs_field = chkp_build_component_ref (lhs, field);
3696 chkp_walk_pointer_assignments (lhs_field, val, arg, handler);
3700 else
3701 for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
3702 if (TREE_CODE (field) == FIELD_DECL
3703 && chkp_type_has_pointer (TREE_TYPE (field)))
3705 tree rhs_field = chkp_build_component_ref (rhs, field);
3706 tree lhs_field = chkp_build_component_ref (lhs, field);
3707 chkp_walk_pointer_assignments (lhs_field, rhs_field, arg, handler);
3710 else if (TREE_CODE (type) == ARRAY_TYPE)
3712 unsigned HOST_WIDE_INT cur = 0;
3713 tree maxval = TYPE_MAX_VALUE (TYPE_DOMAIN (type));
3714 tree etype = TREE_TYPE (type);
3715 tree esize = TYPE_SIZE (etype);
3717 if (TREE_CODE (rhs) == CONSTRUCTOR)
3719 unsigned HOST_WIDE_INT cnt;
3720 tree purp, val, lhs_elem;
3722 FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (rhs), cnt, purp, val)
3724 if (purp && TREE_CODE (purp) == RANGE_EXPR)
3726 tree lo_index = TREE_OPERAND (purp, 0);
3727 tree hi_index = TREE_OPERAND (purp, 1);
3729 for (cur = (unsigned)tree_to_uhwi (lo_index);
3730 cur <= (unsigned)tree_to_uhwi (hi_index);
3731 cur++)
3733 lhs_elem = chkp_build_array_ref (lhs, etype, esize, cur);
3734 chkp_walk_pointer_assignments (lhs_elem, val, arg, handler);
3737 else
3739 if (purp)
3741 gcc_assert (TREE_CODE (purp) == INTEGER_CST);
3742 cur = tree_to_uhwi (purp);
3745 lhs_elem = chkp_build_array_ref (lhs, etype, esize, cur++);
3747 chkp_walk_pointer_assignments (lhs_elem, val, arg, handler);
3751 /* Copy array only when size is known. */
3752 else if (maxval && !integer_minus_onep (maxval))
3753 for (cur = 0; cur <= TREE_INT_CST_LOW (maxval); cur++)
3755 tree lhs_elem = chkp_build_array_ref (lhs, etype, esize, cur);
3756 tree rhs_elem = chkp_build_array_ref (rhs, etype, esize, cur);
3757 chkp_walk_pointer_assignments (lhs_elem, rhs_elem, arg, handler);
3760 else
3761 internal_error("chkp_walk_pointer_assignments: unexpected RHS type: %s",
3762 get_tree_code_name (TREE_CODE (type)));
3765 /* Add code to copy bounds for assignment of RHS to LHS.
3766 ARG is an iterator pointing ne code position. */
3767 static void
3768 chkp_copy_bounds_for_elem (tree lhs, tree rhs, void *arg)
3770 gimple_stmt_iterator *iter = (gimple_stmt_iterator *)arg;
3771 tree bounds = chkp_find_bounds (rhs, iter);
3772 tree addr = chkp_build_addr_expr(lhs);
3774 chkp_build_bndstx (addr, rhs, bounds, iter);
3777 /* Emit static bound initilizers and size vars. */
3778 void
3779 chkp_finish_file (void)
3781 struct varpool_node *node;
3782 struct chkp_ctor_stmt_list stmts;
3784 if (seen_error ())
3785 return;
3787 /* Iterate through varpool and generate bounds initialization
3788 constructors for all statically initialized pointers. */
3789 stmts.avail = MAX_STMTS_IN_STATIC_CHKP_CTOR;
3790 stmts.stmts = NULL;
3791 FOR_EACH_VARIABLE (node)
3792 /* Check that var is actually emitted and we need and may initialize
3793 its bounds. */
3794 if (node->need_bounds_init
3795 && !POINTER_BOUNDS_P (node->decl)
3796 && DECL_RTL (node->decl)
3797 && MEM_P (DECL_RTL (node->decl))
3798 && TREE_ASM_WRITTEN (node->decl))
3800 chkp_walk_pointer_assignments (node->decl,
3801 DECL_INITIAL (node->decl),
3802 &stmts,
3803 chkp_add_modification_to_stmt_list);
3805 if (stmts.avail <= 0)
3807 cgraph_build_static_cdtor ('P', stmts.stmts,
3808 MAX_RESERVED_INIT_PRIORITY + 3);
3809 stmts.avail = MAX_STMTS_IN_STATIC_CHKP_CTOR;
3810 stmts.stmts = NULL;
3814 if (stmts.stmts)
3815 cgraph_build_static_cdtor ('P', stmts.stmts,
3816 MAX_RESERVED_INIT_PRIORITY + 3);
3818 /* Iterate through varpool and generate bounds initialization
3819 constructors for all static bounds vars. */
3820 stmts.avail = MAX_STMTS_IN_STATIC_CHKP_CTOR;
3821 stmts.stmts = NULL;
3822 FOR_EACH_VARIABLE (node)
3823 if (node->need_bounds_init
3824 && POINTER_BOUNDS_P (node->decl)
3825 && TREE_ASM_WRITTEN (node->decl))
3827 tree bnd = node->decl;
3828 tree var;
3830 gcc_assert (DECL_INITIAL (bnd)
3831 && TREE_CODE (DECL_INITIAL (bnd)) == ADDR_EXPR);
3833 var = TREE_OPERAND (DECL_INITIAL (bnd), 0);
3834 chkp_output_static_bounds (bnd, var, &stmts);
3837 if (stmts.stmts)
3838 cgraph_build_static_cdtor ('B', stmts.stmts,
3839 MAX_RESERVED_INIT_PRIORITY + 2);
3841 delete chkp_static_var_bounds;
3842 delete chkp_bounds_map;
3845 /* An instrumentation function which is called for each statement
3846 having memory access we want to instrument. It inserts check
3847 code and bounds copy code.
3849 ITER points to statement to instrument.
3851 NODE holds memory access in statement to check.
3853 LOC holds the location information for statement.
3855 DIRFLAGS determines whether access is read or write.
3857 ACCESS_OFFS should be added to address used in NODE
3858 before check.
3860 ACCESS_SIZE holds size of checked access.
3862 SAFE indicates if NODE access is safe and should not be
3863 checked. */
3864 static void
3865 chkp_process_stmt (gimple_stmt_iterator *iter, tree node,
3866 location_t loc, tree dirflag,
3867 tree access_offs, tree access_size,
3868 bool safe)
3870 tree node_type = TREE_TYPE (node);
3871 tree size = access_size ? access_size : TYPE_SIZE_UNIT (node_type);
3872 tree addr_first = NULL_TREE; /* address of the first accessed byte */
3873 tree addr_last = NULL_TREE; /* address of the last accessed byte */
3874 tree ptr = NULL_TREE; /* a pointer used for dereference */
3875 tree bounds = NULL_TREE;
3877 /* We do not need instrumentation for clobbers. */
3878 if (dirflag == integer_one_node
3879 && gimple_code (gsi_stmt (*iter)) == GIMPLE_ASSIGN
3880 && TREE_CLOBBER_P (gimple_assign_rhs1 (gsi_stmt (*iter))))
3881 return;
3883 switch (TREE_CODE (node))
3885 case ARRAY_REF:
3886 case COMPONENT_REF:
3888 bool bitfield;
3889 tree elt;
3891 if (safe)
3893 /* We are not going to generate any checks, so do not
3894 generate bounds as well. */
3895 addr_first = chkp_build_addr_expr (node);
3896 break;
3899 chkp_parse_array_and_component_ref (node, &ptr, &elt, &safe,
3900 &bitfield, &bounds, iter, false);
3902 /* Break if there is no dereference and operation is safe. */
3904 if (bitfield)
3906 tree field = TREE_OPERAND (node, 1);
3908 if (TREE_CODE (DECL_SIZE_UNIT (field)) == INTEGER_CST)
3909 size = DECL_SIZE_UNIT (field);
3911 if (elt)
3912 elt = chkp_build_addr_expr (elt);
3913 addr_first = fold_convert_loc (loc, ptr_type_node, elt ? elt : ptr);
3914 addr_first = fold_build_pointer_plus_loc (loc,
3915 addr_first,
3916 byte_position (field));
3918 else
3919 addr_first = chkp_build_addr_expr (node);
3921 break;
3923 case INDIRECT_REF:
3924 ptr = TREE_OPERAND (node, 0);
3925 addr_first = ptr;
3926 break;
3928 case MEM_REF:
3929 ptr = TREE_OPERAND (node, 0);
3930 addr_first = chkp_build_addr_expr (node);
3931 break;
3933 case TARGET_MEM_REF:
3934 ptr = TMR_BASE (node);
3935 addr_first = chkp_build_addr_expr (node);
3936 break;
3938 case ARRAY_RANGE_REF:
3939 printf("ARRAY_RANGE_REF\n");
3940 debug_gimple_stmt(gsi_stmt(*iter));
3941 debug_tree(node);
3942 gcc_unreachable ();
3943 break;
3945 case BIT_FIELD_REF:
3947 tree offs, rem, bpu;
3949 gcc_assert (!access_offs);
3950 gcc_assert (!access_size);
3952 bpu = fold_convert (size_type_node, bitsize_int (BITS_PER_UNIT));
3953 offs = fold_convert (size_type_node, TREE_OPERAND (node, 2));
3954 rem = size_binop_loc (loc, TRUNC_MOD_EXPR, offs, bpu);
3955 offs = size_binop_loc (loc, TRUNC_DIV_EXPR, offs, bpu);
3957 size = fold_convert (size_type_node, TREE_OPERAND (node, 1));
3958 size = size_binop_loc (loc, PLUS_EXPR, size, rem);
3959 size = size_binop_loc (loc, CEIL_DIV_EXPR, size, bpu);
3960 size = fold_convert (size_type_node, size);
3962 chkp_process_stmt (iter, TREE_OPERAND (node, 0), loc,
3963 dirflag, offs, size, safe);
3964 return;
3966 break;
3968 case VAR_DECL:
3969 case RESULT_DECL:
3970 case PARM_DECL:
3971 if (dirflag != integer_one_node
3972 || DECL_REGISTER (node))
3973 return;
3975 safe = true;
3976 addr_first = chkp_build_addr_expr (node);
3977 break;
3979 default:
3980 return;
3983 /* If addr_last was not computed then use (addr_first + size - 1)
3984 expression to compute it. */
3985 if (!addr_last)
3987 addr_last = fold_build_pointer_plus_loc (loc, addr_first, size);
3988 addr_last = fold_build_pointer_plus_hwi_loc (loc, addr_last, -1);
3991 /* Shift both first_addr and last_addr by access_offs if specified. */
3992 if (access_offs)
3994 addr_first = fold_build_pointer_plus_loc (loc, addr_first, access_offs);
3995 addr_last = fold_build_pointer_plus_loc (loc, addr_last, access_offs);
3998 /* Generate bndcl/bndcu checks if memory access is not safe. */
3999 if (!safe)
4001 gimple_stmt_iterator stmt_iter = *iter;
4003 if (!bounds)
4004 bounds = chkp_find_bounds (ptr, iter);
4006 chkp_check_mem_access (addr_first, addr_last, bounds,
4007 stmt_iter, loc, dirflag);
4010 /* We need to store bounds in case pointer is stored. */
4011 if (dirflag == integer_one_node
4012 && chkp_type_has_pointer (node_type)
4013 && flag_chkp_store_bounds)
4015 gimple stmt = gsi_stmt (*iter);
4016 tree rhs1 = gimple_assign_rhs1 (stmt);
4017 enum tree_code rhs_code = gimple_assign_rhs_code (stmt);
4019 if (get_gimple_rhs_class (rhs_code) == GIMPLE_SINGLE_RHS)
4020 chkp_walk_pointer_assignments (node, rhs1, iter,
4021 chkp_copy_bounds_for_elem);
4022 else
4024 bounds = chkp_compute_bounds_for_assignment (NULL_TREE, stmt);
4025 chkp_build_bndstx (addr_first, rhs1, bounds, iter);
4030 /* Add code to copy bounds for all pointers copied
4031 in ASSIGN created during inline of EDGE. */
4032 void
4033 chkp_copy_bounds_for_assign (gimple assign, struct cgraph_edge *edge)
4035 tree lhs = gimple_assign_lhs (assign);
4036 tree rhs = gimple_assign_rhs1 (assign);
4037 gimple_stmt_iterator iter = gsi_for_stmt (assign);
4039 if (!flag_chkp_store_bounds)
4040 return;
4042 chkp_walk_pointer_assignments (lhs, rhs, &iter, chkp_copy_bounds_for_elem);
4044 /* We should create edges for all created calls to bndldx and bndstx. */
4045 while (gsi_stmt (iter) != assign)
4047 gimple stmt = gsi_stmt (iter);
4048 if (gimple_code (stmt) == GIMPLE_CALL)
4050 tree fndecl = gimple_call_fndecl (stmt);
4051 struct cgraph_node *callee = cgraph_node::get_create (fndecl);
4052 struct cgraph_edge *new_edge;
4054 gcc_assert (fndecl == chkp_bndstx_fndecl
4055 || fndecl == chkp_bndldx_fndecl
4056 || fndecl == chkp_ret_bnd_fndecl);
4058 new_edge = edge->caller->create_edge (callee,
4059 as_a <gcall *> (stmt),
4060 edge->count,
4061 edge->frequency);
4062 new_edge->frequency = compute_call_stmt_bb_frequency
4063 (edge->caller->decl, gimple_bb (stmt));
4065 gsi_prev (&iter);
4069 /* Some code transformation made during instrumentation pass
4070 may put code into inconsistent state. Here we find and fix
4071 such flaws. */
4072 void
4073 chkp_fix_cfg ()
4075 basic_block bb;
4076 gimple_stmt_iterator i;
4078 /* We could insert some code right after stmt which ends bb.
4079 We wanted to put this code on fallthru edge but did not
4080 add new edges from the beginning because it may cause new
4081 phi node creation which may be incorrect due to incomplete
4082 bound phi nodes. */
4083 FOR_ALL_BB_FN (bb, cfun)
4084 for (i = gsi_start_bb (bb); !gsi_end_p (i); gsi_next (&i))
4086 gimple stmt = gsi_stmt (i);
4087 gimple_stmt_iterator next = i;
4089 gsi_next (&next);
4091 if (stmt_ends_bb_p (stmt)
4092 && !gsi_end_p (next))
4094 edge fall = find_fallthru_edge (bb->succs);
4095 basic_block dest = NULL;
4096 int flags = 0;
4098 gcc_assert (fall);
4100 /* We cannot split abnormal edge. Therefore we
4101 store its params, make it regular and then
4102 rebuild abnormal edge after split. */
4103 if (fall->flags & EDGE_ABNORMAL)
4105 flags = fall->flags & ~EDGE_FALLTHRU;
4106 dest = fall->dest;
4108 fall->flags &= ~EDGE_COMPLEX;
4111 while (!gsi_end_p (next))
4113 gimple next_stmt = gsi_stmt (next);
4114 gsi_remove (&next, false);
4115 gsi_insert_on_edge (fall, next_stmt);
4118 gsi_commit_edge_inserts ();
4120 /* Re-create abnormal edge. */
4121 if (dest)
4122 make_edge (bb, dest, flags);
4127 /* Walker callback for chkp_replace_function_pointers. Replaces
4128 function pointer in the specified operand with pointer to the
4129 instrumented function version. */
4130 static tree
4131 chkp_replace_function_pointer (tree *op, int *walk_subtrees,
4132 void *data ATTRIBUTE_UNUSED)
4134 if (TREE_CODE (*op) == FUNCTION_DECL
4135 && chkp_instrumentable_p (*op)
4136 && (DECL_BUILT_IN_CLASS (*op) == NOT_BUILT_IN
4137 /* For builtins we replace pointers only for selected
4138 function and functions having definitions. */
4139 || (DECL_BUILT_IN_CLASS (*op) == BUILT_IN_NORMAL
4140 && (chkp_instrument_normal_builtin (*op)
4141 || gimple_has_body_p (*op)))))
4143 struct cgraph_node *node = cgraph_node::get_create (*op);
4144 struct cgraph_node *clone = NULL;
4146 if (!node->instrumentation_clone)
4147 clone = chkp_maybe_create_clone (*op);
4149 if (clone)
4150 *op = clone->decl;
4151 *walk_subtrees = 0;
4154 return NULL;
4157 /* This function searches for function pointers in statement
4158 pointed by GSI and replaces them with pointers to instrumented
4159 function versions. */
4160 static void
4161 chkp_replace_function_pointers (gimple_stmt_iterator *gsi)
4163 gimple stmt = gsi_stmt (*gsi);
4164 /* For calls we want to walk call args only. */
4165 if (gimple_code (stmt) == GIMPLE_CALL)
4167 unsigned i;
4168 for (i = 0; i < gimple_call_num_args (stmt); i++)
4169 walk_tree (gimple_call_arg_ptr (stmt, i),
4170 chkp_replace_function_pointer, NULL, NULL);
4172 else
4173 walk_gimple_stmt (gsi, NULL, chkp_replace_function_pointer, NULL);
4176 /* This function instruments all statements working with memory,
4177 calls and rets.
4179 It also removes excess statements from static initializers. */
4180 static void
4181 chkp_instrument_function (void)
4183 basic_block bb, next;
4184 gimple_stmt_iterator i;
4185 enum gimple_rhs_class grhs_class;
4186 bool safe = lookup_attribute ("chkp ctor", DECL_ATTRIBUTES (cfun->decl));
4188 bb = ENTRY_BLOCK_PTR_FOR_FN (cfun)->next_bb;
4191 next = bb->next_bb;
4192 for (i = gsi_start_bb (bb); !gsi_end_p (i); )
4194 gimple s = gsi_stmt (i);
4196 /* Skip statement marked to not be instrumented. */
4197 if (chkp_marked_stmt_p (s))
4199 gsi_next (&i);
4200 continue;
4203 chkp_replace_function_pointers (&i);
4205 switch (gimple_code (s))
4207 case GIMPLE_ASSIGN:
4208 chkp_process_stmt (&i, gimple_assign_lhs (s),
4209 gimple_location (s), integer_one_node,
4210 NULL_TREE, NULL_TREE, safe);
4211 chkp_process_stmt (&i, gimple_assign_rhs1 (s),
4212 gimple_location (s), integer_zero_node,
4213 NULL_TREE, NULL_TREE, safe);
4214 grhs_class = get_gimple_rhs_class (gimple_assign_rhs_code (s));
4215 if (grhs_class == GIMPLE_BINARY_RHS)
4216 chkp_process_stmt (&i, gimple_assign_rhs2 (s),
4217 gimple_location (s), integer_zero_node,
4218 NULL_TREE, NULL_TREE, safe);
4219 break;
4221 case GIMPLE_RETURN:
4223 greturn *r = as_a <greturn *> (s);
4224 if (gimple_return_retval (r) != NULL_TREE)
4226 chkp_process_stmt (&i, gimple_return_retval (r),
4227 gimple_location (r),
4228 integer_zero_node,
4229 NULL_TREE, NULL_TREE, safe);
4231 /* Additionally we need to add bounds
4232 to return statement. */
4233 chkp_add_bounds_to_ret_stmt (&i);
4236 break;
4238 case GIMPLE_CALL:
4239 chkp_add_bounds_to_call_stmt (&i);
4240 break;
4242 default:
4246 gsi_next (&i);
4248 /* We do not need any actual pointer stores in checker
4249 static initializer. */
4250 if (lookup_attribute ("chkp ctor", DECL_ATTRIBUTES (cfun->decl))
4251 && gimple_code (s) == GIMPLE_ASSIGN
4252 && gimple_store_p (s))
4254 gimple_stmt_iterator del_iter = gsi_for_stmt (s);
4255 gsi_remove (&del_iter, true);
4256 unlink_stmt_vdef (s);
4257 release_defs(s);
4260 bb = next;
4262 while (bb);
4264 /* Some input params may have bounds and be address taken. In this case
4265 we should store incoming bounds into bounds table. */
4266 tree arg;
4267 if (flag_chkp_store_bounds)
4268 for (arg = DECL_ARGUMENTS (cfun->decl); arg; arg = DECL_CHAIN (arg))
4269 if (TREE_ADDRESSABLE (arg))
4271 if (BOUNDED_P (arg))
4273 tree bounds = chkp_get_next_bounds_parm (arg);
4274 tree def_ptr = ssa_default_def (cfun, arg);
4275 gimple_stmt_iterator iter
4276 = gsi_start_bb (chkp_get_entry_block ());
4277 chkp_build_bndstx (chkp_build_addr_expr (arg),
4278 def_ptr ? def_ptr : arg,
4279 bounds, &iter);
4281 /* Skip bounds arg. */
4282 arg = TREE_CHAIN (arg);
4284 else if (chkp_type_has_pointer (TREE_TYPE (arg)))
4286 tree orig_arg = arg;
4287 bitmap slots = BITMAP_ALLOC (NULL);
4288 gimple_stmt_iterator iter
4289 = gsi_start_bb (chkp_get_entry_block ());
4290 bitmap_iterator bi;
4291 unsigned bnd_no;
4293 chkp_find_bound_slots (TREE_TYPE (arg), slots);
4295 EXECUTE_IF_SET_IN_BITMAP (slots, 0, bnd_no, bi)
4297 tree bounds = chkp_get_next_bounds_parm (arg);
4298 HOST_WIDE_INT offs = bnd_no * POINTER_SIZE / BITS_PER_UNIT;
4299 tree addr = chkp_build_addr_expr (orig_arg);
4300 tree ptr = build2 (MEM_REF, ptr_type_node, addr,
4301 build_int_cst (ptr_type_node, offs));
4302 chkp_build_bndstx (chkp_build_addr_expr (ptr), ptr,
4303 bounds, &iter);
4305 arg = DECL_CHAIN (arg);
4307 BITMAP_FREE (slots);
4312 /* Find init/null/copy_ptr_bounds calls and replace them
4313 with assignments. It should allow better code
4314 optimization. */
4316 static void
4317 chkp_remove_useless_builtins ()
4319 basic_block bb;
4320 gimple_stmt_iterator gsi;
4322 FOR_EACH_BB_FN (bb, cfun)
4324 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
4326 gimple stmt = gsi_stmt (gsi);
4327 tree fndecl;
4328 enum built_in_function fcode;
4330 /* Find builtins returning first arg and replace
4331 them with assignments. */
4332 if (gimple_code (stmt) == GIMPLE_CALL
4333 && (fndecl = gimple_call_fndecl (stmt))
4334 && DECL_BUILT_IN_CLASS (fndecl) == BUILT_IN_NORMAL
4335 && (fcode = DECL_FUNCTION_CODE (fndecl))
4336 && (fcode == BUILT_IN_CHKP_INIT_PTR_BOUNDS
4337 || fcode == BUILT_IN_CHKP_NULL_PTR_BOUNDS
4338 || fcode == BUILT_IN_CHKP_COPY_PTR_BOUNDS
4339 || fcode == BUILT_IN_CHKP_SET_PTR_BOUNDS))
4341 tree res = gimple_call_arg (stmt, 0);
4342 update_call_from_tree (&gsi, res);
4343 stmt = gsi_stmt (gsi);
4344 update_stmt (stmt);
4350 /* Initialize pass. */
4351 static void
4352 chkp_init (void)
4354 basic_block bb;
4355 gimple_stmt_iterator i;
4357 in_chkp_pass = true;
4359 for (bb = ENTRY_BLOCK_PTR_FOR_FN (cfun)->next_bb; bb; bb = bb->next_bb)
4360 for (i = gsi_start_bb (bb); !gsi_end_p (i); gsi_next (&i))
4361 chkp_unmark_stmt (gsi_stmt (i));
4363 chkp_invalid_bounds = new hash_set<tree>;
4364 chkp_completed_bounds_set = new hash_set<tree>;
4365 delete chkp_reg_bounds;
4366 chkp_reg_bounds = new hash_map<tree, tree>;
4367 delete chkp_bound_vars;
4368 chkp_bound_vars = new hash_map<tree, tree>;
4369 chkp_reg_addr_bounds = new hash_map<tree, tree>;
4370 chkp_incomplete_bounds_map = new hash_map<tree, tree>;
4371 delete chkp_bounds_map;
4372 chkp_bounds_map = new hash_map<tree, tree>;
4373 chkp_abnormal_copies = BITMAP_GGC_ALLOC ();
4375 entry_block = NULL;
4376 zero_bounds = NULL_TREE;
4377 none_bounds = NULL_TREE;
4378 incomplete_bounds = integer_zero_node;
4379 tmp_var = NULL_TREE;
4380 size_tmp_var = NULL_TREE;
4382 chkp_uintptr_type = lang_hooks.types.type_for_mode (ptr_mode, true);
4384 /* We create these constant bounds once for each object file.
4385 These symbols go to comdat section and result in single copy
4386 of each one in the final binary. */
4387 chkp_get_zero_bounds_var ();
4388 chkp_get_none_bounds_var ();
4390 calculate_dominance_info (CDI_DOMINATORS);
4391 calculate_dominance_info (CDI_POST_DOMINATORS);
4393 bitmap_obstack_initialize (NULL);
4396 /* Finalize instrumentation pass. */
4397 static void
4398 chkp_fini (void)
4400 in_chkp_pass = false;
4402 delete chkp_invalid_bounds;
4403 delete chkp_completed_bounds_set;
4404 delete chkp_reg_addr_bounds;
4405 delete chkp_incomplete_bounds_map;
4407 free_dominance_info (CDI_DOMINATORS);
4408 free_dominance_info (CDI_POST_DOMINATORS);
4410 bitmap_obstack_release (NULL);
4412 entry_block = NULL;
4413 zero_bounds = NULL_TREE;
4414 none_bounds = NULL_TREE;
4417 /* Main instrumentation pass function. */
4418 static unsigned int
4419 chkp_execute (void)
4421 chkp_init ();
4423 chkp_instrument_function ();
4425 chkp_remove_useless_builtins ();
4427 chkp_function_mark_instrumented (cfun->decl);
4429 chkp_fix_cfg ();
4431 chkp_fini ();
4433 return 0;
4436 /* Instrumentation pass gate. */
4437 static bool
4438 chkp_gate (void)
4440 return cgraph_node::get (cfun->decl)->instrumentation_clone
4441 || lookup_attribute ("chkp ctor", DECL_ATTRIBUTES (cfun->decl));
4444 namespace {
4446 const pass_data pass_data_chkp =
4448 GIMPLE_PASS, /* type */
4449 "chkp", /* name */
4450 OPTGROUP_NONE, /* optinfo_flags */
4451 TV_NONE, /* tv_id */
4452 PROP_ssa | PROP_cfg, /* properties_required */
4453 0, /* properties_provided */
4454 0, /* properties_destroyed */
4455 0, /* todo_flags_start */
4456 TODO_verify_il
4457 | TODO_update_ssa /* todo_flags_finish */
4460 class pass_chkp : public gimple_opt_pass
4462 public:
4463 pass_chkp (gcc::context *ctxt)
4464 : gimple_opt_pass (pass_data_chkp, ctxt)
4467 /* opt_pass methods: */
4468 virtual opt_pass * clone ()
4470 return new pass_chkp (m_ctxt);
4473 virtual bool gate (function *)
4475 return chkp_gate ();
4478 virtual unsigned int execute (function *)
4480 return chkp_execute ();
4483 }; // class pass_chkp
4485 } // anon namespace
4487 gimple_opt_pass *
4488 make_pass_chkp (gcc::context *ctxt)
4490 return new pass_chkp (ctxt);
4493 #include "gt-tree-chkp.h"