Skip to content

Commit

Permalink
Only issue warning for subtraction involving null pointers on live co…
Browse files Browse the repository at this point in the history
…de paths

Summary:
Change the warning produced for subtraction from (or with) a null pointer
to only be produced when the code path is live.
#54570

Author: Jamie Schmeiser <schmeise@ca.ibm.com>
Reviewed By: anarazel (Andres Freund)
Differential Revision: https://reviews.llvm.org/D126816
  • Loading branch information
jamieschmeiser committed Jun 3, 2022
1 parent 5c902af commit efbf013
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 2 deletions.
6 changes: 4 additions & 2 deletions clang/lib/Sema/SemaExpr.cpp
Expand Up @@ -10845,8 +10845,10 @@ static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,
if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc))
return;

S.Diag(Loc, diag::warn_pointer_sub_null_ptr)
<< S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
S.DiagRuntimeBehavior(Loc, Pointer,
S.PDiag(diag::warn_pointer_sub_null_ptr)
<< S.getLangOpts().CPlusPlus
<< Pointer->getSourceRange());
}

/// Diagnose invalid arithmetic on two function pointers.
Expand Down
10 changes: 10 additions & 0 deletions clang/test/Sema/pointer-subtraction.c
Expand Up @@ -11,6 +11,16 @@ void a(void) {
f = (char *)(f - (char *)0); // expected-warning {{performing pointer subtraction with a null pointer has undefined behavior}}
f = (char *)((char *)0 - (char *)0); // expected-warning {{performing pointer subtraction with a null pointer has undefined behavior}} expected-warning {{performing pointer subtraction with a null pointer has undefined behavior}}

if (1)
f = (char *)((char *)0 - f); // expected-warning {{performing pointer subtraction with a null pointer has undefined behavior}}
else
f = (char *)((char *)0 - f);

if (0)
f = (char *)((char *)0 - f);
else
f = (char *)((char *)0 - f); // expected-warning {{performing pointer subtraction with a null pointer has undefined behavior}}

#ifndef SYSTEM_WARNINGS
SYSTEM_MACRO(f);
#else
Expand Down
10 changes: 10 additions & 0 deletions clang/test/Sema/pointer-subtraction.cpp
Expand Up @@ -11,6 +11,16 @@ void a() {
f = (char *)(f - (char *)0); // expected-warning {{performing pointer subtraction with a null pointer may have undefined behavior}}
f = (char *)((char *)0 - (char *)0); // valid in C++

if (1)
f = (char *)((char *)0 - f); // expected-warning {{performing pointer subtraction with a null pointer may have undefined behavior}}
else
f = (char *)((char *)0 - f);

if (0)
f = (char *)((char *)0 - f);
else
f = (char *)((char *)0 - f); // expected-warning {{performing pointer subtraction with a null pointer may have undefined behavior}}

#ifndef SYSTEM_WARNINGS
SYSTEM_MACRO(f);
#else
Expand Down

0 comments on commit efbf013

Please sign in to comment.