xref: /llvm-project/libc/fuzzing/math/RemQuoDiff.h (revision 3497211d80c22e1c488f1617db1d70413a2096ec)
1 //===-- Template for diffing remquo results ---------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #ifndef LLVM_LIBC_FUZZING_MATH_REMQUO_H
10 #define LLVM_LIBC_FUZZING_MATH_REMQUO_H
11 
12 #include "src/__support/FPUtil/FPBits.h"
13 
14 #include "hdr/math_macros.h"
15 #include <stddef.h>
16 #include <stdint.h>
17 
18 template <typename T> using RemQuoFunc = T (*)(T, T, int *);
19 
20 template <typename T>
21 void RemQuoDiff(RemQuoFunc<T> func1, RemQuoFunc<T> func2, const uint8_t *data,
22                 size_t size) {
23   constexpr size_t typeSize = sizeof(T);
24   if (size < 2 * typeSize)
25     return;
26 
27   T x = *reinterpret_cast<const T *>(data);
28   T y = *reinterpret_cast<const T *>(data + typeSize);
29 
30   int q1, q2;
31   T remainder1 = func1(x, y, &q1);
32   T remainder2 = func2(x, y, &q2);
33 
34   LIBC_NAMESPACE::fputil::FPBits<T> bits1(remainder1);
35   LIBC_NAMESPACE::fputil::FPBits<T> bits2(remainder2);
36 
37   if (bits1.is_nan()) {
38     if (!bits2.is_nan())
39       __builtin_trap();
40     return;
41   }
42 
43   if (bits1.is_inf() != bits2.is_inf())
44     __builtin_trap();
45 
46   // Compare only the 3 LS bits of the quotient.
47   if ((q1 & 0x7) != (q2 & 0x7))
48     __builtin_trap();
49 
50   if (bits1.uintval() != bits2.uintval())
51     __builtin_trap();
52 }
53 
54 #endif // LLVM_LIBC_FUZZING_MATH_REMQUO_H
55