[Clang]Check for a valid Index in array before getting it
Fixes https://github.com/llvm/llvm-project/issues/154713
@llvm/pr-subscribers-mlir-vector @llvm/pr-subscribers-mlir @llvm/pr-subscribers-llvm-selectiondag
@llvm/pr-subscribers-clang
Author: Balaji V. Iyer. (bviyer)
Changes
Fixes https://github.com/llvm/llvm-project/issues/154713
Full diff: https://github.com/llvm/llvm-project/pull/172399.diff
2 Files Affected:
- (modified) clang/lib/AST/ExprConstant.cpp (+4)
- (added) clang/test/AST/array-overflow-index.c (+9)
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 11c5e1c6e90f4..fb85119b137ab 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -9749,6 +9749,10 @@ bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
if (Success) {
Result.setFrom(Info.Ctx, Val);
+ // If Index cannot be represented as a 64 bit integer, return unsuccessful.
+ if (!Index.tryExtValue().has_value())
+ return Error(E);
+
HandleLValueVectorElement(Info, E, Result, VT->getElementType(),
VT->getNumElements(), Index.getExtValue());
}
diff --git a/clang/test/AST/array-overflow-index.c b/clang/test/AST/array-overflow-index.c
new file mode 100644
index 0000000000000..8a43cfbb01f91
--- /dev/null
+++ b/clang/test/AST/array-overflow-index.c
@@ -0,0 +1,9 @@
+// RUN: %clang_cc1 -verify %s
+
+// ref-no-diagnostics
+// expected-no-diagnostics
+
+int __attribute__((vector_size(4))) test_vector = {1};
+int get_last_element(void) {
+ return test_vector[~0UL];
+}
:white_check_mark: With the latest revision this PR passed the C/C++ code formatter.
This change needs a release note.
Please add an entry to clang/docs/ReleaseNotes.rst in the section the most adapted to the change, and referencing any Github issue this change fixes. Thanks!
Can you add a C++ test case along the lines of
That test should also have a RUN line with the new interpreter (-fexperimental-new-constant-interpreter); from the looks of it, the new interpreter doesn’t have this bug so you shouldn’t have to modify it to fix this
-fexperimental-new-constant-interpreter
When I have this enabled in the test case, it will evaluate it and find out that the array index is greater than array size and thus cannot be represented. So I added a test where it catches these errors.
This change needs a release note. Please add an entry to
clang/docs/ReleaseNotes.rstin the section the most adapted to the change, and referencing any Github issue this change fixes. Thanks!
Added.
NOTE: I had to force push due to a merge issue (Very sorry about it). All the changes are there, just that I squashed two commits into 1.
:window: Windows x64 Test Results
- 53146 tests passed
- 2094 tests skipped
:white_check_mark: The build succeeded and all tests passed.