1// Copyright (c) 2015-2016 The Khronos Group Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#include <algorithm>
16#include <cstring>
17#include <string>
18#include <utility>
19#include <vector>
20
21#include "gmock/gmock.h"
22#include "source/spirv_constant.h"
23#include "source/util/bitutils.h"
24#include "source/util/hex_float.h"
25#include "test/test_fixture.h"
26#include "test/unit_spirv.h"
27
28namespace spvtools {
29namespace {
30
31using spvtest::AutoText;
32using spvtest::Concatenate;
33using spvtest::MakeInstruction;
34using spvtest::ScopedContext;
35using spvtest::TextToBinaryTest;
36using testing::Eq;
37using testing::IsNull;
38using testing::NotNull;
39
40// An mask parsing test case.
41struct MaskCase {
42  spv_operand_type_t which_enum;
43  uint32_t expected_value;
44  const char* expression;
45};
46
47using GoodMaskParseTest = ::testing::TestWithParam<MaskCase>;
48
49TEST_P(GoodMaskParseTest, GoodMaskExpressions) {
50  spv_context context = spvContextCreate(SPV_ENV_UNIVERSAL_1_0);
51
52  uint32_t value;
53  EXPECT_EQ(SPV_SUCCESS,
54            AssemblyGrammar(context).parseMaskOperand(
55                GetParam().which_enum, GetParam().expression, &value));
56  EXPECT_EQ(GetParam().expected_value, value);
57
58  spvContextDestroy(context);
59}
60
61INSTANTIATE_TEST_SUITE_P(
62    ParseMask, GoodMaskParseTest,
63    ::testing::ValuesIn(std::vector<MaskCase>{
64        {SPV_OPERAND_TYPE_FP_FAST_MATH_MODE, 0, "None"},
65        {SPV_OPERAND_TYPE_FP_FAST_MATH_MODE, 1, "NotNaN"},
66        {SPV_OPERAND_TYPE_FP_FAST_MATH_MODE, 2, "NotInf"},
67        {SPV_OPERAND_TYPE_FP_FAST_MATH_MODE, 3, "NotNaN|NotInf"},
68        // Mask expressions are symmetric.
69        {SPV_OPERAND_TYPE_FP_FAST_MATH_MODE, 3, "NotInf|NotNaN"},
70        // Repeating a value has no effect.
71        {SPV_OPERAND_TYPE_FP_FAST_MATH_MODE, 3, "NotInf|NotNaN|NotInf"},
72        // Using 3 operands still works.
73        {SPV_OPERAND_TYPE_FP_FAST_MATH_MODE, 0x13, "NotInf|NotNaN|Fast"},
74        {SPV_OPERAND_TYPE_SELECTION_CONTROL, 0, "None"},
75        {SPV_OPERAND_TYPE_SELECTION_CONTROL, 1, "Flatten"},
76        {SPV_OPERAND_TYPE_SELECTION_CONTROL, 2, "DontFlatten"},
77        // Weirdly, you can specify to flatten and don't flatten a selection.
78        {SPV_OPERAND_TYPE_SELECTION_CONTROL, 3, "Flatten|DontFlatten"},
79        {SPV_OPERAND_TYPE_LOOP_CONTROL, 0, "None"},
80        {SPV_OPERAND_TYPE_LOOP_CONTROL, 1, "Unroll"},
81        {SPV_OPERAND_TYPE_LOOP_CONTROL, 2, "DontUnroll"},
82        // Weirdly, you can specify to unroll and don't unroll a loop.
83        {SPV_OPERAND_TYPE_LOOP_CONTROL, 3, "Unroll|DontUnroll"},
84        {SPV_OPERAND_TYPE_FUNCTION_CONTROL, 0, "None"},
85        {SPV_OPERAND_TYPE_FUNCTION_CONTROL, 1, "Inline"},
86        {SPV_OPERAND_TYPE_FUNCTION_CONTROL, 2, "DontInline"},
87        {SPV_OPERAND_TYPE_FUNCTION_CONTROL, 4, "Pure"},
88        {SPV_OPERAND_TYPE_FUNCTION_CONTROL, 8, "Const"},
89        {SPV_OPERAND_TYPE_FUNCTION_CONTROL, 0xd, "Inline|Const|Pure"},
90    }));
91
92using BadFPFastMathMaskParseTest = ::testing::TestWithParam<const char*>;
93
94TEST_P(BadFPFastMathMaskParseTest, BadMaskExpressions) {
95  spv_context context = spvContextCreate(SPV_ENV_UNIVERSAL_1_0);
96
97  uint32_t value;
98  EXPECT_NE(SPV_SUCCESS,
99            AssemblyGrammar(context).parseMaskOperand(
100                SPV_OPERAND_TYPE_FP_FAST_MATH_MODE, GetParam(), &value));
101
102  spvContextDestroy(context);
103}
104
105INSTANTIATE_TEST_SUITE_P(ParseMask, BadFPFastMathMaskParseTest,
106                         ::testing::ValuesIn(std::vector<const char*>{
107                             nullptr, "", "NotValidEnum", "|", "NotInf|",
108                             "|NotInf", "NotInf||NotNaN",
109                             "Unroll"  // A good word, but for the wrong enum
110                         }));
111
112TEST_F(TextToBinaryTest, InvalidText) {
113  ASSERT_EQ(SPV_ERROR_INVALID_TEXT,
114            spvTextToBinary(ScopedContext().context, nullptr, 0, &binary,
115                            &diagnostic));
116  EXPECT_NE(nullptr, diagnostic);
117  EXPECT_THAT(diagnostic->error, Eq(std::string("Missing assembly text.")));
118}
119
120TEST_F(TextToBinaryTest, InvalidPointer) {
121  SetText(
122      "OpEntryPoint Kernel 0 \"\"\nOpExecutionMode 0 LocalSizeHint 1 1 1\n");
123  ASSERT_EQ(SPV_ERROR_INVALID_POINTER,
124            spvTextToBinary(ScopedContext().context, text.str, text.length,
125                            nullptr, &diagnostic));
126}
127
128TEST_F(TextToBinaryTest, InvalidPrefix) {
129  EXPECT_EQ(
130      "Expected <opcode> or <result-id> at the beginning of an instruction, "
131      "found 'Invalid'.",
132      CompileFailure("Invalid"));
133}
134
135TEST_F(TextToBinaryTest, EmptyAssemblyString) {
136  // An empty assembly module is valid!
137  // It should produce a valid module with zero instructions.
138  EXPECT_THAT(CompiledInstructions(""), Eq(std::vector<uint32_t>{}));
139}
140
141TEST_F(TextToBinaryTest, StringSpace) {
142  const std::string code = ("OpSourceExtension \"string with spaces\"\n");
143  EXPECT_EQ(code, EncodeAndDecodeSuccessfully(code));
144}
145
146TEST_F(TextToBinaryTest, UnknownBeginningOfInstruction) {
147  EXPECT_EQ(
148      "Expected <opcode> or <result-id> at the beginning of an instruction, "
149      "found 'Google'.",
150      CompileFailure(
151          "\nOpSource OpenCL_C 12\nOpMemoryModel Physical64 OpenCL\nGoogle\n"));
152  EXPECT_EQ(4u, diagnostic->position.line + 1);
153  EXPECT_EQ(1u, diagnostic->position.column + 1);
154}
155
156TEST_F(TextToBinaryTest, NoEqualSign) {
157  EXPECT_EQ("Expected '=', found end of stream.",
158            CompileFailure("\nOpSource OpenCL_C 12\n"
159                           "OpMemoryModel Physical64 OpenCL\n%2\n"));
160  EXPECT_EQ(5u, diagnostic->position.line + 1);
161  EXPECT_EQ(1u, diagnostic->position.column + 1);
162}
163
164TEST_F(TextToBinaryTest, NoOpCode) {
165  EXPECT_EQ("Expected opcode, found end of stream.",
166            CompileFailure("\nOpSource OpenCL_C 12\n"
167                           "OpMemoryModel Physical64 OpenCL\n%2 =\n"));
168  EXPECT_EQ(5u, diagnostic->position.line + 1);
169  EXPECT_EQ(1u, diagnostic->position.column + 1);
170}
171
172TEST_F(TextToBinaryTest, WrongOpCode) {
173  EXPECT_EQ("Invalid Opcode prefix 'Wahahaha'.",
174            CompileFailure("\nOpSource OpenCL_C 12\n"
175                           "OpMemoryModel Physical64 OpenCL\n%2 = Wahahaha\n"));
176  EXPECT_EQ(4u, diagnostic->position.line + 1);
177  EXPECT_EQ(6u, diagnostic->position.column + 1);
178}
179
180TEST_F(TextToBinaryTest, CRLF) {
181  const std::string input =
182      "%i32 = OpTypeInt 32 1\r\n%c = OpConstant %i32 123\r\n";
183  EXPECT_THAT(
184      CompiledInstructions(input),
185      Eq(Concatenate({MakeInstruction(spv::Op::OpTypeInt, {1, 32, 1}),
186                      MakeInstruction(spv::Op::OpConstant, {1, 2, 123})})));
187}
188
189using TextToBinaryFloatValueTest = spvtest::TextToBinaryTestBase<
190    ::testing::TestWithParam<std::pair<std::string, uint32_t>>>;
191
192TEST_P(TextToBinaryFloatValueTest, Samples) {
193  const std::string input =
194      "%1 = OpTypeFloat 32\n%2 = OpConstant %1 " + GetParam().first;
195  EXPECT_THAT(CompiledInstructions(input),
196              Eq(Concatenate({MakeInstruction(spv::Op::OpTypeFloat, {1, 32}),
197                              MakeInstruction(spv::Op::OpConstant,
198                                              {1, 2, GetParam().second})})));
199}
200
201INSTANTIATE_TEST_SUITE_P(
202    FloatValues, TextToBinaryFloatValueTest,
203    ::testing::ValuesIn(std::vector<std::pair<std::string, uint32_t>>{
204        {"0.0", 0x00000000},          // +0
205        {"!0x00000001", 0x00000001},  // +denorm
206        {"!0x00800000", 0x00800000},  // +norm
207        {"1.5", 0x3fc00000},
208        {"!0x7f800000", 0x7f800000},  // +inf
209        {"!0x7f800001", 0x7f800001},  // NaN
210
211        {"-0.0", 0x80000000},         // -0
212        {"!0x80000001", 0x80000001},  // -denorm
213        {"!0x80800000", 0x80800000},  // -norm
214        {"-2.5", 0xc0200000},
215        {"!0xff800000", 0xff800000},  // -inf
216        {"!0xff800001", 0xff800001},  // NaN
217    }));
218
219using TextToBinaryHalfValueTest = spvtest::TextToBinaryTestBase<
220    ::testing::TestWithParam<std::pair<std::string, uint32_t>>>;
221
222TEST_P(TextToBinaryHalfValueTest, Samples) {
223  const std::string input =
224      "%1 = OpTypeFloat 16\n%2 = OpConstant %1 " + GetParam().first;
225  EXPECT_THAT(CompiledInstructions(input),
226              Eq(Concatenate({MakeInstruction(spv::Op::OpTypeFloat, {1, 16}),
227                              MakeInstruction(spv::Op::OpConstant,
228                                              {1, 2, GetParam().second})})));
229}
230
231INSTANTIATE_TEST_SUITE_P(
232    HalfValues, TextToBinaryHalfValueTest,
233    ::testing::ValuesIn(std::vector<std::pair<std::string, uint32_t>>{
234        {"0.0", 0x00000000},
235        {"1.0", 0x00003c00},
236        {"1.000844", 0x00003c00},  // Truncate to 1.0
237        {"1.000977", 0x00003c01},  // Don't have to truncate
238        {"1.001465", 0x00003c01},  // Truncate to 1.0000977
239        {"1.5", 0x00003e00},
240        {"-1.0", 0x0000bc00},
241        {"2.0", 0x00004000},
242        {"-2.0", 0x0000c000},
243        {"0x1p1", 0x00004000},
244        {"-0x1p1", 0x0000c000},
245        {"0x1.8p1", 0x00004200},
246        {"0x1.8p4", 0x00004e00},
247        {"0x1.801p4", 0x00004e00},
248        {"0x1.804p4", 0x00004e01},
249    }));
250
251TEST(CreateContext, UniversalEnvironment) {
252  auto c = spvContextCreate(SPV_ENV_UNIVERSAL_1_0);
253  EXPECT_THAT(c, NotNull());
254  spvContextDestroy(c);
255}
256
257TEST(CreateContext, VulkanEnvironment) {
258  auto c = spvContextCreate(SPV_ENV_VULKAN_1_0);
259  EXPECT_THAT(c, NotNull());
260  spvContextDestroy(c);
261}
262
263}  // namespace
264}  // namespace spvtools
265