xref: /aosp_15_r20/external/executorch/kernels/optimized/test/libvec_test.cpp (revision 523fa7a60841cd1ecfb9cc4201f1ca8b03ed023a)
1 /*
2  * Copyright (c) Meta Platforms, Inc. and affiliates.
3  * All rights reserved.
4  *
5  * This source code is licensed under the BSD-style license found in the
6  * LICENSE file in the root directory of this source tree.
7  */
8 
9 #include <gtest/gtest.h>
10 
11 #include <executorch/kernels/optimized/vec/functional.h>
12 #include <executorch/kernels/optimized/vec/vec.h>
13 
14 #include <vector>
15 
16 #define TEST_FORALL_SUPPORTED_CTYPES(_) \
17   _<int32_t>();                         \
18   _<int64_t>();                         \
19   _<float>();                           \
20   _<double>();
21 
22 namespace {
23 
24 // Fill a vector with a monotonic sequence of integer values
25 template <typename T>
fill_monotonic(std::vector<T> & arr,const int start=0,const int step=1)26 void fill_monotonic(
27     std::vector<T>& arr,
28     const int start = 0,
29     const int step = 1) {
30   int value = start;
31   for (size_t i = 0; i < arr.size(); ++i) {
32     arr[i] = static_cast<T>(value);
33     value += step;
34   }
35 }
36 
37 template <typename T>
check_all_equal_to(std::vector<T> & arr,const float value)38 bool check_all_equal_to(std::vector<T>& arr, const float value) {
39   for (size_t i = 0; i < arr.size(); ++i) {
40     if (arr[i] != static_cast<T>(value)) {
41       return false;
42     }
43   }
44   return true;
45 }
46 
47 } // namespace
48 
49 template <typename T>
test_load_and_add()50 void test_load_and_add() {
51   using Vec = executorch::vec::Vectorized<T>;
52 
53   constexpr size_t kVecSize = static_cast<size_t>(Vec::size());
54 
55   std::vector<T> in_1(kVecSize);
56   fill_monotonic(in_1);
57 
58   std::vector<T> in_2(kVecSize);
59   fill_monotonic(in_2, kVecSize, -1);
60 
61   const Vec in_1_vec = Vec::loadu(in_1.data());
62   const Vec in_2_vec = Vec::loadu(in_2.data());
63 
64   const Vec out_vec = in_1_vec + in_2_vec;
65 
66   std::vector<T> out(kVecSize);
67   out_vec.store(out.data());
68 
69   EXPECT_TRUE(check_all_equal_to(out, static_cast<T>(kVecSize)));
70 }
71 
TEST(VecFloatTest,LoadAndAdd)72 TEST(VecFloatTest, LoadAndAdd) {
73   TEST_FORALL_SUPPORTED_CTYPES(test_load_and_add);
74 }
75