re PR middle-end/91603 (Unaligned access in expand_assignment)
[official-gcc.git] / gcc / gimple-ssa-warn-restrict.c
blobcbfc47894dc5619140cf4a1e44c07f20b50209c9
1 /* Pass to detect and issue warnings for violations of the restrict
2 qualifier.
3 Copyright (C) 2017-2019 Free Software Foundation, Inc.
4 Contributed by Martin Sebor <msebor@redhat.com>.
6 This file is part of GCC.
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 3, or (at your option) any later
11 version.
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16 for more details.
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3. If not see
20 <http://www.gnu.org/licenses/>. */
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "backend.h"
26 #include "tree.h"
27 #include "gimple.h"
28 #include "domwalk.h"
29 #include "tree-pass.h"
30 #include "builtins.h"
31 #include "ssa.h"
32 #include "gimple-pretty-print.h"
33 #include "gimple-ssa-warn-restrict.h"
34 #include "diagnostic-core.h"
35 #include "fold-const.h"
36 #include "gimple-iterator.h"
37 #include "tree-dfa.h"
38 #include "tree-ssa.h"
39 #include "params.h"
40 #include "tree-cfg.h"
41 #include "tree-object-size.h"
42 #include "calls.h"
43 #include "cfgloop.h"
44 #include "intl.h"
46 namespace {
48 const pass_data pass_data_wrestrict = {
49 GIMPLE_PASS,
50 "wrestrict",
51 OPTGROUP_NONE,
52 TV_NONE,
53 PROP_cfg, /* Properties_required. */
54 0, /* properties_provided. */
55 0, /* properties_destroyed. */
56 0, /* properties_start */
57 0, /* properties_finish */
60 /* Pass to detect violations of strict aliasing requirements in calls
61 to built-in string and raw memory functions. */
62 class pass_wrestrict : public gimple_opt_pass
64 public:
65 pass_wrestrict (gcc::context *ctxt)
66 : gimple_opt_pass (pass_data_wrestrict, ctxt)
67 { }
69 opt_pass *clone () { return new pass_wrestrict (m_ctxt); }
71 virtual bool gate (function *);
72 virtual unsigned int execute (function *);
75 bool
76 pass_wrestrict::gate (function *fun ATTRIBUTE_UNUSED)
78 return warn_array_bounds || warn_restrict || warn_stringop_overflow;
81 /* Class to walk the basic blocks of a function in dominator order. */
82 class wrestrict_dom_walker : public dom_walker
84 public:
85 wrestrict_dom_walker () : dom_walker (CDI_DOMINATORS) {}
87 edge before_dom_children (basic_block) FINAL OVERRIDE;
88 bool handle_gimple_call (gimple_stmt_iterator *);
90 private:
91 void check_call (gimple *);
94 edge
95 wrestrict_dom_walker::before_dom_children (basic_block bb)
97 /* Iterate over statements, looking for function calls. */
98 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
99 gsi_next (&si))
101 gimple *stmt = gsi_stmt (si);
102 if (!is_gimple_call (stmt))
103 continue;
105 check_call (stmt);
108 return NULL;
111 /* Execute the pass for function FUN, walking in dominator order. */
113 unsigned
114 pass_wrestrict::execute (function *fun)
116 calculate_dominance_info (CDI_DOMINATORS);
118 wrestrict_dom_walker walker;
119 walker.walk (ENTRY_BLOCK_PTR_FOR_FN (fun));
121 return 0;
124 /* Description of a memory reference by a built-in function. This
125 is similar to ao_ref but made especially suitable for -Wrestrict
126 and not for optimization. */
127 class builtin_memref
129 public:
130 /* The original pointer argument to the built-in function. */
131 tree ptr;
132 /* The referenced subobject or NULL if not available, and the base
133 object of the memory reference or NULL. */
134 tree ref;
135 tree base;
137 /* The size of the BASE object, PTRDIFF_MAX if indeterminate,
138 and negative until (possibly lazily) initialized. */
139 offset_int basesize;
141 /* The non-negative offset of the referenced subobject. Used to avoid
142 warnings for (apparently) possibly but not definitively overlapping
143 accesses to member arrays. Negative when unknown/invalid. */
144 offset_int refoff;
146 /* The offset range relative to the base. */
147 offset_int offrange[2];
148 /* The size range of the access to this reference. */
149 offset_int sizrange[2];
151 /* Cached result of get_max_objsize(). */
152 const offset_int maxobjsize;
154 /* True for "bounded" string functions like strncat, and strncpy
155 and their variants that specify either an exact or upper bound
156 on the size of the accesses they perform. For strncat both
157 the source and destination references are bounded. For strncpy
158 only the destination reference is. */
159 bool strbounded_p;
161 builtin_memref (tree, tree);
163 tree offset_out_of_bounds (int, offset_int[2]) const;
165 private:
167 /* Ctor helper to set or extend OFFRANGE based on argument. */
168 void extend_offset_range (tree);
170 /* Ctor helper to determine BASE and OFFRANGE from argument. */
171 void set_base_and_offset (tree);
174 /* Description of a memory access by a raw memory or string built-in
175 function involving a pair of builtin_memref's. */
176 class builtin_access
178 public:
179 /* Destination and source memory reference. */
180 builtin_memref* const dstref;
181 builtin_memref* const srcref;
182 /* The size range of the access. It's the greater of the accesses
183 to the two references. */
184 HOST_WIDE_INT sizrange[2];
186 /* The minimum and maximum offset of an overlap of the access
187 (if it does, in fact, overlap), and the size of the overlap. */
188 HOST_WIDE_INT ovloff[2];
189 HOST_WIDE_INT ovlsiz[2];
191 /* True to consider valid only accesses to the smallest subobject
192 and false for raw memory functions. */
193 bool strict () const
195 return detect_overlap != &builtin_access::generic_overlap;
198 builtin_access (gimple *, builtin_memref &, builtin_memref &);
200 /* Entry point to determine overlap. */
201 bool overlap ();
203 private:
204 /* Implementation functions used to determine overlap. */
205 bool generic_overlap ();
206 bool strcat_overlap ();
207 bool strcpy_overlap ();
209 bool no_overlap ()
211 return false;
214 offset_int overlap_size (const offset_int [2], const offset_int[2],
215 offset_int [2]);
217 private:
218 /* Temporaries used to compute the final result. */
219 offset_int dstoff[2];
220 offset_int srcoff[2];
221 offset_int dstsiz[2];
222 offset_int srcsiz[2];
224 /* Pointer to a member function to call to determine overlap. */
225 bool (builtin_access::*detect_overlap) ();
228 /* Initialize a memory reference representation from a pointer EXPR and
229 a size SIZE in bytes. If SIZE is NULL_TREE then the size is assumed
230 to be unknown. */
232 builtin_memref::builtin_memref (tree expr, tree size)
233 : ptr (expr),
234 ref (),
235 base (),
236 basesize (-1),
237 refoff (HOST_WIDE_INT_MIN),
238 offrange (),
239 sizrange (),
240 maxobjsize (tree_to_shwi (max_object_size ())),
241 strbounded_p ()
243 /* Unfortunately, wide_int default ctor is a no-op so array members
244 of the type must be set individually. */
245 offrange[0] = offrange[1] = 0;
246 sizrange[0] = sizrange[1] = 0;
248 if (!expr)
249 return;
251 /* Find the BASE object or pointer referenced by EXPR and set
252 the offset range OFFRANGE in the process. */
253 set_base_and_offset (expr);
255 if (size)
257 tree range[2];
258 /* Determine the size range, allowing for the result to be [0, 0]
259 for SIZE in the anti-range ~[0, N] where N >= PTRDIFF_MAX. */
260 get_size_range (size, range, true);
261 sizrange[0] = wi::to_offset (range[0]);
262 sizrange[1] = wi::to_offset (range[1]);
263 /* get_size_range returns SIZE_MAX for the maximum size.
264 Constrain it to the real maximum of PTRDIFF_MAX. */
265 if (sizrange[0] <= maxobjsize && sizrange[1] > maxobjsize)
266 sizrange[1] = maxobjsize;
268 else
269 sizrange[1] = maxobjsize;
271 if (!DECL_P (base))
272 return;
274 /* If the offset could be in the range of the referenced object
275 constrain its bounds so neither exceeds those of the object. */
276 if (offrange[0] < 0 && offrange[1] > 0)
277 offrange[0] = 0;
279 offset_int maxoff = maxobjsize;
280 tree basetype = TREE_TYPE (base);
281 if (TREE_CODE (basetype) == ARRAY_TYPE)
283 if (ref && array_at_struct_end_p (ref))
284 ; /* Use the maximum possible offset for last member arrays. */
285 else if (tree basesize = TYPE_SIZE_UNIT (basetype))
286 if (TREE_CODE (basesize) == INTEGER_CST)
287 /* Size could be non-constant for a variable-length type such
288 as a struct with a VLA member (a GCC extension). */
289 maxoff = wi::to_offset (basesize);
292 if (offrange[0] >= 0)
294 if (offrange[1] < 0)
295 offrange[1] = offrange[0] <= maxoff ? maxoff : maxobjsize;
296 else if (offrange[0] <= maxoff && offrange[1] > maxoff)
297 offrange[1] = maxoff;
301 /* Ctor helper to set or extend OFFRANGE based on the OFFSET argument.
302 Pointer offsets are represented as unsigned sizetype but must be
303 treated as signed. */
305 void
306 builtin_memref::extend_offset_range (tree offset)
308 if (TREE_CODE (offset) == INTEGER_CST)
310 offset_int off = int_cst_value (offset);
311 if (off != 0)
313 offrange[0] += off;
314 offrange[1] += off;
316 return;
319 if (TREE_CODE (offset) == SSA_NAME)
321 /* A pointer offset is represented as sizetype but treated
322 as signed. */
323 wide_int min, max;
324 value_range_kind rng = get_range_info (offset, &min, &max);
325 if (rng == VR_ANTI_RANGE && wi::lts_p (max, min))
327 /* Convert an anti-range whose upper bound is less than
328 its lower bound to a signed range. */
329 offrange[0] += offset_int::from (max + 1, SIGNED);
330 offrange[1] += offset_int::from (min - 1, SIGNED);
331 return;
334 if (rng == VR_RANGE
335 && (DECL_P (base) || wi::lts_p (min, max)))
337 /* Preserve the bounds of the range for an offset into
338 a known object (it may be adjusted later relative to
339 a constant offset from its beginning). Otherwise use
340 the bounds only when they are ascending when treated
341 as signed. */
342 offrange[0] += offset_int::from (min, SIGNED);
343 offrange[1] += offset_int::from (max, SIGNED);
344 return;
347 /* Handle an anti-range the same as no range at all. */
348 gimple *stmt = SSA_NAME_DEF_STMT (offset);
349 tree type;
350 if (is_gimple_assign (stmt)
351 && (type = TREE_TYPE (gimple_assign_rhs1 (stmt)))
352 && INTEGRAL_TYPE_P (type))
354 tree_code code = gimple_assign_rhs_code (stmt);
355 if (code == NOP_EXPR)
357 /* Use the bounds of the type of the NOP_EXPR operand
358 even if it's signed. The result doesn't trigger
359 warnings but makes their output more readable. */
360 offrange[0] += wi::to_offset (TYPE_MIN_VALUE (type));
361 offrange[1] += wi::to_offset (TYPE_MAX_VALUE (type));
362 return;
367 const offset_int maxoff = tree_to_shwi (max_object_size ()) >> 1;
368 const offset_int minoff = -maxoff - 1;
370 offrange[0] += minoff;
371 offrange[1] += maxoff;
374 /* Determines the base object or pointer of the reference EXPR
375 and the offset range from the beginning of the base. */
377 void
378 builtin_memref::set_base_and_offset (tree expr)
380 tree offset = NULL_TREE;
382 if (TREE_CODE (expr) == SSA_NAME)
384 /* Try to tease the offset out of the pointer. */
385 gimple *stmt = SSA_NAME_DEF_STMT (expr);
386 if (!base
387 && gimple_assign_single_p (stmt)
388 && gimple_assign_rhs_code (stmt) == ADDR_EXPR)
389 expr = gimple_assign_rhs1 (stmt);
390 else if (is_gimple_assign (stmt))
392 tree_code code = gimple_assign_rhs_code (stmt);
393 if (code == NOP_EXPR)
395 tree rhs = gimple_assign_rhs1 (stmt);
396 if (POINTER_TYPE_P (TREE_TYPE (rhs)))
397 expr = gimple_assign_rhs1 (stmt);
398 else
400 base = expr;
401 return;
404 else if (code == POINTER_PLUS_EXPR)
406 expr = gimple_assign_rhs1 (stmt);
407 offset = gimple_assign_rhs2 (stmt);
409 else
411 base = expr;
412 return;
415 else
417 /* FIXME: Handle PHI nodes in case like:
418 _12 = &MEM[(void *)&a + 2B] + _10;
420 <bb> [local count: 1073741824]:
421 # prephitmp_13 = PHI <_12, &MEM[(void *)&a + 2B]>
422 memcpy (prephitmp_13, p_7(D), 6); */
423 base = expr;
424 return;
428 if (TREE_CODE (expr) == ADDR_EXPR)
429 expr = TREE_OPERAND (expr, 0);
431 /* Stash the reference for offset validation. */
432 ref = expr;
434 poly_int64 bitsize, bitpos;
435 tree var_off;
436 machine_mode mode;
437 int sign, reverse, vol;
439 /* Determine the base object or pointer of the reference and
440 the constant bit offset from the beginning of the base.
441 If the offset has a non-constant component, it will be in
442 VAR_OFF. MODE, SIGN, REVERSE, and VOL are write only and
443 unused here. */
444 base = get_inner_reference (expr, &bitsize, &bitpos, &var_off,
445 &mode, &sign, &reverse, &vol);
447 /* get_inner_reference is not expected to return null. */
448 gcc_assert (base != NULL);
450 if (offset)
451 extend_offset_range (offset);
453 poly_int64 bytepos = exact_div (bitpos, BITS_PER_UNIT);
455 /* Convert the poly_int64 offset to offset_int. The offset
456 should be constant but be prepared for it not to be just in
457 case. */
458 offset_int cstoff;
459 if (bytepos.is_constant (&cstoff))
461 offrange[0] += cstoff;
462 offrange[1] += cstoff;
464 /* Besides the reference saved above, also stash the offset
465 for validation. */
466 if (TREE_CODE (expr) == COMPONENT_REF)
467 refoff = cstoff;
469 else
470 offrange[1] += maxobjsize;
472 if (var_off)
474 if (TREE_CODE (var_off) == INTEGER_CST)
476 cstoff = wi::to_offset (var_off);
477 offrange[0] += cstoff;
478 offrange[1] += cstoff;
480 else
481 offrange[1] += maxobjsize;
484 if (TREE_CODE (base) == MEM_REF)
486 tree memrefoff = TREE_OPERAND (base, 1);
487 extend_offset_range (memrefoff);
488 base = TREE_OPERAND (base, 0);
491 if (TREE_CODE (base) == SSA_NAME)
492 set_base_and_offset (base);
495 /* Return error_mark_node if the signed offset exceeds the bounds
496 of the address space (PTRDIFF_MAX). Otherwise, return either
497 BASE or REF when the offset exceeds the bounds of the BASE or
498 REF object, and set OOBOFF to the past-the-end offset formed
499 by the reference, including its size. When STRICT is non-zero
500 use REF size, when available, otherwise use BASE size. When
501 STRICT is greater than 1, use the size of the last array member
502 as the bound, otherwise treat such a member as a flexible array
503 member. Return NULL when the offset is in bounds. */
505 tree
506 builtin_memref::offset_out_of_bounds (int strict, offset_int ooboff[2]) const
508 if (!ptr)
509 return NULL_TREE;
511 /* A temporary, possibly adjusted, copy of the offset range. */
512 offset_int offrng[2] = { offrange[0], offrange[1] };
514 if (DECL_P (base) && TREE_CODE (TREE_TYPE (base)) == ARRAY_TYPE)
516 /* Check for offset in an anti-range with a negative lower bound.
517 For such a range, consider only the non-negative subrange. */
518 if (offrng[1] < offrng[0] && offrng[1] < 0)
519 offrng[1] = maxobjsize;
522 /* Conservative offset of the last byte of the referenced object. */
523 offset_int endoff;
525 /* The bounds need not be ordered. Set HIB to use as the index
526 of the larger of the bounds and LOB as the opposite. */
527 bool hib = wi::les_p (offrng[0], offrng[1]);
528 bool lob = !hib;
530 if (basesize < 0)
532 endoff = offrng[lob] + sizrange[0];
534 /* For a reference through a pointer to an object of unknown size
535 all initial offsets are considered valid, positive as well as
536 negative, since the pointer itself can point past the beginning
537 of the object. However, the sum of the lower bound of the offset
538 and that of the size must be less than or equal than PTRDIFF_MAX. */
539 if (endoff > maxobjsize)
540 return error_mark_node;
542 return NULL_TREE;
545 /* A reference to an object of known size must be within the bounds
546 of the base object. */
547 if (offrng[hib] < 0 || offrng[lob] > basesize)
548 return base;
550 /* The extent of the reference must also be within the bounds of
551 the base object (if known) or the maximum object size otherwise. */
552 endoff = wi::smax (offrng[lob], 0) + sizrange[0];
553 if (endoff > maxobjsize)
554 return error_mark_node;
556 offset_int size = basesize;
557 tree obj = base;
559 if (strict
560 && DECL_P (obj)
561 && ref
562 && refoff >= 0
563 && TREE_CODE (ref) == COMPONENT_REF
564 && (strict > 1
565 || !array_at_struct_end_p (ref)))
567 /* If the reference is to a member subobject, the offset must
568 be within the bounds of the subobject. */
569 tree field = TREE_OPERAND (ref, 1);
570 tree type = TREE_TYPE (field);
571 if (tree sz = TYPE_SIZE_UNIT (type))
572 if (TREE_CODE (sz) == INTEGER_CST)
574 size = refoff + wi::to_offset (sz);
575 obj = ref;
579 if (endoff <= size)
580 return NULL_TREE;
582 /* Set the out-of-bounds offset range to be one greater than
583 that delimited by the reference including its size. */
584 ooboff[lob] = size + 1;
586 if (endoff > ooboff[lob])
587 ooboff[hib] = endoff;
588 else
589 ooboff[hib] = wi::smax (offrng[lob], 0) + sizrange[1];
591 return obj;
594 /* Create an association between the memory references DST and SRC
595 for access by a call EXPR to a memory or string built-in funtion. */
597 builtin_access::builtin_access (gimple *call, builtin_memref &dst,
598 builtin_memref &src)
599 : dstref (&dst), srcref (&src), sizrange (), ovloff (), ovlsiz (),
600 dstoff (), srcoff (), dstsiz (), srcsiz ()
602 /* Zero out since the offset_int ctors invoked above are no-op. */
603 dstoff[0] = dstoff[1] = 0;
604 srcoff[0] = srcoff[1] = 0;
605 dstsiz[0] = dstsiz[1] = 0;
606 srcsiz[0] = srcsiz[1] = 0;
608 /* Object Size Type to use to determine the size of the destination
609 and source objects. Overridden below for raw memory functions. */
610 int ostype = 1;
612 /* True when the size of one reference depends on the offset of
613 itself or the other. */
614 bool depends_p = true;
616 /* True when the size of the destination reference DSTREF has been
617 determined from SRCREF and so needs to be adjusted by the latter's
618 offset. Only meaningful for bounded string functions like strncpy. */
619 bool dstadjust_p = false;
621 /* The size argument number (depends on the built-in). */
622 unsigned sizeargno = 2;
624 tree func = gimple_call_fndecl (call);
625 switch (DECL_FUNCTION_CODE (func))
627 case BUILT_IN_MEMCPY:
628 case BUILT_IN_MEMCPY_CHK:
629 case BUILT_IN_MEMPCPY:
630 case BUILT_IN_MEMPCPY_CHK:
631 ostype = 0;
632 depends_p = false;
633 detect_overlap = &builtin_access::generic_overlap;
634 break;
636 case BUILT_IN_MEMMOVE:
637 case BUILT_IN_MEMMOVE_CHK:
638 /* For memmove there is never any overlap to check for. */
639 ostype = 0;
640 depends_p = false;
641 detect_overlap = &builtin_access::no_overlap;
642 break;
644 case BUILT_IN_MEMSET:
645 case BUILT_IN_MEMSET_CHK:
646 /* For memset there is never any overlap to check for. */
647 ostype = 0;
648 depends_p = false;
649 detect_overlap = &builtin_access::no_overlap;
650 break;
652 case BUILT_IN_STPNCPY:
653 case BUILT_IN_STPNCPY_CHK:
654 case BUILT_IN_STRNCPY:
655 case BUILT_IN_STRNCPY_CHK:
656 dstref->strbounded_p = true;
657 detect_overlap = &builtin_access::strcpy_overlap;
658 break;
660 case BUILT_IN_STPCPY:
661 case BUILT_IN_STPCPY_CHK:
662 case BUILT_IN_STRCPY:
663 case BUILT_IN_STRCPY_CHK:
664 detect_overlap = &builtin_access::strcpy_overlap;
665 break;
667 case BUILT_IN_STRCAT:
668 case BUILT_IN_STRCAT_CHK:
669 detect_overlap = &builtin_access::strcat_overlap;
670 break;
672 case BUILT_IN_STRNCAT:
673 case BUILT_IN_STRNCAT_CHK:
674 dstref->strbounded_p = true;
675 srcref->strbounded_p = true;
676 detect_overlap = &builtin_access::strcat_overlap;
677 break;
679 default:
680 /* Handle other string functions here whose access may need
681 to be validated for in-bounds offsets and non-overlapping
682 copies. */
683 return;
686 const offset_int maxobjsize = dst.maxobjsize;
688 /* Try to determine the size of the base object. compute_objsize
689 expects a pointer so create one if BASE is a non-pointer object. */
690 tree addr;
691 if (dst.basesize < 0)
693 addr = dst.base;
694 if (!POINTER_TYPE_P (TREE_TYPE (addr)))
695 addr = build1 (ADDR_EXPR, (TREE_TYPE (addr)), addr);
697 if (tree dstsize = compute_objsize (addr, ostype))
698 dst.basesize = wi::to_offset (dstsize);
699 else if (POINTER_TYPE_P (TREE_TYPE (addr)))
700 dst.basesize = HOST_WIDE_INT_MIN;
701 else
702 dst.basesize = maxobjsize;
705 if (src.base && src.basesize < 0)
707 addr = src.base;
708 if (!POINTER_TYPE_P (TREE_TYPE (addr)))
709 addr = build1 (ADDR_EXPR, (TREE_TYPE (addr)), addr);
711 if (tree srcsize = compute_objsize (addr, ostype))
712 src.basesize = wi::to_offset (srcsize);
713 else if (POINTER_TYPE_P (TREE_TYPE (addr)))
714 src.basesize = HOST_WIDE_INT_MIN;
715 else
716 src.basesize = maxobjsize;
719 /* If there is no dependency between the references or the base
720 objects of the two references aren't the same there's nothing
721 else to do. */
722 if (depends_p && dstref->base != srcref->base)
723 return;
725 /* ...otherwise, make adjustments for references to the same object
726 by string built-in functions to reflect the constraints imposed
727 by the function. */
729 /* For bounded string functions determine the range of the bound
730 on the access. For others, the range stays unbounded. */
731 offset_int bounds[2] = { maxobjsize, maxobjsize };
732 if (dstref->strbounded_p)
734 unsigned nargs = gimple_call_num_args (call);
735 if (nargs <= sizeargno)
736 return;
738 tree size = gimple_call_arg (call, sizeargno);
739 tree range[2];
740 if (get_size_range (size, range, true))
742 bounds[0] = wi::to_offset (range[0]);
743 bounds[1] = wi::to_offset (range[1]);
746 /* If both references' size ranges are indeterminate use the last
747 (size) argument from the function call as a substitute. This
748 may only be necessary for strncpy (but not for memcpy where
749 the size range would have been already determined this way). */
750 if (dstref->sizrange[0] == 0 && dstref->sizrange[1] == maxobjsize
751 && srcref->sizrange[0] == 0 && srcref->sizrange[1] == maxobjsize)
753 dstref->sizrange[0] = bounds[0];
754 dstref->sizrange[1] = bounds[1];
758 /* The size range of one reference involving the same base object
759 can be determined from the size range of the other reference.
760 This makes it possible to compute accurate offsets for warnings
761 involving functions like strcpy where the length of just one of
762 the two arguments is known (determined by tree-ssa-strlen). */
763 if (dstref->sizrange[0] == 0 && dstref->sizrange[1] == maxobjsize)
765 /* When the destination size is unknown set it to the size of
766 the source. */
767 dstref->sizrange[0] = srcref->sizrange[0];
768 dstref->sizrange[1] = srcref->sizrange[1];
770 else if (srcref->sizrange[0] == 0 && srcref->sizrange[1] == maxobjsize)
772 /* When the source size is unknown set it to the size of
773 the destination. */
774 srcref->sizrange[0] = dstref->sizrange[0];
775 srcref->sizrange[1] = dstref->sizrange[1];
777 if (depends_p)
779 if (dstref->strbounded_p)
781 /* Read access by strncpy is bounded. */
782 if (bounds[0] < srcref->sizrange[0])
783 srcref->sizrange[0] = bounds[0];
784 if (bounds[1] < srcref->sizrange[1])
785 srcref->sizrange[1] = bounds[1];
788 /* For string functions, adjust the size range of the source
789 reference by the inverse boundaries of the offset (because
790 the higher the offset into the string the shorter its
791 length). */
792 if (srcref->offrange[1] >= 0
793 && srcref->offrange[1] < srcref->sizrange[0])
794 srcref->sizrange[0] -= srcref->offrange[1];
795 else
796 srcref->sizrange[0] = 0;
798 if (srcref->offrange[0] > 0)
800 if (srcref->offrange[0] < srcref->sizrange[1])
801 srcref->sizrange[1] -= srcref->offrange[0];
802 else
803 srcref->sizrange[1] = 0;
806 dstadjust_p = true;
810 if (detect_overlap == &builtin_access::generic_overlap)
812 if (dstref->strbounded_p)
814 dstref->sizrange[0] = bounds[0];
815 dstref->sizrange[1] = bounds[1];
817 if (dstref->sizrange[0] < srcref->sizrange[0])
818 srcref->sizrange[0] = dstref->sizrange[0];
820 if (dstref->sizrange[1] < srcref->sizrange[1])
821 srcref->sizrange[1] = dstref->sizrange[1];
824 else if (detect_overlap == &builtin_access::strcpy_overlap)
826 if (!dstref->strbounded_p)
828 /* For strcpy, adjust the destination size range to match that
829 of the source computed above. */
830 if (depends_p && dstadjust_p)
832 dstref->sizrange[0] = srcref->sizrange[0];
833 dstref->sizrange[1] = srcref->sizrange[1];
838 if (dstref->strbounded_p)
840 /* For strncpy, adjust the destination size range to match that
841 of the source computed above. */
842 dstref->sizrange[0] = bounds[0];
843 dstref->sizrange[1] = bounds[1];
845 if (bounds[0] < srcref->sizrange[0])
846 srcref->sizrange[0] = bounds[0];
848 if (bounds[1] < srcref->sizrange[1])
849 srcref->sizrange[1] = bounds[1];
853 offset_int
854 builtin_access::overlap_size (const offset_int a[2], const offset_int b[2],
855 offset_int *off)
857 const offset_int *p = a;
858 const offset_int *q = b;
860 /* Point P at the bigger of the two ranges and Q at the smaller. */
861 if (wi::lts_p (a[1] - a[0], b[1] - b[0]))
863 p = b;
864 q = a;
867 if (p[0] < q[0])
869 if (p[1] < q[0])
870 return 0;
872 *off = q[0];
873 return wi::smin (p[1], q[1]) - q[0];
876 if (q[1] < p[0])
877 return 0;
879 off[0] = p[0];
880 return q[1] - p[0];
883 /* Return true if the bounded mempry (memcpy amd similar) or string function
884 access (strncpy and similar) ACS overlaps. */
886 bool
887 builtin_access::generic_overlap ()
889 builtin_access &acs = *this;
890 const builtin_memref *dstref = acs.dstref;
891 const builtin_memref *srcref = acs.srcref;
893 gcc_assert (dstref->base == srcref->base);
895 const offset_int maxobjsize = acs.dstref->maxobjsize;
897 offset_int maxsize = dstref->basesize < 0 ? maxobjsize : dstref->basesize;
898 gcc_assert (maxsize <= maxobjsize);
900 /* Adjust the larger bounds of the offsets (which may be the first
901 element if the lower bound is larger than the upper bound) to
902 make them valid for the smallest access (if possible) but no smaller
903 than the smaller bounds. */
904 gcc_assert (wi::les_p (acs.dstoff[0], acs.dstoff[1]));
906 if (maxsize < acs.dstoff[1] + acs.dstsiz[0])
907 acs.dstoff[1] = maxsize - acs.dstsiz[0];
908 if (acs.dstoff[1] < acs.dstoff[0])
909 acs.dstoff[1] = acs.dstoff[0];
911 gcc_assert (wi::les_p (acs.srcoff[0], acs.srcoff[1]));
913 if (maxsize < acs.srcoff[1] + acs.srcsiz[0])
914 acs.srcoff[1] = maxsize - acs.srcsiz[0];
915 if (acs.srcoff[1] < acs.srcoff[0])
916 acs.srcoff[1] = acs.srcoff[0];
918 /* Determine the minimum and maximum space for the access given
919 the offsets. */
920 offset_int space[2];
921 space[0] = wi::abs (acs.dstoff[0] - acs.srcoff[0]);
922 space[1] = space[0];
924 offset_int d = wi::abs (acs.dstoff[0] - acs.srcoff[1]);
925 if (acs.srcsiz[0] > 0)
927 if (d < space[0])
928 space[0] = d;
930 if (space[1] < d)
931 space[1] = d;
933 else
934 space[1] = acs.dstsiz[1];
936 d = wi::abs (acs.dstoff[1] - acs.srcoff[0]);
937 if (d < space[0])
938 space[0] = d;
940 if (space[1] < d)
941 space[1] = d;
943 /* Treat raw memory functions both of whose references are bounded
944 as special and permit uncertain overlaps to go undetected. For
945 all kinds of constant offset and constant size accesses, if
946 overlap isn't certain it is not possible. */
947 bool overlap_possible = space[0] < acs.dstsiz[1];
948 if (!overlap_possible)
949 return false;
951 bool overlap_certain = space[1] < acs.dstsiz[0];
953 /* True when the size of one reference depends on the offset of
954 the other. */
955 bool depends_p = detect_overlap != &builtin_access::generic_overlap;
957 if (!overlap_certain)
959 if (!dstref->strbounded_p && !depends_p)
960 /* Memcpy only considers certain overlap. */
961 return false;
963 /* There's no way to distinguish an access to the same member
964 of a structure from one to two distinct members of the same
965 structure. Give up to avoid excessive false positives. */
966 tree basetype = TREE_TYPE (dstref->base);
968 if (POINTER_TYPE_P (basetype))
969 basetype = TREE_TYPE (basetype);
970 else
971 while (TREE_CODE (basetype) == ARRAY_TYPE)
972 basetype = TREE_TYPE (basetype);
974 if (RECORD_OR_UNION_TYPE_P (basetype))
975 return false;
978 /* True for stpcpy and strcpy. */
979 bool stxcpy_p = (!dstref->strbounded_p
980 && detect_overlap == &builtin_access::strcpy_overlap);
982 if (dstref->refoff >= 0
983 && srcref->refoff >= 0
984 && dstref->refoff != srcref->refoff
985 && (stxcpy_p || dstref->strbounded_p || srcref->strbounded_p))
986 return false;
988 offset_int siz[2] = { maxobjsize + 1, 0 };
990 ovloff[0] = HOST_WIDE_INT_MAX;
991 ovloff[1] = HOST_WIDE_INT_MIN;
993 /* Adjustment to the lower bound of the offset of the overlap to
994 account for a subset of unbounded string calls where the size
995 of the destination string depends on the length of the source
996 which in turn depends on the offset into it. */
997 bool sub1;
999 if (stxcpy_p)
1001 sub1 = acs.dstoff[0] <= acs.srcoff[0];
1003 /* Iterate over the extreme locations (on the horizontal axis formed
1004 by their offsets) and sizes of two regions and find their smallest
1005 and largest overlap and the corresponding offsets. */
1006 for (unsigned i = 0; i != 2; ++i)
1008 const offset_int a[2] = {
1009 acs.dstoff[i], acs.dstoff[i] + acs.dstsiz[!i]
1012 const offset_int b[2] = {
1013 acs.srcoff[i], acs.srcoff[i] + acs.srcsiz[!i]
1016 offset_int off;
1017 offset_int sz = overlap_size (a, b, &off);
1018 if (sz < siz[0])
1019 siz[0] = sz;
1021 if (siz[1] <= sz)
1022 siz[1] = sz;
1024 if (sz != 0)
1026 if (wi::lts_p (off, ovloff[0]))
1027 ovloff[0] = off.to_shwi ();
1028 if (wi::lts_p (ovloff[1], off))
1029 ovloff[1] = off.to_shwi ();
1033 else
1035 sub1 = !depends_p;
1037 /* Iterate over the extreme locations (on the horizontal axis
1038 formed by their offsets) and sizes of two regions and find
1039 their smallest and largest overlap and the corresponding
1040 offsets. */
1042 for (unsigned io = 0; io != 2; ++io)
1043 for (unsigned is = 0; is != 2; ++is)
1045 const offset_int a[2] = {
1046 acs.dstoff[io], acs.dstoff[io] + acs.dstsiz[is]
1049 for (unsigned jo = 0; jo != 2; ++jo)
1050 for (unsigned js = 0; js != 2; ++js)
1052 if (depends_p)
1054 /* For st{p,r}ncpy the size of the source sequence
1055 depends on the offset into it. */
1056 if (js)
1057 break;
1058 js = !jo;
1061 const offset_int b[2] = {
1062 acs.srcoff[jo], acs.srcoff[jo] + acs.srcsiz[js]
1065 offset_int off;
1066 offset_int sz = overlap_size (a, b, &off);
1067 if (sz < siz[0])
1068 siz[0] = sz;
1070 if (siz[1] <= sz)
1071 siz[1] = sz;
1073 if (sz != 0)
1075 if (wi::lts_p (off, ovloff[0]))
1076 ovloff[0] = off.to_shwi ();
1077 if (wi::lts_p (ovloff[1], off))
1078 ovloff[1] = off.to_shwi ();
1084 ovlsiz[0] = siz[0].to_shwi ();
1085 ovlsiz[1] = siz[1].to_shwi ();
1087 if (ovlsiz[0] == 0 && ovlsiz[1] > 1)
1088 ovloff[0] = ovloff[1] + ovlsiz[1] - 1 - sub1;
1090 return true;
1093 /* Return true if the strcat-like access overlaps. */
1095 bool
1096 builtin_access::strcat_overlap ()
1098 builtin_access &acs = *this;
1099 const builtin_memref *dstref = acs.dstref;
1100 const builtin_memref *srcref = acs.srcref;
1102 gcc_assert (dstref->base == srcref->base);
1104 const offset_int maxobjsize = acs.dstref->maxobjsize;
1106 gcc_assert (dstref->base && dstref->base == srcref->base);
1108 /* Adjust for strcat-like accesses. */
1110 /* As a special case for strcat, set the DSTREF offsets to the length
1111 of the source string since the function starts writing at the first
1112 nul, and set the size to 1 for the length of the nul. */
1113 acs.dstoff[0] += acs.dstsiz[0];
1114 acs.dstoff[1] += acs.dstsiz[1];
1116 bool strfunc_unknown_args = acs.dstsiz[0] == 0 && acs.dstsiz[1] != 0;
1118 /* The lower bound is zero when the size is unknown because then
1119 overlap is not certain. */
1120 acs.dstsiz[0] = strfunc_unknown_args ? 0 : 1;
1121 acs.dstsiz[1] = 1;
1123 offset_int maxsize = dstref->basesize < 0 ? maxobjsize : dstref->basesize;
1124 gcc_assert (maxsize <= maxobjsize);
1126 /* For references to the same base object, determine if there's a pair
1127 of valid offsets into the two references such that access between
1128 them doesn't overlap. Adjust both upper bounds to be valid for
1129 the smaller size (i.e., at most MAXSIZE - SIZE). */
1131 if (maxsize < acs.dstoff[1] + acs.dstsiz[0])
1132 acs.dstoff[1] = maxsize - acs.dstsiz[0];
1134 if (maxsize < acs.srcoff[1] + acs.srcsiz[0])
1135 acs.srcoff[1] = maxsize - acs.srcsiz[0];
1137 /* Check to see if there's enough space for both accesses without
1138 overlap. Determine the optimistic (maximum) amount of available
1139 space. */
1140 offset_int space;
1141 if (acs.dstoff[0] <= acs.srcoff[0])
1143 if (acs.dstoff[1] < acs.srcoff[1])
1144 space = acs.srcoff[1] + acs.srcsiz[0] - acs.dstoff[0];
1145 else
1146 space = acs.dstoff[1] + acs.dstsiz[0] - acs.srcoff[0];
1148 else
1149 space = acs.dstoff[1] + acs.dstsiz[0] - acs.srcoff[0];
1151 /* Overlap is certain if the distance between the farthest offsets
1152 of the opposite accesses is less than the sum of the lower bounds
1153 of the sizes of the two accesses. */
1154 bool overlap_certain = space < acs.dstsiz[0] + acs.srcsiz[0];
1156 /* For a constant-offset, constant size access, consider the largest
1157 distance between the offset bounds and the lower bound of the access
1158 size. If the overlap isn't certain return success. */
1159 if (!overlap_certain
1160 && acs.dstoff[0] == acs.dstoff[1]
1161 && acs.srcoff[0] == acs.srcoff[1]
1162 && acs.dstsiz[0] == acs.dstsiz[1]
1163 && acs.srcsiz[0] == acs.srcsiz[1])
1164 return false;
1166 /* Overlap is not certain but may be possible. */
1168 offset_int access_min = acs.dstsiz[0] + acs.srcsiz[0];
1170 /* Determine the conservative (minimum) amount of space. */
1171 space = wi::abs (acs.dstoff[0] - acs.srcoff[0]);
1172 offset_int d = wi::abs (acs.dstoff[0] - acs.srcoff[1]);
1173 if (d < space)
1174 space = d;
1175 d = wi::abs (acs.dstoff[1] - acs.srcoff[0]);
1176 if (d < space)
1177 space = d;
1179 /* For a strict test (used for strcpy and similar with unknown or
1180 variable bounds or sizes), consider the smallest distance between
1181 the offset bounds and either the upper bound of the access size
1182 if known, or the lower bound otherwise. */
1183 if (access_min <= space && (access_min != 0 || !strfunc_unknown_args))
1184 return false;
1186 /* When strcat overlap is certain it is always a single byte:
1187 the terminating NUL, regardless of offsets and sizes. When
1188 overlap is only possible its range is [0, 1]. */
1189 acs.ovlsiz[0] = dstref->sizrange[0] == dstref->sizrange[1] ? 1 : 0;
1190 acs.ovlsiz[1] = 1;
1192 offset_int endoff = dstref->offrange[0] + dstref->sizrange[0];
1193 if (endoff <= srcref->offrange[0])
1194 acs.ovloff[0] = wi::smin (maxobjsize, srcref->offrange[0]).to_shwi ();
1195 else
1196 acs.ovloff[0] = wi::smin (maxobjsize, endoff).to_shwi ();
1198 acs.sizrange[0] = wi::smax (wi::abs (endoff - srcref->offrange[0]) + 1,
1199 srcref->sizrange[0]).to_shwi ();
1200 if (dstref->offrange[0] == dstref->offrange[1])
1202 if (srcref->offrange[0] == srcref->offrange[1])
1203 acs.ovloff[1] = acs.ovloff[0];
1204 else
1205 acs.ovloff[1]
1206 = wi::smin (maxobjsize,
1207 srcref->offrange[1] + srcref->sizrange[1]).to_shwi ();
1209 else
1210 acs.ovloff[1]
1211 = wi::smin (maxobjsize,
1212 dstref->offrange[1] + dstref->sizrange[1]).to_shwi ();
1214 if (acs.sizrange[0] == 0)
1215 acs.sizrange[0] = 1;
1216 acs.sizrange[1] = wi::smax (acs.dstsiz[1], srcref->sizrange[1]).to_shwi ();
1217 return true;
1220 /* Return true if the strcpy-like access overlaps. */
1222 bool
1223 builtin_access::strcpy_overlap ()
1225 return generic_overlap ();
1229 /* Return true if DSTREF and SRCREF describe accesses that either overlap
1230 one another or that, in order not to overlap, would imply that the size
1231 of the referenced object(s) exceeds the maximum size of an object. Set
1232 Otherwise, if DSTREF and SRCREF do not definitely overlap (even though
1233 they may overlap in a way that's not apparent from the available data),
1234 return false. */
1236 bool
1237 builtin_access::overlap ()
1239 builtin_access &acs = *this;
1241 const offset_int maxobjsize = dstref->maxobjsize;
1243 acs.sizrange[0] = wi::smax (dstref->sizrange[0],
1244 srcref->sizrange[0]).to_shwi ();
1245 acs.sizrange[1] = wi::smax (dstref->sizrange[1],
1246 srcref->sizrange[1]).to_shwi ();
1248 /* Check to see if the two references refer to regions that are
1249 too large not to overlap in the address space (whose maximum
1250 size is PTRDIFF_MAX). */
1251 offset_int size = dstref->sizrange[0] + srcref->sizrange[0];
1252 if (maxobjsize < size)
1254 acs.ovloff[0] = (maxobjsize - dstref->sizrange[0]).to_shwi ();
1255 acs.ovlsiz[0] = (size - maxobjsize).to_shwi ();
1256 return true;
1259 /* If both base objects aren't known return the maximum possible
1260 offset that would make them not overlap. */
1261 if (!dstref->base || !srcref->base)
1262 return false;
1264 /* Set the access offsets. */
1265 acs.dstoff[0] = dstref->offrange[0];
1266 acs.dstoff[1] = dstref->offrange[1];
1268 /* If the base object is an array adjust the bounds of the offset
1269 to be non-negative and within the bounds of the array if possible. */
1270 if (dstref->base
1271 && TREE_CODE (TREE_TYPE (dstref->base)) == ARRAY_TYPE)
1273 if (acs.dstoff[0] < 0 && acs.dstoff[1] >= 0)
1274 acs.dstoff[0] = 0;
1276 if (acs.dstoff[1] < acs.dstoff[0])
1278 if (tree size = TYPE_SIZE_UNIT (TREE_TYPE (dstref->base)))
1279 acs.dstoff[1] = wi::umin (acs.dstoff[1], wi::to_offset (size));
1280 else
1281 acs.dstoff[1] = wi::umin (acs.dstoff[1], maxobjsize);
1285 acs.srcoff[0] = srcref->offrange[0];
1286 acs.srcoff[1] = srcref->offrange[1];
1288 if (srcref->base
1289 && TREE_CODE (TREE_TYPE (srcref->base)) == ARRAY_TYPE)
1291 if (acs.srcoff[0] < 0 && acs.srcoff[1] >= 0)
1292 acs.srcoff[0] = 0;
1294 if (tree size = TYPE_SIZE_UNIT (TREE_TYPE (srcref->base)))
1295 acs.srcoff[1] = wi::umin (acs.srcoff[1], wi::to_offset (size));
1296 else if (acs.srcoff[1] < acs.srcoff[0])
1297 acs.srcoff[1] = wi::umin (acs.srcoff[1], maxobjsize);
1300 /* When the upper bound of the offset is less than the lower bound
1301 the former is the result of a negative offset being represented
1302 as a large positive value or vice versa. The resulting range is
1303 a union of two subranges: [MIN, UB] and [LB, MAX]. Since such
1304 a union is not representable using the current data structure
1305 replace it with the full range of offsets. */
1306 if (acs.dstoff[1] < acs.dstoff[0])
1308 acs.dstoff[0] = -maxobjsize - 1;
1309 acs.dstoff[1] = maxobjsize;
1312 /* Validate the offset and size of each reference on its own first.
1313 This is independent of whether or not the base objects are the
1314 same. Normally, this would have already been detected and
1315 diagnosed by -Warray-bounds, unless it has been disabled. */
1316 offset_int maxoff = acs.dstoff[0] + dstref->sizrange[0];
1317 if (maxobjsize < maxoff)
1319 acs.ovlsiz[0] = (maxoff - maxobjsize).to_shwi ();
1320 acs.ovloff[0] = acs.dstoff[0].to_shwi () - acs.ovlsiz[0];
1321 return true;
1324 /* Repeat the same as above but for the source offsets. */
1325 if (acs.srcoff[1] < acs.srcoff[0])
1327 acs.srcoff[0] = -maxobjsize - 1;
1328 acs.srcoff[1] = maxobjsize;
1331 maxoff = acs.srcoff[0] + srcref->sizrange[0];
1332 if (maxobjsize < maxoff)
1334 acs.ovlsiz[0] = (maxoff - maxobjsize).to_shwi ();
1335 acs.ovlsiz[1] = (acs.srcoff[0] + srcref->sizrange[1]
1336 - maxobjsize).to_shwi ();
1337 acs.ovloff[0] = acs.srcoff[0].to_shwi () - acs.ovlsiz[0];
1338 return true;
1341 if (dstref->base != srcref->base)
1342 return false;
1344 acs.dstsiz[0] = dstref->sizrange[0];
1345 acs.dstsiz[1] = dstref->sizrange[1];
1347 acs.srcsiz[0] = srcref->sizrange[0];
1348 acs.srcsiz[1] = srcref->sizrange[1];
1350 /* Call the appropriate function to determine the overlap. */
1351 if ((this->*detect_overlap) ())
1353 if (!sizrange[1])
1355 /* Unless the access size range has already been set, do so here. */
1356 sizrange[0] = wi::smax (acs.dstsiz[0], srcref->sizrange[0]).to_shwi ();
1357 sizrange[1] = wi::smax (acs.dstsiz[1], srcref->sizrange[1]).to_shwi ();
1359 return true;
1362 return false;
1365 /* Attempt to detect and diagnose an overlapping copy in a call expression
1366 EXPR involving an an access ACS to a built-in memory or string function.
1367 Return true when one has been detected, false otherwise. */
1369 static bool
1370 maybe_diag_overlap (location_t loc, gimple *call, builtin_access &acs)
1372 if (!acs.overlap ())
1373 return false;
1375 if (gimple_no_warning_p (call))
1376 return true;
1378 /* For convenience. */
1379 const builtin_memref &dstref = *acs.dstref;
1380 const builtin_memref &srcref = *acs.srcref;
1382 /* Determine the range of offsets and sizes of the overlap if it
1383 exists and issue diagnostics. */
1384 HOST_WIDE_INT *ovloff = acs.ovloff;
1385 HOST_WIDE_INT *ovlsiz = acs.ovlsiz;
1386 HOST_WIDE_INT *sizrange = acs.sizrange;
1388 tree func = gimple_call_fndecl (call);
1390 /* To avoid a combinatorial explosion of diagnostics format the offsets
1391 or their ranges as strings and use them in the warning calls below. */
1392 char offstr[3][64];
1394 if (dstref.offrange[0] == dstref.offrange[1]
1395 || dstref.offrange[1] > HOST_WIDE_INT_MAX)
1396 sprintf (offstr[0], HOST_WIDE_INT_PRINT_DEC,
1397 dstref.offrange[0].to_shwi ());
1398 else
1399 sprintf (offstr[0],
1400 "[" HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC "]",
1401 dstref.offrange[0].to_shwi (),
1402 dstref.offrange[1].to_shwi ());
1404 if (srcref.offrange[0] == srcref.offrange[1]
1405 || srcref.offrange[1] > HOST_WIDE_INT_MAX)
1406 sprintf (offstr[1],
1407 HOST_WIDE_INT_PRINT_DEC,
1408 srcref.offrange[0].to_shwi ());
1409 else
1410 sprintf (offstr[1],
1411 "[" HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC "]",
1412 srcref.offrange[0].to_shwi (),
1413 srcref.offrange[1].to_shwi ());
1415 if (ovloff[0] == ovloff[1] || !ovloff[1])
1416 sprintf (offstr[2], HOST_WIDE_INT_PRINT_DEC, ovloff[0]);
1417 else
1418 sprintf (offstr[2],
1419 "[" HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC "]",
1420 ovloff[0], ovloff[1]);
1422 const offset_int maxobjsize = dstref.maxobjsize;
1423 bool must_overlap = ovlsiz[0] > 0;
1425 if (ovlsiz[1] == 0)
1426 ovlsiz[1] = ovlsiz[0];
1428 if (must_overlap)
1430 /* Issue definitive "overlaps" diagnostic in this block. */
1432 if (sizrange[0] == sizrange[1])
1434 if (ovlsiz[0] == ovlsiz[1])
1435 warning_at (loc, OPT_Wrestrict,
1436 sizrange[0] == 1
1437 ? (ovlsiz[0] == 1
1438 ? G_("%G%qD accessing %wu byte at offsets %s "
1439 "and %s overlaps %wu byte at offset %s")
1440 : G_("%G%qD accessing %wu byte at offsets %s "
1441 "and %s overlaps %wu bytes at offset "
1442 "%s"))
1443 : (ovlsiz[0] == 1
1444 ? G_("%G%qD accessing %wu bytes at offsets %s "
1445 "and %s overlaps %wu byte at offset %s")
1446 : G_("%G%qD accessing %wu bytes at offsets %s "
1447 "and %s overlaps %wu bytes at offset "
1448 "%s")),
1449 call, func, sizrange[0],
1450 offstr[0], offstr[1], ovlsiz[0], offstr[2]);
1451 else if (ovlsiz[1] >= 0 && ovlsiz[1] < maxobjsize.to_shwi ())
1452 warning_n (loc, OPT_Wrestrict, sizrange[0],
1453 "%G%qD accessing %wu byte at offsets %s "
1454 "and %s overlaps between %wu and %wu bytes "
1455 "at offset %s",
1456 "%G%qD accessing %wu bytes at offsets %s "
1457 "and %s overlaps between %wu and %wu bytes "
1458 "at offset %s",
1459 call, func, sizrange[0], offstr[0], offstr[1],
1460 ovlsiz[0], ovlsiz[1], offstr[2]);
1461 else
1462 warning_n (loc, OPT_Wrestrict, sizrange[0],
1463 "%G%qD accessing %wu byte at offsets %s and "
1464 "%s overlaps %wu or more bytes at offset %s",
1465 "%G%qD accessing %wu bytes at offsets %s and "
1466 "%s overlaps %wu or more bytes at offset %s",
1467 call, func, sizrange[0],
1468 offstr[0], offstr[1], ovlsiz[0], offstr[2]);
1469 return true;
1472 if (sizrange[1] >= 0 && sizrange[1] < maxobjsize.to_shwi ())
1474 if (ovlsiz[0] == ovlsiz[1])
1475 warning_n (loc, OPT_Wrestrict, ovlsiz[0],
1476 "%G%qD accessing between %wu and %wu bytes "
1477 "at offsets %s and %s overlaps %wu byte at "
1478 "offset %s",
1479 "%G%qD accessing between %wu and %wu bytes "
1480 "at offsets %s and %s overlaps %wu bytes "
1481 "at offset %s",
1482 call, func, sizrange[0], sizrange[1],
1483 offstr[0], offstr[1], ovlsiz[0], offstr[2]);
1484 else if (ovlsiz[1] >= 0 && ovlsiz[1] < maxobjsize.to_shwi ())
1485 warning_at (loc, OPT_Wrestrict,
1486 "%G%qD accessing between %wu and %wu bytes at "
1487 "offsets %s and %s overlaps between %wu and %wu "
1488 "bytes at offset %s",
1489 call, func, sizrange[0], sizrange[1],
1490 offstr[0], offstr[1], ovlsiz[0], ovlsiz[1],
1491 offstr[2]);
1492 else
1493 warning_at (loc, OPT_Wrestrict,
1494 "%G%qD accessing between %wu and %wu bytes at "
1495 "offsets %s and %s overlaps %wu or more bytes "
1496 "at offset %s",
1497 call, func, sizrange[0], sizrange[1],
1498 offstr[0], offstr[1], ovlsiz[0], offstr[2]);
1499 return true;
1502 if (ovlsiz[0] != ovlsiz[1])
1503 ovlsiz[1] = maxobjsize.to_shwi ();
1505 if (ovlsiz[0] == ovlsiz[1])
1506 warning_n (loc, OPT_Wrestrict, ovlsiz[0],
1507 "%G%qD accessing %wu or more bytes at offsets "
1508 "%s and %s overlaps %wu byte at offset %s",
1509 "%G%qD accessing %wu or more bytes at offsets "
1510 "%s and %s overlaps %wu bytes at offset %s",
1511 call, func, sizrange[0], offstr[0], offstr[1],
1512 ovlsiz[0], offstr[2]);
1513 else if (ovlsiz[1] >= 0 && ovlsiz[1] < maxobjsize.to_shwi ())
1514 warning_at (loc, OPT_Wrestrict,
1515 "%G%qD accessing %wu or more bytes at offsets %s "
1516 "and %s overlaps between %wu and %wu bytes "
1517 "at offset %s",
1518 call, func, sizrange[0], offstr[0], offstr[1],
1519 ovlsiz[0], ovlsiz[1], offstr[2]);
1520 else
1521 warning_at (loc, OPT_Wrestrict,
1522 "%G%qD accessing %wu or more bytes at offsets %s "
1523 "and %s overlaps %wu or more bytes at offset %s",
1524 call, func, sizrange[0], offstr[0], offstr[1],
1525 ovlsiz[0], offstr[2]);
1526 return true;
1529 /* Use more concise wording when one of the offsets is unbounded
1530 to avoid confusing the user with large and mostly meaningless
1531 numbers. */
1532 bool open_range;
1533 if (DECL_P (dstref.base) && TREE_CODE (TREE_TYPE (dstref.base)) == ARRAY_TYPE)
1534 open_range = ((dstref.offrange[0] == 0
1535 && dstref.offrange[1] == maxobjsize)
1536 || (srcref.offrange[0] == 0
1537 && srcref.offrange[1] == maxobjsize));
1538 else
1539 open_range = ((dstref.offrange[0] == -maxobjsize - 1
1540 && dstref.offrange[1] == maxobjsize)
1541 || (srcref.offrange[0] == -maxobjsize - 1
1542 && srcref.offrange[1] == maxobjsize));
1544 if (sizrange[0] == sizrange[1] || sizrange[1] == 1)
1546 if (ovlsiz[1] == 1)
1548 if (open_range)
1549 warning_n (loc, OPT_Wrestrict, sizrange[1],
1550 "%G%qD accessing %wu byte may overlap "
1551 "%wu byte",
1552 "%G%qD accessing %wu bytes may overlap "
1553 "%wu byte",
1554 call, func, sizrange[1], ovlsiz[1]);
1555 else
1556 warning_n (loc, OPT_Wrestrict, sizrange[1],
1557 "%G%qD accessing %wu byte at offsets %s "
1558 "and %s may overlap %wu byte at offset %s",
1559 "%G%qD accessing %wu bytes at offsets %s "
1560 "and %s may overlap %wu byte at offset %s",
1561 call, func, sizrange[1], offstr[0], offstr[1],
1562 ovlsiz[1], offstr[2]);
1563 return true;
1566 if (open_range)
1567 warning_n (loc, OPT_Wrestrict, sizrange[1],
1568 "%G%qD accessing %wu byte may overlap "
1569 "up to %wu bytes",
1570 "%G%qD accessing %wu bytes may overlap "
1571 "up to %wu bytes",
1572 call, func, sizrange[1], ovlsiz[1]);
1573 else
1574 warning_n (loc, OPT_Wrestrict, sizrange[1],
1575 "%G%qD accessing %wu byte at offsets %s and "
1576 "%s may overlap up to %wu bytes at offset %s",
1577 "%G%qD accessing %wu bytes at offsets %s and "
1578 "%s may overlap up to %wu bytes at offset %s",
1579 call, func, sizrange[1], offstr[0], offstr[1],
1580 ovlsiz[1], offstr[2]);
1581 return true;
1584 if (sizrange[1] >= 0 && sizrange[1] < maxobjsize.to_shwi ())
1586 if (open_range)
1587 warning_n (loc, OPT_Wrestrict, ovlsiz[1],
1588 "%G%qD accessing between %wu and %wu bytes "
1589 "may overlap %wu byte",
1590 "%G%qD accessing between %wu and %wu bytes "
1591 "may overlap up to %wu bytes",
1592 call, func, sizrange[0], sizrange[1], ovlsiz[1]);
1593 else
1594 warning_n (loc, OPT_Wrestrict, ovlsiz[1],
1595 "%G%qD accessing between %wu and %wu bytes "
1596 "at offsets %s and %s may overlap %wu byte "
1597 "at offset %s",
1598 "%G%qD accessing between %wu and %wu bytes "
1599 "at offsets %s and %s may overlap up to %wu "
1600 "bytes at offset %s",
1601 call, func, sizrange[0], sizrange[1],
1602 offstr[0], offstr[1], ovlsiz[1], offstr[2]);
1603 return true;
1606 warning_n (loc, OPT_Wrestrict, ovlsiz[1],
1607 "%G%qD accessing %wu or more bytes at offsets %s "
1608 "and %s may overlap %wu byte at offset %s",
1609 "%G%qD accessing %wu or more bytes at offsets %s "
1610 "and %s may overlap up to %wu bytes at offset %s",
1611 call, func, sizrange[0], offstr[0], offstr[1],
1612 ovlsiz[1], offstr[2]);
1614 return true;
1617 /* Validate REF size and offsets in an expression passed as an argument
1618 to a CALL to a built-in function FUNC to make sure they are within
1619 the bounds of the referenced object if its size is known, or
1620 PTRDIFF_MAX otherwise. DO_WARN is true when a diagnostic should
1621 be issued, false otherwise.
1622 Both initial values of the offsets and their final value computed
1623 by the function by incrementing the initial value by the size are
1624 validated. Return true if the offsets are not valid and a diagnostic
1625 has been issued, or would have been issued if DO_WARN had been true. */
1627 static bool
1628 maybe_diag_access_bounds (location_t loc, gimple *call, tree func, int strict,
1629 const builtin_memref &ref, bool do_warn)
1631 const offset_int maxobjsize = ref.maxobjsize;
1633 /* Check for excessive size first and regardless of warning options
1634 since the result is used to make codegen decisions. */
1635 if (ref.sizrange[0] > maxobjsize)
1637 /* Return true without issuing a warning. */
1638 if (!do_warn)
1639 return true;
1641 if (ref.ref && TREE_NO_WARNING (ref.ref))
1642 return false;
1644 if (warn_stringop_overflow)
1646 if (EXPR_HAS_LOCATION (ref.ptr))
1647 loc = EXPR_LOCATION (ref.ptr);
1649 loc = expansion_point_location_if_in_system_header (loc);
1651 if (ref.sizrange[0] == ref.sizrange[1])
1652 return warning_at (loc, OPT_Wstringop_overflow_,
1653 "%G%qD specified bound %wu "
1654 "exceeds maximum object size %wu",
1655 call, func, ref.sizrange[0].to_uhwi (),
1656 maxobjsize.to_uhwi ());
1658 return warning_at (loc, OPT_Wstringop_overflow_,
1659 "%G%qD specified bound between %wu and %wu "
1660 "exceeds maximum object size %wu",
1661 call, func, ref.sizrange[0].to_uhwi (),
1662 ref.sizrange[1].to_uhwi (),
1663 maxobjsize.to_uhwi ());
1667 /* Check for out-bounds pointers regardless of warning options since
1668 the result is used to make codegen decisions. */
1669 offset_int ooboff[] = { ref.offrange[0], ref.offrange[1] };
1670 tree oobref = ref.offset_out_of_bounds (strict, ooboff);
1671 if (!oobref)
1672 return false;
1674 /* Return true without issuing a warning. */
1675 if (!do_warn)
1676 return true;
1678 if (!warn_array_bounds)
1679 return false;
1681 if (TREE_NO_WARNING (ref.ptr)
1682 || (ref.ref && TREE_NO_WARNING (ref.ref)))
1683 return false;
1685 if (EXPR_HAS_LOCATION (ref.ptr))
1686 loc = EXPR_LOCATION (ref.ptr);
1688 loc = expansion_point_location_if_in_system_header (loc);
1690 char rangestr[2][64];
1691 if (ooboff[0] == ooboff[1]
1692 || (ooboff[0] != ref.offrange[0]
1693 && ooboff[0].to_shwi () >= ooboff[1].to_shwi ()))
1694 sprintf (rangestr[0], "%lli", (long long) ooboff[0].to_shwi ());
1695 else
1696 sprintf (rangestr[0], "[%lli, %lli]",
1697 (long long) ooboff[0].to_shwi (),
1698 (long long) ooboff[1].to_shwi ());
1700 bool warned = false;
1702 if (oobref == error_mark_node)
1704 if (ref.sizrange[0] == ref.sizrange[1])
1705 sprintf (rangestr[1], "%llu",
1706 (unsigned long long) ref.sizrange[0].to_shwi ());
1707 else
1708 sprintf (rangestr[1], "[%lli, %lli]",
1709 (unsigned long long) ref.sizrange[0].to_uhwi (),
1710 (unsigned long long) ref.sizrange[1].to_uhwi ());
1712 tree type;
1714 if (DECL_P (ref.base)
1715 && TREE_CODE (type = TREE_TYPE (ref.base)) == ARRAY_TYPE)
1717 auto_diagnostic_group d;
1718 if (warning_at (loc, OPT_Warray_bounds,
1719 "%G%qD pointer overflow between offset %s "
1720 "and size %s accessing array %qD with type %qT",
1721 call, func, rangestr[0], rangestr[1], ref.base, type))
1723 inform (DECL_SOURCE_LOCATION (ref.base),
1724 "array %qD declared here", ref.base);
1725 warned = true;
1727 else
1728 warned = warning_at (loc, OPT_Warray_bounds,
1729 "%G%qD pointer overflow between offset %s "
1730 "and size %s",
1731 call, func, rangestr[0], rangestr[1]);
1733 else
1734 warned = warning_at (loc, OPT_Warray_bounds,
1735 "%G%qD pointer overflow between offset %s "
1736 "and size %s",
1737 call, func, rangestr[0], rangestr[1]);
1739 else if (oobref == ref.base)
1741 /* True when the offset formed by an access to the reference
1742 is out of bounds, rather than the initial offset wich is
1743 in bounds. This implies access past the end. */
1744 bool form = ooboff[0] != ref.offrange[0];
1746 if (DECL_P (ref.base))
1748 auto_diagnostic_group d;
1749 if ((ref.basesize < maxobjsize
1750 && warning_at (loc, OPT_Warray_bounds,
1751 form
1752 ? G_("%G%qD forming offset %s is out of "
1753 "the bounds [0, %wu] of object %qD with "
1754 "type %qT")
1755 : G_("%G%qD offset %s is out of the bounds "
1756 "[0, %wu] of object %qD with type %qT"),
1757 call, func, rangestr[0], ref.basesize.to_uhwi (),
1758 ref.base, TREE_TYPE (ref.base)))
1759 || warning_at (loc, OPT_Warray_bounds,
1760 form
1761 ? G_("%G%qD forming offset %s is out of "
1762 "the bounds of object %qD with type %qT")
1763 : G_("%G%qD offset %s is out of the bounds "
1764 "of object %qD with type %qT"),
1765 call, func, rangestr[0],
1766 ref.base, TREE_TYPE (ref.base)))
1768 inform (DECL_SOURCE_LOCATION (ref.base),
1769 "%qD declared here", ref.base);
1770 warned = true;
1773 else if (ref.basesize < maxobjsize)
1774 warned = warning_at (loc, OPT_Warray_bounds,
1775 form
1776 ? G_("%G%qD forming offset %s is out "
1777 "of the bounds [0, %wu]")
1778 : G_("%G%qD offset %s is out "
1779 "of the bounds [0, %wu]"),
1780 call, func, rangestr[0], ref.basesize.to_uhwi ());
1781 else
1782 warned = warning_at (loc, OPT_Warray_bounds,
1783 form
1784 ? G_("%G%qD forming offset %s is out of bounds")
1785 : G_("%G%qD offset %s is out of bounds"),
1786 call, func, rangestr[0]);
1788 else if (TREE_CODE (ref.ref) == MEM_REF)
1790 tree type = TREE_TYPE (TREE_OPERAND (ref.ref, 0));
1791 if (POINTER_TYPE_P (type))
1792 type = TREE_TYPE (type);
1793 type = TYPE_MAIN_VARIANT (type);
1795 warned = warning_at (loc, OPT_Warray_bounds,
1796 "%G%qD offset %s from the object at %qE is out "
1797 "of the bounds of %qT",
1798 call, func, rangestr[0], ref.base, type);
1800 else
1802 tree type = TYPE_MAIN_VARIANT (TREE_TYPE (ref.ref));
1804 warned = warning_at (loc, OPT_Warray_bounds,
1805 "%G%qD offset %s from the object at %qE is out "
1806 "of the bounds of referenced subobject %qD with "
1807 "type %qT at offset %wu",
1808 call, func, rangestr[0], ref.base,
1809 TREE_OPERAND (ref.ref, 1), type,
1810 ref.refoff.to_uhwi ());
1813 return warned;
1816 /* Check a CALL statement for restrict-violations and issue warnings
1817 if/when appropriate. */
1819 void
1820 wrestrict_dom_walker::check_call (gimple *call)
1822 /* Avoid checking the call if it has already been diagnosed for
1823 some reason. */
1824 if (gimple_no_warning_p (call))
1825 return;
1827 tree func = gimple_call_fndecl (call);
1828 if (!func || !fndecl_built_in_p (func, BUILT_IN_NORMAL))
1829 return;
1831 /* Argument number to extract from the call (depends on the built-in
1832 and its kind). */
1833 unsigned dst_idx = -1;
1834 unsigned src_idx = -1;
1835 unsigned bnd_idx = -1;
1837 /* Is this CALL to a string function (as opposed to one to a raw
1838 memory function). */
1839 bool strfun = true;
1841 switch (DECL_FUNCTION_CODE (func))
1843 case BUILT_IN_MEMCPY:
1844 case BUILT_IN_MEMCPY_CHK:
1845 case BUILT_IN_MEMPCPY:
1846 case BUILT_IN_MEMPCPY_CHK:
1847 case BUILT_IN_MEMMOVE:
1848 case BUILT_IN_MEMMOVE_CHK:
1849 strfun = false;
1850 /* Fall through. */
1852 case BUILT_IN_STPNCPY:
1853 case BUILT_IN_STPNCPY_CHK:
1854 case BUILT_IN_STRNCAT:
1855 case BUILT_IN_STRNCAT_CHK:
1856 case BUILT_IN_STRNCPY:
1857 case BUILT_IN_STRNCPY_CHK:
1858 dst_idx = 0;
1859 src_idx = 1;
1860 bnd_idx = 2;
1861 break;
1863 case BUILT_IN_MEMSET:
1864 case BUILT_IN_MEMSET_CHK:
1865 dst_idx = 0;
1866 bnd_idx = 2;
1867 break;
1869 case BUILT_IN_STPCPY:
1870 case BUILT_IN_STPCPY_CHK:
1871 case BUILT_IN_STRCPY:
1872 case BUILT_IN_STRCPY_CHK:
1873 case BUILT_IN_STRCAT:
1874 case BUILT_IN_STRCAT_CHK:
1875 dst_idx = 0;
1876 src_idx = 1;
1877 break;
1879 default:
1880 /* Handle other string functions here whose access may need
1881 to be validated for in-bounds offsets and non-overlapping
1882 copies. */
1883 return;
1886 unsigned nargs = gimple_call_num_args (call);
1888 tree dst = dst_idx < nargs ? gimple_call_arg (call, dst_idx) : NULL_TREE;
1889 tree src = src_idx < nargs ? gimple_call_arg (call, src_idx) : NULL_TREE;
1890 tree dstwr = bnd_idx < nargs ? gimple_call_arg (call, bnd_idx) : NULL_TREE;
1892 /* For string functions with an unspecified or unknown bound,
1893 assume the size of the access is one. */
1894 if (!dstwr && strfun)
1895 dstwr = size_one_node;
1897 /* DST and SRC can be null for a call with an insufficient number
1898 of arguments to a built-in function declared without a protype. */
1899 if (!dst || (src_idx < nargs && !src))
1900 return;
1902 /* DST, SRC, or DSTWR can also have the wrong type in a call to
1903 a function declared without a prototype. Avoid checking such
1904 invalid calls. */
1905 if (TREE_CODE (TREE_TYPE (dst)) != POINTER_TYPE
1906 || (src && TREE_CODE (TREE_TYPE (src)) != POINTER_TYPE)
1907 || (dstwr && !INTEGRAL_TYPE_P (TREE_TYPE (dstwr))))
1908 return;
1910 if (!check_bounds_or_overlap (call, dst, src, dstwr, NULL_TREE))
1911 return;
1913 /* Avoid diagnosing the call again. */
1914 gimple_set_no_warning (call, true);
1917 } /* anonymous namespace */
1919 /* Attempt to detect and diagnose invalid offset bounds and (except for
1920 memmove) overlapping copy in a call expression EXPR from SRC to DST
1921 and DSTSIZE and SRCSIZE bytes, respectively. Both DSTSIZE and
1922 SRCSIZE may be NULL. DO_WARN is false to detect either problem
1923 without issue a warning. Return the OPT_Wxxx constant corresponding
1924 to the warning if one has been detected and zero otherwise. */
1927 check_bounds_or_overlap (gimple *call, tree dst, tree src, tree dstsize,
1928 tree srcsize, bool bounds_only /* = false */,
1929 bool do_warn /* = true */)
1931 location_t loc = gimple_nonartificial_location (call);
1932 loc = expansion_point_location_if_in_system_header (loc);
1934 tree func = gimple_call_fndecl (call);
1936 builtin_memref dstref (dst, dstsize);
1937 builtin_memref srcref (src, srcsize);
1939 builtin_access acs (call, dstref, srcref);
1941 /* Set STRICT to the value of the -Warray-bounds=N argument for
1942 string functions or when N > 1. */
1943 int strict = (acs.strict () || warn_array_bounds > 1 ? warn_array_bounds : 0);
1945 /* Validate offsets first to make sure they are within the bounds
1946 of the destination object if its size is known, or PTRDIFF_MAX
1947 otherwise. */
1948 if (maybe_diag_access_bounds (loc, call, func, strict, dstref, do_warn)
1949 || maybe_diag_access_bounds (loc, call, func, strict, srcref, do_warn))
1951 if (do_warn)
1952 gimple_set_no_warning (call, true);
1953 return OPT_Warray_bounds;
1956 if (!warn_restrict || bounds_only || !src)
1957 return 0;
1959 if (!bounds_only)
1961 switch (DECL_FUNCTION_CODE (func))
1963 case BUILT_IN_MEMMOVE:
1964 case BUILT_IN_MEMMOVE_CHK:
1965 case BUILT_IN_MEMSET:
1966 case BUILT_IN_MEMSET_CHK:
1967 return 0;
1968 default:
1969 break;
1973 if (operand_equal_p (dst, src, 0))
1975 /* Issue -Wrestrict unless the pointers are null (those do
1976 not point to objects and so do not indicate an overlap;
1977 such calls could be the result of sanitization and jump
1978 threading). */
1979 if (!integer_zerop (dst) && !gimple_no_warning_p (call))
1981 warning_at (loc, OPT_Wrestrict,
1982 "%G%qD source argument is the same as destination",
1983 call, func);
1984 gimple_set_no_warning (call, true);
1985 return OPT_Wrestrict;
1988 return 0;
1991 /* Return false when overlap has been detected. */
1992 if (maybe_diag_overlap (loc, call, acs))
1994 gimple_set_no_warning (call, true);
1995 return OPT_Wrestrict;
1998 return 0;
2001 gimple_opt_pass *
2002 make_pass_warn_restrict (gcc::context *ctxt)
2004 return new pass_wrestrict (ctxt);