diff options
| author | Richard Smith <richard-llvm@metafoo.co.uk> | 2013-09-10 21:34:14 +0000 |
|---|---|---|
| committer | Richard Smith <richard-llvm@metafoo.co.uk> | 2013-09-10 21:34:14 +0000 |
| commit | 84c6b3d293d91e9d8403108d5069f7b6e6a57afa (patch) | |
| tree | d9aef84d54689cd71d22630bb269ad86066e0dd2 /clang/lib | |
| parent | 754a3ead62b5a5bf685d23ab914148c55307106c (diff) | |
| download | bcm5719-llvm-84c6b3d293d91e9d8403108d5069f7b6e6a57afa.tar.gz bcm5719-llvm-84c6b3d293d91e9d8403108d5069f7b6e6a57afa.zip | |
PR5683: Issue a warning when subtracting pointers to types of zero size, and
treat such subtractions as being non-constant. Patch by Serge Pavlov! With a
few tweaks by me.
llvm-svn: 190439
Diffstat (limited to 'clang/lib')
| -rw-r--r-- | clang/lib/AST/ExprConstant.cpp | 9 | ||||
| -rw-r--r-- | clang/lib/Sema/SemaExpr.cpp | 12 |
2 files changed, 21 insertions, 0 deletions
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp index b6602145e28..218ce8101b5 100644 --- a/clang/lib/AST/ExprConstant.cpp +++ b/clang/lib/AST/ExprConstant.cpp @@ -6570,6 +6570,15 @@ bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) { if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize)) return false; + // As an extension, a type may have zero size (empty struct or union in + // C, array of zero length). Pointer subtraction in such cases has + // undefined behavior, so is not constant. + if (ElementSize.isZero()) { + Info.Diag(E, diag::note_constexpr_pointer_subtraction_zero_size) + << ElementType; + return false; + } + // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime, // and produce incorrect results when it overflows. Such behavior // appears to be non-conforming, but is common, so perhaps we should diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp index da834cc2519..918201c44cf 100644 --- a/clang/lib/Sema/SemaExpr.cpp +++ b/clang/lib/Sema/SemaExpr.cpp @@ -7041,6 +7041,18 @@ QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, LHS.get(), RHS.get())) return QualType(); + // The pointee type may have zero size. As an extension, a structure or + // union may have zero size or an array may have zero length. In this + // case subtraction does not make sense. + if (!rpointee->isVoidType() && !rpointee->isFunctionType()) { + CharUnits ElementSize = Context.getTypeSizeInChars(rpointee); + if (ElementSize.isZero()) { + Diag(Loc,diag::warn_sub_ptr_zero_size_types) + << rpointee.getUnqualifiedType() + << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); + } + } + if (CompLHSTy) *CompLHSTy = LHS.get()->getType(); return Context.getPointerDiffType(); } |

