1 // Copyright (c) 2018 Google 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 "source/opt/ir_builder.h"
16 
17 #include <memory>
18 #include <vector>
19 
20 #include "effcee/effcee.h"
21 #include "gtest/gtest.h"
22 #include "source/opt/basic_block.h"
23 #include "source/opt/build_module.h"
24 #include "source/opt/instruction.h"
25 #include "source/opt/type_manager.h"
26 #include "spirv-tools/libspirv.hpp"
27 
28 namespace spvtools {
29 namespace opt {
30 namespace {
31 
32 using Analysis = IRContext::Analysis;
33 using IRBuilderTest = ::testing::Test;
34 
Validate(const std::vector<uint32_t> & bin)35 bool Validate(const std::vector<uint32_t>& bin) {
36   spv_target_env target_env = SPV_ENV_UNIVERSAL_1_2;
37   spv_context spvContext = spvContextCreate(target_env);
38   spv_diagnostic diagnostic = nullptr;
39   spv_const_binary_t binary = {bin.data(), bin.size()};
40   spv_result_t error = spvValidate(spvContext, &binary, &diagnostic);
41   if (error != 0) spvDiagnosticPrint(diagnostic);
42   spvDiagnosticDestroy(diagnostic);
43   spvContextDestroy(spvContext);
44   return error == 0;
45 }
46 
Match(const std::string & original,IRContext * context,bool do_validation=true)47 void Match(const std::string& original, IRContext* context,
48            bool do_validation = true) {
49   std::vector<uint32_t> bin;
50   context->module()->ToBinary(&bin, true);
51   if (do_validation) {
52     EXPECT_TRUE(Validate(bin));
53   }
54   std::string assembly;
55   SpirvTools tools(SPV_ENV_UNIVERSAL_1_2);
56   EXPECT_TRUE(
57       tools.Disassemble(bin, &assembly, SpirvTools::kDefaultDisassembleOption))
58       << "Disassembling failed for shader:\n"
59       << assembly << std::endl;
60   auto match_result = effcee::Match(assembly, original);
61   EXPECT_EQ(effcee::Result::Status::Ok, match_result.status())
62       << match_result.message() << "\nChecking result:\n"
63       << assembly;
64 }
65 
TEST_F(IRBuilderTest,TestInsnAddition)66 TEST_F(IRBuilderTest, TestInsnAddition) {
67   const std::string text = R"(
68 ; CHECK: %18 = OpLabel
69 ; CHECK: OpPhi %int %int_0 %14
70 ; CHECK: OpPhi %bool %16 %14
71 ; CHECK: OpBranch %17
72                OpCapability Shader
73           %1 = OpExtInstImport "GLSL.std.450"
74                OpMemoryModel Logical GLSL450
75                OpEntryPoint Fragment %2 "main" %3
76                OpExecutionMode %2 OriginUpperLeft
77                OpSource GLSL 330
78                OpName %2 "main"
79                OpName %4 "i"
80                OpName %3 "c"
81                OpDecorate %3 Location 0
82           %5 = OpTypeVoid
83           %6 = OpTypeFunction %5
84           %7 = OpTypeInt 32 1
85           %8 = OpTypePointer Function %7
86           %9 = OpConstant %7 0
87          %10 = OpTypeBool
88          %11 = OpTypeFloat 32
89          %12 = OpTypeVector %11 4
90          %13 = OpTypePointer Output %12
91           %3 = OpVariable %13 Output
92           %2 = OpFunction %5 None %6
93          %14 = OpLabel
94           %4 = OpVariable %8 Function
95                OpStore %4 %9
96          %15 = OpLoad %7 %4
97          %16 = OpINotEqual %10 %15 %9
98                OpSelectionMerge %17 None
99                OpBranchConditional %16 %18 %17
100          %18 = OpLabel
101                OpBranch %17
102          %17 = OpLabel
103                OpReturn
104                OpFunctionEnd
105 )";
106 
107   {
108     std::unique_ptr<IRContext> context =
109         BuildModule(SPV_ENV_UNIVERSAL_1_2, nullptr, text);
110 
111     BasicBlock* bb = context->cfg()->block(18);
112 
113     // Build managers.
114     context->get_def_use_mgr();
115     context->get_instr_block(nullptr);
116 
117     InstructionBuilder builder(context.get(), &*bb->begin());
118     Instruction* phi1 = builder.AddPhi(7, {9, 14});
119     Instruction* phi2 = builder.AddPhi(10, {16, 14});
120 
121     // Make sure the InstructionBuilder did not update the def/use manager.
122     EXPECT_EQ(context->get_def_use_mgr()->GetDef(phi1->result_id()), nullptr);
123     EXPECT_EQ(context->get_def_use_mgr()->GetDef(phi2->result_id()), nullptr);
124     EXPECT_EQ(context->get_instr_block(phi1), nullptr);
125     EXPECT_EQ(context->get_instr_block(phi2), nullptr);
126 
127     Match(text, context.get());
128   }
129 
130   {
131     std::unique_ptr<IRContext> context =
132         BuildModule(SPV_ENV_UNIVERSAL_1_2, nullptr, text);
133 
134     // Build managers.
135     context->get_def_use_mgr();
136     context->get_instr_block(nullptr);
137 
138     BasicBlock* bb = context->cfg()->block(18);
139     InstructionBuilder builder(
140         context.get(), &*bb->begin(),
141         IRContext::kAnalysisDefUse | IRContext::kAnalysisInstrToBlockMapping);
142     Instruction* phi1 = builder.AddPhi(7, {9, 14});
143     Instruction* phi2 = builder.AddPhi(10, {16, 14});
144 
145     // Make sure InstructionBuilder updated the def/use manager
146     EXPECT_NE(context->get_def_use_mgr()->GetDef(phi1->result_id()), nullptr);
147     EXPECT_NE(context->get_def_use_mgr()->GetDef(phi2->result_id()), nullptr);
148     EXPECT_NE(context->get_instr_block(phi1), nullptr);
149     EXPECT_NE(context->get_instr_block(phi2), nullptr);
150 
151     Match(text, context.get());
152   }
153 }
154 
TEST_F(IRBuilderTest,TestCondBranchAddition)155 TEST_F(IRBuilderTest, TestCondBranchAddition) {
156   const std::string text = R"(
157 ; CHECK: %main = OpFunction %void None %6
158 ; CHECK-NEXT: %15 = OpLabel
159 ; CHECK-NEXT: OpSelectionMerge %13 None
160 ; CHECK-NEXT: OpBranchConditional %true %14 %13
161 ; CHECK-NEXT: %14 = OpLabel
162 ; CHECK-NEXT: OpBranch %13
163 ; CHECK-NEXT: %13 = OpLabel
164 ; CHECK-NEXT: OpReturn
165                OpCapability Shader
166           %1 = OpExtInstImport "GLSL.std.450"
167                OpMemoryModel Logical GLSL450
168                OpEntryPoint Fragment %2 "main" %3
169                OpExecutionMode %2 OriginUpperLeft
170                OpSource GLSL 330
171                OpName %2 "main"
172                OpName %4 "i"
173                OpName %3 "c"
174                OpDecorate %3 Location 0
175           %5 = OpTypeVoid
176           %6 = OpTypeFunction %5
177           %7 = OpTypeBool
178           %8 = OpTypePointer Private %7
179           %9 = OpConstantTrue %7
180          %10 = OpTypeFloat 32
181          %11 = OpTypeVector %10 4
182          %12 = OpTypePointer Output %11
183           %3 = OpVariable %12 Output
184           %4 = OpVariable %8 Private
185           %2 = OpFunction %5 None %6
186          %13 = OpLabel
187                OpReturn
188                OpFunctionEnd
189 )";
190 
191   {
192     std::unique_ptr<IRContext> context =
193         BuildModule(SPV_ENV_UNIVERSAL_1_2, nullptr, text);
194 
195     Function& fn = *context->module()->begin();
196 
197     BasicBlock& bb_merge = *fn.begin();
198 
199     // TODO(1841): Handle id overflow.
200     fn.begin().InsertBefore(std::unique_ptr<BasicBlock>(
201         new BasicBlock(std::unique_ptr<Instruction>(new Instruction(
202             context.get(), spv::Op::OpLabel, 0, context->TakeNextId(), {})))));
203     BasicBlock& bb_true = *fn.begin();
204     {
205       InstructionBuilder builder(context.get(), &*bb_true.begin());
206       builder.AddBranch(bb_merge.id());
207     }
208 
209     // TODO(1841): Handle id overflow.
210     fn.begin().InsertBefore(std::unique_ptr<BasicBlock>(
211         new BasicBlock(std::unique_ptr<Instruction>(new Instruction(
212             context.get(), spv::Op::OpLabel, 0, context->TakeNextId(), {})))));
213     BasicBlock& bb_cond = *fn.begin();
214 
215     InstructionBuilder builder(context.get(), &bb_cond);
216     // This also test consecutive instruction insertion: merge selection +
217     // branch.
218     builder.AddConditionalBranch(9, bb_true.id(), bb_merge.id(), bb_merge.id());
219 
220     Match(text, context.get());
221   }
222 }
223 
TEST_F(IRBuilderTest,AddSelect)224 TEST_F(IRBuilderTest, AddSelect) {
225   const std::string text = R"(
226 ; CHECK: [[bool:%\w+]] = OpTypeBool
227 ; CHECK: [[uint:%\w+]] = OpTypeInt 32 0
228 ; CHECK: [[true:%\w+]] = OpConstantTrue [[bool]]
229 ; CHECK: [[u0:%\w+]] = OpConstant [[uint]] 0
230 ; CHECK: [[u1:%\w+]] = OpConstant [[uint]] 1
231 ; CHECK: OpSelect [[uint]] [[true]] [[u0]] [[u1]]
232 OpCapability Kernel
233 OpCapability Linkage
234 OpMemoryModel Logical OpenCL
235 %1 = OpTypeVoid
236 %2 = OpTypeBool
237 %3 = OpTypeInt 32 0
238 %4 = OpConstantTrue %2
239 %5 = OpConstant %3 0
240 %6 = OpConstant %3 1
241 %7 = OpTypeFunction %1
242 %8 = OpFunction %1 None %7
243 %9 = OpLabel
244 OpReturn
245 OpFunctionEnd
246 )";
247 
248   std::unique_ptr<IRContext> context =
249       BuildModule(SPV_ENV_UNIVERSAL_1_2, nullptr, text);
250   EXPECT_NE(nullptr, context);
251 
252   InstructionBuilder builder(context.get(),
253                              &*context->module()->begin()->begin()->begin());
254   EXPECT_NE(nullptr, builder.AddSelect(3u, 4u, 5u, 6u));
255 
256   Match(text, context.get());
257 }
258 
TEST_F(IRBuilderTest,AddCompositeConstruct)259 TEST_F(IRBuilderTest, AddCompositeConstruct) {
260   const std::string text = R"(
261 ; CHECK: [[uint:%\w+]] = OpTypeInt
262 ; CHECK: [[u0:%\w+]] = OpConstant [[uint]] 0
263 ; CHECK: [[u1:%\w+]] = OpConstant [[uint]] 1
264 ; CHECK: [[struct:%\w+]] = OpTypeStruct [[uint]] [[uint]] [[uint]] [[uint]]
265 ; CHECK: OpCompositeConstruct [[struct]] [[u0]] [[u1]] [[u1]] [[u0]]
266 OpCapability Kernel
267 OpCapability Linkage
268 OpMemoryModel Logical OpenCL
269 %1 = OpTypeVoid
270 %2 = OpTypeInt 32 0
271 %3 = OpConstant %2 0
272 %4 = OpConstant %2 1
273 %5 = OpTypeStruct %2 %2 %2 %2
274 %6 = OpTypeFunction %1
275 %7 = OpFunction %1 None %6
276 %8 = OpLabel
277 OpReturn
278 OpFunctionEnd
279 )";
280 
281   std::unique_ptr<IRContext> context =
282       BuildModule(SPV_ENV_UNIVERSAL_1_2, nullptr, text);
283   EXPECT_NE(nullptr, context);
284 
285   InstructionBuilder builder(context.get(),
286                              &*context->module()->begin()->begin()->begin());
287   std::vector<uint32_t> ids = {3u, 4u, 4u, 3u};
288   EXPECT_NE(nullptr, builder.AddCompositeConstruct(5u, ids));
289 
290   Match(text, context.get());
291 }
292 
TEST_F(IRBuilderTest,ConstantAdder)293 TEST_F(IRBuilderTest, ConstantAdder) {
294   const std::string text = R"(
295 ; CHECK: [[uint:%\w+]] = OpTypeInt 32 0
296 ; CHECK: OpConstant [[uint]] 13
297 ; CHECK: [[sint:%\w+]] = OpTypeInt 32 1
298 ; CHECK: OpConstant [[sint]] -1
299 ; CHECK: OpConstant [[uint]] 1
300 ; CHECK: OpConstant [[sint]] 34
301 ; CHECK: OpConstant [[uint]] 0
302 ; CHECK: OpConstant [[sint]] 0
303 OpCapability Shader
304 OpCapability Linkage
305 OpMemoryModel Logical GLSL450
306 %1 = OpTypeVoid
307 %2 = OpTypeFunction %1
308 %3 = OpFunction %1 None %2
309 %4 = OpLabel
310 OpReturn
311 OpFunctionEnd
312 )";
313 
314   std::unique_ptr<IRContext> context =
315       BuildModule(SPV_ENV_UNIVERSAL_1_2, nullptr, text);
316   EXPECT_NE(nullptr, context);
317 
318   InstructionBuilder builder(context.get(),
319                              &*context->module()->begin()->begin()->begin());
320   EXPECT_NE(nullptr, builder.GetUintConstant(13));
321   EXPECT_NE(nullptr, builder.GetSintConstant(-1));
322 
323   // Try adding the same constants again to make sure they aren't added.
324   EXPECT_NE(nullptr, builder.GetUintConstant(13));
325   EXPECT_NE(nullptr, builder.GetSintConstant(-1));
326 
327   // Try adding different constants to make sure the type is reused.
328   EXPECT_NE(nullptr, builder.GetUintConstant(1));
329   EXPECT_NE(nullptr, builder.GetSintConstant(34));
330 
331   // Try adding 0 as both signed and unsigned.
332   EXPECT_NE(nullptr, builder.GetUintConstant(0));
333   EXPECT_NE(nullptr, builder.GetSintConstant(0));
334 
335   Match(text, context.get());
336 }
337 
TEST_F(IRBuilderTest,ConstantAdderTypeAlreadyExists)338 TEST_F(IRBuilderTest, ConstantAdderTypeAlreadyExists) {
339   const std::string text = R"(
340 ; CHECK: OpConstant %uint 13
341 ; CHECK: OpConstant %int -1
342 ; CHECK: OpConstant %uint 1
343 ; CHECK: OpConstant %int 34
344 ; CHECK: OpConstant %uint 0
345 ; CHECK: OpConstant %int 0
346 OpCapability Shader
347 OpCapability Linkage
348 OpMemoryModel Logical GLSL450
349 %1 = OpTypeVoid
350 %uint = OpTypeInt 32 0
351 %int = OpTypeInt 32 1
352 %4 = OpTypeFunction %1
353 %5 = OpFunction %1 None %4
354 %6 = OpLabel
355 OpReturn
356 OpFunctionEnd
357 )";
358 
359   std::unique_ptr<IRContext> context =
360       BuildModule(SPV_ENV_UNIVERSAL_1_2, nullptr, text);
361   EXPECT_NE(nullptr, context);
362 
363   InstructionBuilder builder(context.get(),
364                              &*context->module()->begin()->begin()->begin());
365   Instruction* const_1 = builder.GetUintConstant(13);
366   Instruction* const_2 = builder.GetSintConstant(-1);
367 
368   EXPECT_NE(nullptr, const_1);
369   EXPECT_NE(nullptr, const_2);
370 
371   // Try adding the same constants again to make sure they aren't added.
372   EXPECT_EQ(const_1, builder.GetUintConstant(13));
373   EXPECT_EQ(const_2, builder.GetSintConstant(-1));
374 
375   Instruction* const_3 = builder.GetUintConstant(1);
376   Instruction* const_4 = builder.GetSintConstant(34);
377 
378   // Try adding different constants to make sure the type is reused.
379   EXPECT_NE(nullptr, const_3);
380   EXPECT_NE(nullptr, const_4);
381 
382   Instruction* const_5 = builder.GetUintConstant(0);
383   Instruction* const_6 = builder.GetSintConstant(0);
384 
385   // Try adding 0 as both signed and unsigned.
386   EXPECT_NE(nullptr, const_5);
387   EXPECT_NE(nullptr, const_6);
388 
389   // They have the same value but different types so should be unique.
390   EXPECT_NE(const_5, const_6);
391 
392   // Check the types are correct.
393   uint32_t type_id_unsigned = const_1->GetSingleWordOperand(0);
394   uint32_t type_id_signed = const_2->GetSingleWordOperand(0);
395 
396   EXPECT_NE(type_id_unsigned, type_id_signed);
397 
398   EXPECT_EQ(const_3->GetSingleWordOperand(0), type_id_unsigned);
399   EXPECT_EQ(const_5->GetSingleWordOperand(0), type_id_unsigned);
400 
401   EXPECT_EQ(const_4->GetSingleWordOperand(0), type_id_signed);
402   EXPECT_EQ(const_6->GetSingleWordOperand(0), type_id_signed);
403 
404   Match(text, context.get());
405 }
406 
TEST_F(IRBuilderTest,AccelerationStructureNV)407 TEST_F(IRBuilderTest, AccelerationStructureNV) {
408   const std::string text = R"(
409 ; CHECK: OpTypeAccelerationStructureKHR
410 OpCapability Shader
411 OpCapability RayTracingNV
412 OpExtension "SPV_NV_ray_tracing"
413 OpMemoryModel Logical GLSL450
414 OpEntryPoint Fragment %8 "main"
415 OpExecutionMode %8 OriginUpperLeft
416 %1 = OpTypeVoid
417 %2 = OpTypeBool
418 %3 = OpTypeAccelerationStructureNV
419 %7 = OpTypeFunction %1
420 %8 = OpFunction %1 None %7
421 %9 = OpLabel
422 OpReturn
423 OpFunctionEnd
424 )";
425 
426   std::unique_ptr<IRContext> context =
427       BuildModule(SPV_ENV_UNIVERSAL_1_2, nullptr, text);
428   EXPECT_NE(nullptr, context);
429 
430   InstructionBuilder builder(context.get(),
431                              &*context->module()->begin()->begin()->begin());
432   Match(text, context.get());
433 }
434 
435 }  // namespace
436 }  // namespace opt
437 }  // namespace spvtools
438