Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion clang/lib/Analysis/UnsafeBufferUsage.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -600,12 +600,27 @@ static bool isSafeArraySubscript(const ArraySubscriptExpr &Node,
} else if (const auto *BE = dyn_cast<BinaryOperator>(IndexExpr)) {
// For an integer expression `e` and an integer constant `n`, `e & n` and
// `n & e` are bounded by `n`:
if (BE->getOpcode() != BO_And)
if (BE->getOpcode() != BO_And && BE->getOpcode() != BO_Rem)
return false;

const Expr *LHS = BE->getLHS();
const Expr *RHS = BE->getRHS();

if (BE->getOpcode() == BO_Rem) {
// If n is a negative number, then n % const can be greater than const
if (!LHS->getType()->isUnsignedIntegerType()) {
return false;
}

if (!RHS->isValueDependent() && RHS->EvaluateAsInt(EVResult, Ctx)) {
llvm::APSInt result = EVResult.Val.getInt();
if (result.isNonNegative() && result.getLimitedValue() <= limit)
Copy link

Copilot AI May 15, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nitpick] Consider adding a comment to explain the purpose and derivation of the 'limit' variable to enhance clarity on how it determines the safe boundary for remainder operations.

Copilot uses AI. Check for mistakes.
return true;
}

return false;
}

if ((!LHS->isValueDependent() &&
LHS->EvaluateAsInt(EVResult, Ctx)) || // case: `n & e`
(!RHS->isValueDependent() &&
Expand Down
16 changes: 15 additions & 1 deletion clang/test/SemaCXX/warn-unsafe-buffer-usage-array.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,21 @@ void constant_idx_safe0(unsigned idx) {
buffer[0] = 0;
}

int array[10]; // expected-warning {{'array' is an unsafe buffer that does not perform bounds checks}}
int array[10]; // expected-warning 3{{'array' is an unsafe buffer that does not perform bounds checks}}

void circular_access_unsigned(unsigned idx) {
array[idx % 10];
array[idx % 11]; // expected-note {{used in buffer access here}}
array[(idx + 3) % 10];
array[(--idx) % 8];
array[idx & 9 % 10];
array[9 & idx % 11];
array [12 % 10];
}

void circular_access_signed(int idx) {
array[idx % 10]; // expected-note {{used in buffer access here}}
}

void masked_idx1(unsigned long long idx, Foo f) {
// Bitwise and operation
Expand Down