Skip to content

Commit 238e324

Browse files
committed
implement wraps attribute
Signed-off-by: Justin Stitt <[email protected]>
1 parent df575be commit 238e324

20 files changed

+376
-26
lines changed

clang/docs/ReleaseNotes.rst

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -425,6 +425,15 @@ Attribute Changes in Clang
425425
size_t count;
426426
};
427427
428+
- Introduced ``__attribute((wraps))__`` which can be added to type or variable
429+
declarations. Using an attributed type or variable in an arithmetic
430+
expression will define the overflow behavior for that expression as having
431+
two's complement wrap-around. These expressions cannot trigger integer
432+
overflow warnings or sanitizer warnings. They also cannot be optimized away
433+
by some eager UB optimizations.
434+
435+
This attribute is only valid for C, as there are built-in language
436+
alternatives for other languages.
428437

429438
Improvements to Clang's diagnostics
430439
-----------------------------------

clang/include/clang/AST/Expr.h

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

4064+
/// Does one of the subexpressions have the wraps attribute?
4065+
bool hasWrappingOperand(const ASTContext &Ctx) const;
4066+
40644067
protected:
40654068
BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs, Opcode opc,
40664069
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
@@ -1441,6 +1441,8 @@ class QualType {
14411441
return getQualifiers().hasStrongOrWeakObjCLifetime();
14421442
}
14431443

1444+
bool hasWrapsAttr() const;
1445+
14441446
// true when Type is objc's weak and weak is enabled but ARC isn't.
14451447
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const;
14461448

clang/include/clang/Basic/Attr.td

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4569,3 +4569,10 @@ def ClspvLibclcBuiltin: InheritableAttr {
45694569
let Documentation = [ClspvLibclcBuiltinDoc];
45704570
let SimpleHandler = 1;
45714571
}
4572+
4573+
def Wraps : DeclOrTypeAttr {
4574+
let Spellings = [Clang<"wraps">];
4575+
let Subjects = SubjectList<[Var, TypedefName, Field]>;
4576+
let Documentation = [WrapsDocs];
4577+
let LangOpts = [COnly];
4578+
}

clang/include/clang/Basic/AttrDocs.td

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8101,3 +8101,72 @@ Attribute used by `clspv`_ (OpenCL-C to Vulkan SPIR-V compiler) to identify func
81018101
.. _`libclc`: https://libclc.llvm.org
81028102
}];
81038103
}
8104+
8105+
def WrapsDocs : Documentation {
8106+
let Category = DocCatField;
8107+
let Content = [{
8108+
This attribute can be used with type or variable declarations to denote that
8109+
arithmetic containing these marked components have defined overflow behavior.
8110+
Specifically, the behavior is defined as being consistent with two's complement
8111+
wrap-around. For the purposes of sanitizers or warnings that concern themselves
8112+
with the definedness of integer arithmetic, they will cease to instrument or
8113+
warn about arithmetic that directly involves a "wrapping" component.
8114+
8115+
For example, ``-fsanitize=signed-integer-overflow`` or ``-Winteger-overflow``
8116+
will not warn about suspicious overflowing arithmetic -- assuming correct usage
8117+
of the wraps attribute.
8118+
8119+
This example shows some basic usage of ``__attribute__((wraps))`` on a type
8120+
definition when building with ``-fsanitize=signed-integer-overflow``
8121+
8122+
.. code-block:: c
8123+
8124+
typedef int __attribute__((wraps)) wrapping_int;
8125+
8126+
void foo() {
8127+
wrapping_int a = INT_MAX;
8128+
++a; // no sanitizer warning
8129+
}
8130+
8131+
int main() { foo(); }
8132+
8133+
In the following example, we use ``__attribute__((wraps))`` on a variable to
8134+
disable overflow instrumentation for arithmetic expressions it appears in. We
8135+
do so with a popular overflow-checking pattern which we might not want to trip
8136+
sanitizers (like ``-fsanitize=unsigned-integer-overflow``).
8137+
8138+
.. code-block:: c
8139+
8140+
void foo(int offset) {
8141+
unsigned int A __attribute__((wraps)) = UINT_MAX;
8142+
8143+
// to check for overflow using this pattern, we may perform a real overflow
8144+
// thus triggering sanitizers to step in. Since A is "wrapping", we can be
8145+
// sure there are no sanitizer warnings.
8146+
if (A + offset < A) {
8147+
// handle overflow manually
8148+
// ...
8149+
return;
8150+
}
8151+
8152+
// now, handle non-overflow case ...
8153+
}
8154+
8155+
The above example demonstrates some of the power and elegance this attribute
8156+
provides. We can use code patterns we are already familiar with (like ``if (x +
8157+
y < x)``) while gaining control over the overflow behavior on a case-by-case
8158+
basis.
8159+
8160+
When combined with ``-fwrapv``, this attribute can still be applied as normal
8161+
but has no function apart from annotating types and variables for readers. This
8162+
is because ``-fwrapv`` defines all arithmetic as being "wrapping", rending this
8163+
attribute's efforts redundant.
8164+
8165+
When using this attribute without ``-fwrapv`` and without any sanitizers, it
8166+
still has an impact on the definedness of arithmetic expressions containing
8167+
wrapping components. Since the behavior of said expressions is now technically
8168+
defined, the compiler will forgo some eager optimizations that are used on
8169+
expressions containing UB.
8170+
}];
8171+
}
8172+

