Skip to content

[compiler-rt][nsan] Add support for nan detection #101531

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 18 commits into from
Aug 23, 2024

Conversation

cseslowpoke
Copy link
Contributor

Add support for nan detection
#100305

Copy link

github-actions bot commented Aug 1, 2024

Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be
notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this page.

If this is not working for you, it is probably because you do not have write
permissions for the repository. In which case you can instead tag reviewers by
name in a comment by using @ followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review
by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate
is once a week. Please remember that you are asking for valuable time from other developers.

If you have further questions, they may be answered by the LLVM GitHub User Guide.

You can also ask questions in a comment on this PR, on the LLVM Discord or on the forums.

@llvmbot
Copy link
Member

llvmbot commented Aug 1, 2024

@llvm/pr-subscribers-compiler-rt-sanitizer

Author: pokeslow (cseslowpoke)

Changes

Add support for nan detection
#100305


Full diff: https://github.com/llvm/llvm-project/pull/101531.diff

3 Files Affected:

  • (modified) compiler-rt/lib/nsan/nsan.cpp (+8)
  • (modified) compiler-rt/lib/nsan/nsan_flags.inc (+2)
  • (added) compiler-rt/test/nsan/nan.cpp (+19)
diff --git a/compiler-rt/lib/nsan/nsan.cpp b/compiler-rt/lib/nsan/nsan.cpp
index 568a1b3a65575..9c505193daa00 100644
--- a/compiler-rt/lib/nsan/nsan.cpp
+++ b/compiler-rt/lib/nsan/nsan.cpp
@@ -444,6 +444,14 @@ int32_t checkFT(const FT value, ShadowFT Shadow, CheckTypeT CheckType,
   const InternalFT check_value = value;
   const InternalFT check_shadow = Shadow;
 
+  // We only check for NaNs in the value, not the shadow.
+  if (flags().check_nan && isnan(check_value)) {
+    Decorator D;
+    Printf("%s", D.Warning());
+    Printf("WARNING: NumericalStabilitySanitizer: NaN detected\n");
+    Printf("%s", D.Default());
+  }
+
   // See this article for an interesting discussion of how to compare floats:
   // https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
   static constexpr const FT Eps = FTInfo<FT>::kEpsilon;
diff --git a/compiler-rt/lib/nsan/nsan_flags.inc b/compiler-rt/lib/nsan/nsan_flags.inc
index 63c15475f6754..2c67c4bb7f779 100644
--- a/compiler-rt/lib/nsan/nsan_flags.inc
+++ b/compiler-rt/lib/nsan/nsan_flags.inc
@@ -47,3 +47,5 @@ NSAN_FLAG(bool, enable_loadtracking_stats, false,
           "memory, the number of times nsan resumed from the original value "
           "due to invalid or unknown types.")
 NSAN_FLAG(bool, print_stats_on_exit, false, "If true, print stats on exit.")
+NSAN_FLAG(bool, check_nan, false,
+          "If true, check the floating-point number is nan")
\ No newline at end of file
diff --git a/compiler-rt/test/nsan/nan.cpp b/compiler-rt/test/nsan/nan.cpp
new file mode 100644
index 0000000000000..a84b51859aaed
--- /dev/null
+++ b/compiler-rt/test/nsan/nan.cpp
@@ -0,0 +1,19 @@
+// RUN: %clangxx_nsan -O0 -g %s -o %t
+// RUN: NSAN_OPTIONS=check_nan=true %run %t 2>&1 | FileCheck %s
+
+#include <cmath>
+#include <cstdio>
+
+// This function returns a NaN value for triggering the NaN detection.
+__attribute__((noinline)) float ReturnNaN() {
+  float ret = 0.0 / 0.0;
+  return ret;
+  // CHECK: WARNING: NumericalStabilitySanitizer: NaN detected
+}
+
+int main() {
+  float val = ReturnNaN();
+  printf("val: %f\n", val);
+  // CHECK: WARNING: NumericalStabilitySanitizer: NaN detected
+  return 0;
+}

@cseslowpoke
Copy link
Contributor Author

@alexander-shaposhnikov

@alexander-shaposhnikov
Copy link
Collaborator

Have not looked at the code yet.
Regarding tests - could you please add larger tests (e.g. quadratic equation and unstable version of softmax).
P.S. It'd be interesting to try it on a real-world program and see what the reports look like / check if things work as expected or not.

@cseslowpoke
Copy link
Contributor Author

cseslowpoke commented Aug 6, 2024

Have not looked at the code yet. Regarding tests - could you please add larger tests (e.g. quadratic equation and unstable version of softmax). P.S. It'd be interesting to try it on a real-world program and see what the reports look like / check if things work as expected or not.

Sorry for taking so long to submit this. In the past few days, I wrote some tests (maybe I can add a few more) and made it so that the stack is output when NaN is detected.

cseslowpoke and others added 2 commits August 6, 2024 12:32
[compiler-rt][nsan] Add additional tests for nsan and generate a stack trace for NaN reports
@alexander-shaposhnikov
Copy link
Collaborator

@cseslowpoke, thanks for working on this. I've added a few comments,
I'd probably wait for a few days to let @MaskRay have a look at the patch as well.

@vitalybuka vitalybuka requested review from alexander-shaposhnikov and removed request for vitalybuka August 7, 2024 21:50
__m256 vec = _mm256_loadu_ps(&input[i]);
__m256 result = _mm256_sqrt_ps(vec);
_mm256_storeu_ps(&output[i], result);
// when simd is used, the warning is not triggered
Copy link
Collaborator

Choose a reason for hiding this comment

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

it looks like something is broken.
we'd like to detect cases like this, the report triggered by std::sqrt below is not relevant, need to figure out/understand what's broken for simd.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Sure, I’ll check the generated LLVM IR to identify where the issue might be.

Copy link
Collaborator

Choose a reason for hiding this comment

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

I've simplified the test a bit:

#include <cassert>
#include <cmath>
#include <immintrin.h>
#include <iostream>

void simd_sqrt(const float *input, float *output, size_t size) {
  size_t i = 0;
  assert(size % 8 == 0);
  for (; i < size; i += 8) {
    __m256 vec = _mm256_loadu_ps(&input[i]);
    __m256 result = _mm256_sqrt_ps(vec);
    _mm256_storeu_ps(&output[i], result);
  }
}

int main() {
  float input[] = {0.0, 1.0, -2.0, 3.0, 4.0, 5.0, 6.0, 7.0};
  float output[8];

  simd_sqrt(input, output, 8);

  for (int i = 0; i < 8; ++i) {
    std::cout << output[i] << std::endl;
  }
  return 0;
}
clang++ -fsanitize=numerical -mavx -O3 -g ~/simd2.cpp -o ~/simd2.exe

It also works as expected.

Copy link
Contributor Author

@cseslowpoke cseslowpoke Aug 22, 2024

Choose a reason for hiding this comment

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

When using sqrt, it detects NaN, but I'm not sure if using _mm256_sqrt_ps would exhibit similar behavior.

@alexander-shaposhnikov
Copy link
Collaborator

@cseslowpoke
I've applied locally your patch on top the current trunk and tried the example

#include <iostream>
#include <cmath>

typedef float v8sf __attribute__ ((vector_size(32)));

v8sf simd_sqrt(v8sf a) {
  return __builtin_elementwise_sqrt(a);
}

int main() {
  v8sf a = {1.0, -2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0};
  a = simd_sqrt(a);

  // This prevents DCE.
  for (size_t i = 0; i < 8; ++i) {
    std::cout << a[i] << std::endl;
  }

  return 0;
}

clang++ -fsanitize=numerical -mavx -O3 -g ~/simd.cpp -o ~/simd.exe
NSAN_OPTIONS=check_nan=true,halt_on_error=0 ~/simd.exe

works as expected.
Let's use it as a test for now.

@alexander-shaposhnikov
Copy link
Collaborator

alexander-shaposhnikov commented Aug 20, 2024

@cseslowpoke, let's try to complete this effort:

  1. Rebase the patch
  2. Make sure halt_on_error works (see comments above)
  3. Update tests (see inline comments)
  4. Test halt_on_error=1 and test -O3

Copy link
Collaborator

@alexander-shaposhnikov alexander-shaposhnikov left a comment

Choose a reason for hiding this comment

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

Added a few comments,
otherwise, LGTM.
We can merge it in,
I'll probably do some cleanup afterwards.

@alexander-shaposhnikov alexander-shaposhnikov merged commit 283dff4 into llvm:main Aug 23, 2024
6 checks passed
Copy link

@cseslowpoke Congratulations on having your first Pull Request (PR) merged into the LLVM Project!

Your changes will be combined with recent changes from other authors, then tested by our build bots. If there is a problem with a build, you may receive a report in an email or a comment on this PR.

Please check whether problems have been caused by your change specifically, as the builds can include changes from many authors. It is not uncommon for your change to be included in a build that fails due to someone else's changes, or infrastructure issues.

How to do this, and the rest of the post-merge process, is covered in detail here.

If your change does cause a problem, it may be reverted, or you can revert it yourself. This is a normal part of LLVM development. You can fix your changes and open a new PR to merge them again.

If you don't get any reports, no action is required from you. Your changes are working as expected, well done!

@MatzeB
Copy link
Contributor

MatzeB commented Aug 26, 2024

Hi, I believe this change (after re-applied in 5136521 ) fails our builds using gcc 11.x:

/home/engshare/third-party2/gcc/11.x/centos9-native/886b5eb/bin/g++ -D_GNU_SOURCE -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS -I/home/engshare/third-party2/llvm-fb/17/src/build-platform010/pic/projects/compiler-rt/lib/nsan -I/home/engshare/third-party2/llvm-fb/17/src/llvm-project/compiler-rt/lib/nsan -I/home/engshare/third-party2/llvm-fb/17/src/build-platform010/pic/include -I/home/engshare/third-party2/llvm-fb/17/src/llvm-project/llvm/include -I/home/engshare/third-party2/llvm-fb/17/src/llvm-project/compiler-rt/lib/nsan/.. -O3 -g -pipe -Wall -Wno-error -Wp,-D_FORTIFY_SOURCE=2 -fstack-protector --param=ssp-buffer-size=4 -fno-omit-frame-pointer -momit-leaf-frame-pointer -fno-reorder-blocks-and-partition -gz=none -Wl,-z,relro -fcommon -gdwarf-4 -gstrict-dwarf -march=corei7 -mtune=skylake -nostdinc -grecord-gcc-switches -fdebug-prefix-map=/home/engshare/third-party2/llvm-fb/17/src/llvm-project=/home/engshare/third-party2/llvm-fb/17/src/llvm-project -fdebug-prefix-map=/home/engshare/third-party2/llvm-fb/17/src/build-platform010/pic=/home/engshare/third-party2/llvm-fb/17/src/llvm-project -isystem/home/engshare/third-party2/libedit/3.1/platform010/6e03f73/include -isystem/home/engshare/third-party2/zlib/1.2.8/platform010/76ebdda/include -isystem/home/engshare/third-party2/ncurses/6.1/platform010/76ebdda/include -isystem/home/engshare/third-party2/xz/5.2.2/platform010/76ebdda/include -isystem/home/engshare/third-party2/readline/8.0/platform010/6e03f73/include -isystem/home/engshare/third-party2/gdbm/1.11/platform010/76ebdda/include -isystem/home/engshare/third-party2/binutils/2.37/platform010/64091f4/include -isystem/home/engshare/third-party2/openssl/1.1.1/platform010/76ebdda/include -isystem/home/engshare/third-party2/sqlite/3.36/platform010/9079c97/include -isystem/home/engshare/third-party2/python/3.10/platform010/9168809/include -isystem/home/engshare/third-party2/libffi/3.2.1/platform010/76ebdda/lib/libffi-3.2.1/include -isystem/home/engshare/third-party2/jemalloc/master/platform010/779a252/include -isystem/home/engshare/third-party2/libuuid/1.0.2/platform010/76ebdda/include -isystem/home/engshare/third-party2/libxml2/2.9.9/platform010/ec4b15a/include -isystem/home/engshare/third-party2/libxml2/2.9.9/platform010/ec4b15a/include/libxml2 -isystem/home/engshare/third-party2/grpc/1.42.0/platform010/92e86c7/include -isystem/home/engshare/third-party2/bzip2/1.0.6/platform010/76ebdda/include -isystem/home/engshare/third-party2/libunwind/1.8/platform010/76ebdda/include -isystem/home/engshare/third-party2/libzip/1.5.1/platform010/6ace573/include -isystem/home/engshare/third-party2/benchmark/trunk/platform010/76ebdda/include -isystem/home/engshare/third-party2/re2/20190601/platform010/76ebdda/include -isystem/home/engshare/third-party2/gflags/2.2.0/platform010/76ebdda/include -isystem/home/engshare/third-party2/c-ares/1.13.0/platform010/76ebdda/include -fPIC -fPIC -fno-semantic-interposition -fvisibility-inlines-hidden -Werror=date-time -fno-lifetime-dse -Wall -Wextra -Wno-unused-parameter -Wwrite-strings -Wcast-qual -Wno-missing-field-initializers -pedantic -Wno-long-long -Wimplicit-fallthrough -Wno-uninitialized -Wno-nonnull -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wdelete-non-virtual-dtor -Wsuggest-override -Wno-comment -Wno-misleading-indentation -Wctad-maybe-unsupported -fdiagnostics-color -ffunction-sections -fdata-sections -Wall -Wno-unused-parameter -O2 -g -DNDEBUG -std=c++17 -fvisibility=default -m64 -fPIC -fno-builtin -fno-exceptions -fomit-frame-pointer -funwind-tables -fno-stack-protector -fvisibility=hidden -fno-lto -O3 -g -Wno-variadic-macros -nostdinc++ -fno-rtti -MD -MT projects/compiler-rt/lib/nsan/CMakeFiles/RTNsan.x86_64.dir/nsan.cpp.o -MF projects/compiler-rt/lib/nsan/CMakeFiles/RTNsan.x86_64.dir/nsan.cpp.o.d -o projects/compiler-rt/lib/nsan/CMakeFiles/RTNsan.x86_64.dir/nsan.cpp.o -c /home/engshare/third-party2/llvm-fb/17/src/llvm-project/compiler-rt/lib/nsan/nsan.cpp
In file included from /home/engshare/third-party2/llvm-fb/17/src/llvm-project/compiler-rt/lib/nsan/../sanitizer_common/sanitizer_linux.h:22,
                 from /home/engshare/third-party2/llvm-fb/17/src/llvm-project/compiler-rt/lib/nsan/../sanitizer_common/sanitizer_procmaps.h:25,
                 from /home/engshare/third-party2/llvm-fb/17/src/llvm-project/compiler-rt/lib/nsan/../sanitizer_common/sanitizer_allocator.h:24,
                 from /home/engshare/third-party2/llvm-fb/17/src/llvm-project/compiler-rt/lib/nsan/../sanitizer_common/sanitizer_allocator_internal.h:16,
                 from /home/engshare/third-party2/llvm-fb/17/src/llvm-project/compiler-rt/lib/nsan/../sanitizer_common/sanitizer_addrhashmap.h:19,
                 from /home/engshare/third-party2/llvm-fb/17/src/llvm-project/compiler-rt/lib/nsan/nsan_stats.h:19,
                 from /home/engshare/third-party2/llvm-fb/17/src/llvm-project/compiler-rt/lib/nsan/nsan.cpp:35:
/home/engshare/third-party2/llvm-fb/17/src/llvm-project/compiler-rt/lib/nsan/../sanitizer_common/sanitizer_platform_limits_posix.h:593:10: warning: ISO C++ prohibits anonymous structs [-Wpedantic]
  593 |   struct {
      |          ^
/home/engshare/third-party2/llvm-fb/17/src/llvm-project/compiler-rt/lib/nsan/nsan.cpp: In function 'void __nsan_dump_shadow_mem(const u8*, size_t, size_t, size_t)':
/home/engshare/third-party2/llvm-fb/17/src/llvm-project/compiler-rt/lib/nsan/nsan.cpp:359:23: warning: cast from type 'const u8*' {aka 'const unsigned char*'} to type 'void*' casts away qualifiers [-Wcast-qual]
  359 |     printf("%p:    ", (void *)(addr + R * bytes_per_line));
      |                       ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/engshare/third-party2/llvm-fb/17/src/llvm-project/compiler-rt/lib/nsan/nsan.cpp: In instantiation of 'int32_t checkFT(FT, ShadowFT, __nsan::CheckTypeT, __sanitizer::uptr) [with FT = double; ShadowFT = __float128; int32_t = int; __sanitizer::uptr = long unsigned int]':
/home/engshare/third-party2/llvm-fb/17/src/llvm-project/compiler-rt/lib/nsan/nsan.cpp:605:17:   required from here
/home/engshare/third-party2/llvm-fb/17/src/llvm-project/compiler-rt/lib/nsan/nsan.cpp:449:33: error: call of overloaded 'isnan(const InternalFT&)' is ambiguous
  449 |   if (flags().check_nan && isnan(check_value)) {
      |                            ~~~~~^~~~~~~~~~~~~
In file included from /home/engshare/third-party2/libgcc/11.x/platform010/5684a5a/include/c++/11.x/math.h:36,
                 from /home/engshare/third-party2/llvm-fb/17/src/llvm-project/compiler-rt/lib/nsan/nsan.h:29,
                 from /home/engshare/third-party2/llvm-fb/17/src/llvm-project/compiler-rt/lib/nsan/nsan.cpp:33:
/home/engshare/third-party2/libgcc/11.x/platform010/5684a5a/include/c++/11.x/cmath:624:3: note: candidate: 'constexpr bool std::isnan(long double)'
  624 |   isnan(long double __x)
      |   ^~~~~
/home/engshare/third-party2/libgcc/11.x/platform010/5684a5a/include/c++/11.x/cmath:619:3: note: candidate: 'constexpr bool std::isnan(double)'
  619 |   isnan(double __x)
      |   ^~~~~
/home/engshare/third-party2/libgcc/11.x/platform010/5684a5a/include/c++/11.x/cmath:611:3: note: candidate: 'constexpr bool std::isnan(float)'
  611 |   isnan(float __x)
      |   ^~~~~

could you take a look?

@alexander-shaposhnikov
Copy link
Collaborator

alexander-shaposhnikov commented Aug 26, 2024

@MatzeB - thanks, that's interesting.

UPD. 65d6c47

@cseslowpoke
Copy link
Contributor Author

I think it's because std::isnan doesn't provide a version for __float128, so we may need to find an alternative way to check for nan.

@alexander-shaposhnikov
Copy link
Collaborator

alexander-shaposhnikov commented Aug 26, 2024

UPD. I think a proper fix would be to simply call isnan(value)

@MatzeB
Copy link
Contributor

MatzeB commented Aug 26, 2024

Sorry for slow reaction. Our build succeeded after 65d6c47 . Thanks for (super quick) fix!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants