Skip to content

Commit 06250aa

Browse files
committed
implement wraps attribute
Signed-off-by: Justin Stitt <[email protected]>
1 parent d21e731 commit 06250aa

20 files changed

+375
-26
lines changed

clang/docs/ReleaseNotes.rst

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,16 @@ Attribute Changes in Clang
230230
instantiation by accidentally allowing it in C++ in some circumstances.
231231
(#GH106864)
232232

233+
- Introduced ``__attribute((wraps))__`` which can be added to type or variable
234+
declarations. Using an attributed type or variable in an arithmetic
235+
expression will define the overflow behavior for that expression as having
236+
two's complement wrap-around. These expressions cannot trigger integer
237+
overflow warnings or sanitizer warnings. They also cannot be optimized away
238+
by some eager UB optimizations.
239+
240+
This attribute is only valid for C, as there are built-in language
241+
alternatives for other languages.
242+
233243
Improvements to Clang's diagnostics
234244
-----------------------------------
235245

clang/include/clang/AST/Expr.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4095,6 +4095,9 @@ class BinaryOperator : public Expr {
40954095
return getFPFeaturesInEffect(LO).getAllowFEnvAccess();
40964096
}
40974097

4098+
/// Does one of the subexpressions have the wraps attribute?
4099+
bool hasWrappingOperand(const ASTContext &Ctx) const;
4100+
40984101
protected:
40994102
BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs, Opcode opc,
41004103
QualType ResTy, ExprValueKind VK, ExprObjectKind OK,

clang/include/clang/AST/Type.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1454,6 +1454,8 @@ class QualType {
14541454
return getQualifiers().hasStrongOrWeakObjCLifetime();
14551455
}
14561456

1457+
bool hasWrapsAttr() const;
1458+
14571459
// true when Type is objc's weak and weak is enabled but ARC isn't.
14581460
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const;
14591461

clang/include/clang/Basic/Attr.td

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4790,3 +4790,10 @@ def ClspvLibclcBuiltin: InheritableAttr {
47904790
let Documentation = [ClspvLibclcBuiltinDoc];
47914791
let SimpleHandler = 1;
47924792
}
4793+
4794+
def Wraps : DeclOrTypeAttr {
4795+
let Spellings = [Clang<"wraps">];
4796+
let Subjects = SubjectList<[Var, TypedefName, Field]>;
4797+
let Documentation = [WrapsDocs];
4798+
let LangOpts = [COnly];
4799+
}

clang/include/clang/Basic/AttrDocs.td

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8415,3 +8415,71 @@ of ``nonallocating`` by the compiler.
84158415
}];
84168416
}
84178417