clang/include/clang/Basic/DiagnosticGroups.td

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1530,3 +1530,9 @@ def BitIntExtension : DiagGroup<"bit-int-extension">;
15301530

15311531
// Warnings about misuse of ExtractAPI options.
15321532
def ExtractAPIMisuse : DiagGroup<"extractapi-misuse">;
1533+
1534+
// Warnings regarding the usage of __attribute__((wraps)) on non-integer types.
1535+
def UselessWrapsAttr : DiagGroup<"useless-wraps-attribute">;
1536+
1537+
// Warnings about the wraps attribute getting implicitly discarded
1538+
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
@@ -6563,6 +6563,13 @@ def err_counted_by_attr_pointee_unknown_size : Error<
65636563
"a struct type with a flexible array member"
65646564
"}2">;
65656565

6566+
def warn_wraps_attr_var_decl_type_not_integer : Warning<
6567+
"using attribute 'wraps' with non-integer type '%0' has no function">,
6568+
InGroup<UselessWrapsAttr>;
6569+
def warn_wraps_attr_maybe_lost : Warning<
6570+
"'wraps' attribute may be implicitly discarded when converted to %0">,
6571+
InGroup<ImpDiscardedWrapsAttr>;
6572+
65666573
let CategoryName = "ARC Semantic Issue" in {
65676574

65686575
// 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,
@@ -4756,6 +4761,8 @@ BinaryOperator::BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs,
47564761
if (hasStoredFPFeatures())
47574762
setStoredFPFeatures(FPFeatures);
47584763
setDependence(computeDependence(this));
4764+
if (hasWrappingOperand(Ctx))
4765+
setType(Ctx.getAttributedType(attr::Wraps, getType(), getType()));
47594766
}
47604767

47614768
BinaryOperator::BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs,
@@ -4773,6 +4780,8 @@ BinaryOperator::BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs,
47734780
if (hasStoredFPFeatures())
47744781
setStoredFPFeatures(FPFeatures);
47754782
setDependence(computeDependence(this));
4783+
if (hasWrappingOperand(Ctx))
4784+
setType(Ctx.getAttributedType(attr::Wraps, getType(), getType()));
47764785
}
47774786

47784787
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
@@ -2779,7 +2779,7 @@ static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
27792779
APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
27802780
Result = Value.trunc(LHS.getBitWidth());
27812781
if (Result.extend(BitWidth) != Value) {
2782-
if (Info.checkingForUndefinedBehavior())
2782+
if (Info.checkingForUndefinedBehavior() && !E->getType().hasWrapsAttr())
27832783
Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
27842784
diag::warn_integer_constant_overflow)
27852785
<< toString(Result, 10, Result.isSigned(), /*formatAsCLiteral=*/false,
@@ -14117,7 +14117,7 @@ bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
1411714117
if (!Result.isInt()) return Error(E);
1411814118
const APSInt &Value = Result.getInt();
1411914119
if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
14120-
if (Info.checkingForUndefinedBehavior())
14120+
if (Info.checkingForUndefinedBehavior() && !E->getType().hasWrapsAttr())
1412114121
Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1412214122
diag::warn_integer_constant_overflow)
1412314123
<< 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
@@ -2830,6 +2830,10 @@ bool QualType::isTriviallyEqualityComparableType(
28302830
CanonicalType, /*CheckIfTriviallyCopyable=*/false);
28312831
}
28322832

2833+
bool QualType::hasWrapsAttr() const {
2834+
return !isNull() && getTypePtr()->hasAttr(attr::Wraps);
2835+
}
2836+
28332837
bool QualType::isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const {
28342838
return !Context.getLangOpts().ObjCAutoRefCount &&
28352839
Context.getLangOpts().ObjCWeak &&

0 commit comments

Comments
 (0)