8418+
def WrapsDocs : Documentation {
8419+
let Category = DocCatField;
8420+
let Content = [{
8421+
This attribute can be used with type or variable declarations to denote that
8422+
arithmetic containing these marked components have defined overflow behavior.
8423+
Specifically, the behavior is defined as being consistent with two's complement
8424+
wrap-around. For the purposes of sanitizers or warnings that concern themselves
8425+
with the definedness of integer arithmetic, they will cease to instrument or
8426+
warn about arithmetic that directly involves a "wrapping" component.
8427+
8428+
For example, ``-fsanitize=signed-integer-overflow`` or ``-Winteger-overflow``
8429+
will not warn about suspicious overflowing arithmetic -- assuming correct usage
8430+
of the wraps attribute.
8431+
8432+
This example shows some basic usage of ``__attribute__((wraps))`` on a type
8433+
definition when building with ``-fsanitize=signed-integer-overflow``
8434+
8435+
.. code-block:: c
8436+
8437+
typedef int __attribute__((wraps)) wrapping_int;
8438+
8439+
void foo() {
8440+
wrapping_int a = INT_MAX;
8441+
++a; // no sanitizer warning
8442+
}
8443+
8444+
int main() { foo(); }
8445+
8446+
In the following example, we use ``__attribute__((wraps))`` on a variable to
8447+
disable overflow instrumentation for arithmetic expressions it appears in. We
8448+
do so with a popular overflow-checking pattern which we might not want to trip
8449+
sanitizers (like ``-fsanitize=unsigned-integer-overflow``).
8450+
8451+
.. code-block:: c
8452+
8453+
void foo(int offset) {
8454+
unsigned int A __attribute__((wraps)) = UINT_MAX;
8455+
8456+
// check for overflow using a common pattern, however we may accidentally
8457+
// perform a real overflow thus triggering sanitizers to step in. Since "A"
8458+
// is "wrapping", we can avoid sanitizer warnings.
8459+
if (A + offset < A) {
8460+
// handle overflow manually
8461+
// ...
8462+
return;
8463+
}
8464+
8465+
// now, handle non-overflow case ...
8466+
}
8467+
8468+
The above example demonstrates some of the power and elegance this attribute
8469+
provides. We can use code patterns we are already familiar with (like ``if (x +
8470+
y < x)``) while gaining control over the overflow behavior on a case-by-case
8471+
basis.
8472+
8473+
When combined with ``-fwrapv``, this attribute can still be applied as normal
8474+
but has no function apart from annotating types and variables for readers. This
8475+
is because ``-fwrapv`` defines all arithmetic as being "wrapping", rendering
8476+
this attribute's efforts redundant.
8477+
8478+
When using this attribute without ``-fwrapv`` and without any sanitizers, it
8479+
still has an impact on the definedness of arithmetic expressions containing
8480+
wrapping components. Since the behavior of said expressions is now technically
8481+
defined, the compiler will forgo some eager optimizations that are used on
8482+
expressions containing UB.
8483+
}];
8484+
}
8485+

clang/include/clang/Basic/DiagnosticGroups.td

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1576,3 +1576,9 @@ def ExtractAPIMisuse : DiagGroup<"extractapi-misuse">;
15761576
// Warnings about using the non-standard extension having an explicit specialization
15771577
// with a storage class specifier.
15781578
def ExplicitSpecializationStorageClass : DiagGroup<"explicit-specialization-storage-class">;
1579+
1580+
// Warnings regarding the usage of __attribute__((wraps)) on non-integer types.
1581+
def UselessWrapsAttr : DiagGroup<"useless-wraps-attribute">;
1582+
1583+
// Warnings about the wraps attribute getting implicitly discarded
1584+
def ImpDiscardedWrapsAttr : DiagGroup<"implicitly-discarded-wraps-attribute">;

clang/include/clang/Basic/DiagnosticSemaKinds.td

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6633,6 +6633,13 @@ def warn_counted_by_attr_elt_type_unknown_size :
66336633
Warning<err_counted_by_attr_pointee_unknown_size.Summary>,
66346634
InGroup<BoundsSafetyCountedByEltTyUnknownSize>;
66356635

6636+
def warn_wraps_attr_var_decl_type_not_integer : Warning<
6637+
"using attribute 'wraps' with non-integer type '%0' has no function">,
6638+
InGroup<UselessWrapsAttr>;
6639+
def warn_wraps_attr_maybe_lost : Warning<
6640+
"'wraps' attribute may be implicitly discarded when converted to %0">,
6641+
InGroup<ImpDiscardedWrapsAttr>;
6642+
66366643
let CategoryName = "ARC Semantic Issue" in {
66376644

66386645
// ARC-mode diagnostics.

clang/lib/AST/Expr.cpp

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2237,6 +2237,11 @@ bool BinaryOperator::isNullPointerArithmeticExtension(ASTContext &Ctx,
22372237
return true;
22382238
}
22392239

2240+
bool BinaryOperator::hasWrappingOperand(const ASTContext &Ctx) const {
2241+
return getLHS()->getType().hasWrapsAttr() ||
2242+
getRHS()->getType().hasWrapsAttr();
2243+
}
2244+
22402245
SourceLocExpr::SourceLocExpr(const ASTContext &Ctx, SourceLocIdentKind Kind,
22412246
QualType ResultTy, SourceLocation BLoc,
22422247
SourceLocation RParenLoc,
@@ -4844,6 +4849,8 @@ BinaryOperator::BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs,
48444849
if (hasStoredFPFeatures())
48454850
setStoredFPFeatures(FPFeatures);
48464851
setDependence(computeDependence(this));
4852+
if (hasWrappingOperand(Ctx))
4853+
setType(Ctx.getAttributedType(attr::Wraps, getType(), getType()));
48474854
}
48484855

48494856
BinaryOperator::BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs,
@@ -4862,6 +4869,8 @@ BinaryOperator::BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs,
48624869
if (hasStoredFPFeatures())
48634870
setStoredFPFeatures(FPFeatures);
48644871
setDependence(computeDependence(this));
4872+
if (hasWrappingOperand(Ctx))
4873+
setType(Ctx.getAttributedType(attr::Wraps, getType(), getType()));
48654874
}
48664875

48674876
BinaryOperator *BinaryOperator::CreateEmpty(const ASTContext &C,

clang/lib/AST/ExprConstant.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2805,7 +2805,7 @@ static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
28052805
APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
28062806
Result = Value.trunc(LHS.getBitWidth());
28072807
if (Result.extend(BitWidth) != Value) {
2808-
if (Info.checkingForUndefinedBehavior())
2808+
if (Info.checkingForUndefinedBehavior() && !E->getType().hasWrapsAttr())
28092809
Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
28102810
diag::warn_integer_constant_overflow)
28112811
<< toString(Result, 10, Result.isSigned(), /*formatAsCLiteral=*/false,
@@ -14391,7 +14391,7 @@ bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
1439114391
if (!Result.isInt()) return Error(E);
1439214392
const APSInt &Value = Result.getInt();
1439314393
if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
14394-
if (Info.checkingForUndefinedBehavior())
14394+
if (Info.checkingForUndefinedBehavior() && !E->getType().hasWrapsAttr())
1439514395
Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1439614396
diag::warn_integer_constant_overflow)
1439714397
<< toString(Value, 10, Value.isSigned(), /*formatAsCLiteral=*/false,

clang/lib/AST/Type.cpp

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2850,6 +2850,10 @@ bool QualType::isWebAssemblyFuncrefType() const {
28502850
getAddressSpace() == LangAS::wasm_funcref;
28512851
}
28522852

2853+
bool QualType::hasWrapsAttr() const {
2854+
return !isNull() && getTypePtr()->hasAttr(attr::Wraps);
2855+
}
2856+
28532857
QualType::PrimitiveDefaultInitializeKind
28542858
QualType::isNonTrivialToPrimitiveDefaultInitialize() const {
28552859
if (const auto *RT =

clang/lib/AST/TypePrinter.cpp

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2019,6 +2019,9 @@ void TypePrinter::printAttributedAfter(const AttributedType *T,
20192019
case attr::AArch64SVEPcs: OS << "aarch64_sve_pcs"; break;
20202020
case attr::AMDGPUKernelCall: OS << "amdgpu_kernel"; break;
20212021
case attr::IntelOclBicc: OS << "inteloclbicc"; break;
2022+
case attr::Wraps:
2023+
OS << "wraps";
2024+
break;
20222025
case attr::PreserveMost:
20232026
OS << "preserve_most";
20242027
break;

clang/lib/CodeGen/CGExprScalar.cpp

Lines changed: 34 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,10 @@ struct BinOpInfo {
157157
}
158158
return false;
159159
}
160+
161+
/// Does the BinaryOperator have the wraps attribute?
162+
/// If so, we can elide overflow sanitizer checks.
163+
bool hasWrappingOperand() const { return E->getType().hasWrapsAttr(); }
160164
};
161165

162166
static bool MustVisitNullValue(const Expr *E) {
@@ -749,7 +753,8 @@ class ScalarExprEmitter
749753

750754
// Binary Operators.
751755
Value *EmitMul(const BinOpInfo &Ops) {
752-
if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
756+
if (Ops.Ty->isSignedIntegerOrEnumerationType() &&
757+
!Ops.hasWrappingOperand()) {
753758
switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
754759
case LangOptions::SOB_Defined:
755760
if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
@@ -785,7 +790,8 @@ class ScalarExprEmitter
785790

786791
if (Ops.Ty->isUnsignedIntegerType() &&
787792
CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
788-
!CanElideOverflowCheck(CGF.getContext(), Ops))
793+
!CanElideOverflowCheck(CGF.getContext(), Ops) &&
794+
!Ops.hasWrappingOperand())
789795
return EmitOverflowCheckedBinOp(Ops);
790796

791797
if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
@@ -1117,7 +1123,7 @@ void ScalarExprEmitter::EmitIntegerTruncationCheck(Value *Src, QualType SrcType,
11171123
// If the comparison result is 'i1 false', then the truncation was lossy.
11181124

11191125
// Do we care about this type of truncation?
1120-
if (!CGF.SanOpts.has(Check.second.second))
1126+
if (!CGF.SanOpts.has(Check.second.second) || DstType.hasWrapsAttr())
11211127
return;
11221128

11231129
llvm::Constant *StaticArgs[] = {
@@ -1350,6 +1356,14 @@ void CodeGenFunction::EmitBitfieldConversionCheck(Value *Src, QualType SrcType,
13501356
bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
13511357
bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
13521358

1359+
bool SrcWraps = SrcType.hasWrapsAttr();
1360+
bool DstWraps = DstType.hasWrapsAttr();
1361+
1362+
// The wraps attribute should silence any sanitizer warnings
1363+
// regarding truncation or overflow
1364+
if (SrcWraps || DstWraps)
1365+
return;
1366+
13531367
CodeGenFunction::SanitizerScope SanScope(this);
13541368

13551369
std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
@@ -2916,6 +2930,9 @@ ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
29162930
bool excludeOverflowPattern =
29172931
matchesPostDecrInWhile(E, isInc, isPre, CGF.getContext());
29182932

2933+
BinOpInfo Ops = createBinOpInfoFromIncDec(
2934+
E, value, isInc, E->getFPFeaturesInEffect(CGF.getLangOpts()));
2935+
29192936
if (CGF.getContext().isPromotableIntegerType(type)) {
29202937
promotedType = CGF.getContext().getPromotedIntegerType(type);
29212938
assert(promotedType != type && "Shouldn't promote to the same type.");
@@ -2972,11 +2989,12 @@ ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
29722989
// Note that signed integer inc/dec with width less than int can't
29732990
// overflow because of promotion rules; we're just eliding a few steps
29742991
// here.
2975-
} else if (E->canOverflow() && type->isSignedIntegerOrEnumerationType()) {
2992+
} else if (E->canOverflow() && type->isSignedIntegerOrEnumerationType() &&
2993+
!Ops.hasWrappingOperand()) {
29762994
value = EmitIncDecConsiderOverflowBehavior(E, value, isInc);
29772995
} else if (E->canOverflow() && type->isUnsignedIntegerType() &&
29782996
CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
2979-
!excludeOverflowPattern) {
2997+
!Ops.hasWrappingOperand() && !excludeOverflowPattern) {
29802998
value = EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec(
29812999
E, value, isInc, E->getFPFeaturesInEffect(CGF.getLangOpts())));
29823000
} else {
@@ -3765,7 +3783,8 @@ Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
37653783
if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) ||
37663784
CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) &&
37673785
Ops.Ty->isIntegerType() &&
3768-
(Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) {
3786+
(Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow()) &&
3787+
!Ops.hasWrappingOperand()) {
37693788
llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
37703789
EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
37713790
} else if (CGF.SanOpts.has(SanitizerKind::FloatDivideByZero) &&
@@ -3814,7 +3833,8 @@ Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
38143833
if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) ||
38153834
CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) &&
38163835
Ops.Ty->isIntegerType() &&
3817-
(Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) {
3836+
(Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow()) &&
3837+
!Ops.hasWrappingOperand()) {
38183838
CodeGenFunction::SanitizerScope SanScope(&CGF);
38193839
llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
38203840
EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
@@ -4179,7 +4199,7 @@ Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
41794199
op.RHS->getType()->isPointerTy())
41804200
return emitPointerArithmetic(CGF, op, CodeGenFunction::NotSubtraction);
41814201

4182-
if (op.Ty->isSignedIntegerOrEnumerationType()) {
4202+
if (op.Ty->isSignedIntegerOrEnumerationType() && !op.hasWrappingOperand()) {
41834203
switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
41844204
case LangOptions::SOB_Defined:
41854205
if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
@@ -4212,7 +4232,7 @@ Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
42124232

42134233
if (op.Ty->isUnsignedIntegerType() &&
42144234
CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
4215-
!CanElideOverflowCheck(CGF.getContext(), op))
4235+
!CanElideOverflowCheck(CGF.getContext(), op) && !op.hasWrappingOperand())
42164236
return EmitOverflowCheckedBinOp(op);
42174237

42184238
if (op.LHS->getType()->isFPOrFPVectorTy()) {
@@ -4335,7 +4355,7 @@ Value *ScalarExprEmitter::EmitFixedPointBinOp(const BinOpInfo &op) {
43354355
Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
43364356
// The LHS is always a pointer if either side is.
43374357
if (!op.LHS->getType()->isPointerTy()) {
4338-
if (op.Ty->isSignedIntegerOrEnumerationType()) {
4358+
if (op.Ty->isSignedIntegerOrEnumerationType() && !op.hasWrappingOperand()) {
43394359
switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
43404360
case LangOptions::SOB_Defined:
43414361
if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
@@ -4368,7 +4388,8 @@ Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
43684388

43694389
if (op.Ty->isUnsignedIntegerType() &&
43704390
CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
4371-
!CanElideOverflowCheck(CGF.getContext(), op))
4391+
!CanElideOverflowCheck(CGF.getContext(), op) &&
4392+
!op.hasWrappingOperand())
43724393
return EmitOverflowCheckedBinOp(op);
43734394

43744395
if (op.LHS->getType()->isFPOrFPVectorTy()) {
@@ -4488,7 +4509,8 @@ Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
44884509
bool SanitizeSignedBase = CGF.SanOpts.has(SanitizerKind::ShiftBase) &&
44894510
Ops.Ty->hasSignedIntegerRepresentation() &&
44904511
!CGF.getLangOpts().isSignedOverflowDefined() &&
4491-
!CGF.getLangOpts().CPlusPlus20;
4512+
!CGF.getLangOpts().CPlusPlus20 &&
4513+
!Ops.hasWrappingOperand();
44924514
bool SanitizeUnsignedBase =
44934515
CGF.SanOpts.has(SanitizerKind::UnsignedShiftBase) &&
44944516
Ops.Ty->hasUnsignedIntegerRepresentation();

clang/lib/Sema/Sema.cpp

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -735,6 +735,9 @@ ExprResult Sema::ImpCastExprToType(Expr *E, QualType Ty,
735735
QualType ExprTy = Context.getCanonicalType(E->getType());
736736
QualType TypeTy = Context.getCanonicalType(Ty);
737737

738+
if (E->getType().getTypePtr()->isIntegerType() && E->getType().hasWrapsAttr())
739+
Ty = Context.getAttributedType(attr::Wraps, Ty, Ty);
740+
738741
if (ExprTy == TypeTy)
739742
return E;
740743

0 commit comments

Comments
 (0)