1 // Copyright (c) 2018 Google LLC
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/replace_invalid_opc.h"
16
17 #include <bitset>
18 #include <vector>
19
20 namespace spvtools {
21 namespace opt {
22
Process()23 Pass::Status ReplaceInvalidOpcodePass::Process() {
24 bool modified = false;
25
26 if (context()->get_feature_mgr()->HasCapability(SpvCapabilityLinkage)) {
27 return Status::SuccessWithoutChange;
28 }
29
30 SpvExecutionModel execution_model = GetExecutionModel();
31 if (execution_model == SpvExecutionModelKernel) {
32 // We do not handle kernels.
33 return Status::SuccessWithoutChange;
34 }
35 if (execution_model == SpvExecutionModelMax) {
36 // Mixed execution models for the entry points. This case is not currently
37 // handled.
38 return Status::SuccessWithoutChange;
39 }
40
41 for (Function& func : *get_module()) {
42 modified |= RewriteFunction(&func, execution_model);
43 }
44 return (modified ? Status::SuccessWithChange : Status::SuccessWithoutChange);
45 }
46
GetExecutionModel()47 SpvExecutionModel ReplaceInvalidOpcodePass::GetExecutionModel() {
48 SpvExecutionModel result = SpvExecutionModelMax;
49 bool first = true;
50 for (Instruction& entry_point : get_module()->entry_points()) {
51 if (first) {
52 result =
53 static_cast<SpvExecutionModel>(entry_point.GetSingleWordInOperand(0));
54 first = false;
55 } else {
56 SpvExecutionModel current_model =
57 static_cast<SpvExecutionModel>(entry_point.GetSingleWordInOperand(0));
58 if (current_model != result) {
59 result = SpvExecutionModelMax;
60 break;
61 }
62 }
63 }
64 return result;
65 }
66
RewriteFunction(Function * function,SpvExecutionModel model)67 bool ReplaceInvalidOpcodePass::RewriteFunction(Function* function,
68 SpvExecutionModel model) {
69 bool modified = false;
70 Instruction* last_line_dbg_inst = nullptr;
71 function->ForEachInst(
72 [model, &modified, &last_line_dbg_inst, this](Instruction* inst) {
73 // Track the debug information so we can have a meaningful message.
74 if (inst->opcode() == SpvOpLabel || inst->opcode() == SpvOpNoLine) {
75 last_line_dbg_inst = nullptr;
76 return;
77 } else if (inst->opcode() == SpvOpLine) {
78 last_line_dbg_inst = inst;
79 return;
80 }
81
82 bool replace = false;
83 if (model != SpvExecutionModelFragment &&
84 IsFragmentShaderOnlyInstruction(inst)) {
85 replace = true;
86 }
87
88 if (model != SpvExecutionModelTessellationControl &&
89 model != SpvExecutionModelGLCompute) {
90 if (inst->opcode() == SpvOpControlBarrier) {
91 assert(model != SpvExecutionModelKernel &&
92 "Expecting to be working on a shader module.");
93 replace = true;
94 }
95 }
96
97 if (replace) {
98 modified = true;
99 if (last_line_dbg_inst == nullptr) {
100 ReplaceInstruction(inst, nullptr, 0, 0);
101 } else {
102 // Get the name of the source file.
103 Instruction* file_name = context()->get_def_use_mgr()->GetDef(
104 last_line_dbg_inst->GetSingleWordInOperand(0));
105 const char* source = reinterpret_cast<const char*>(
106 &file_name->GetInOperand(0).words[0]);
107
108 // Get the line number and column number.
109 uint32_t line_number =
110 last_line_dbg_inst->GetSingleWordInOperand(1);
111 uint32_t col_number = last_line_dbg_inst->GetSingleWordInOperand(2);
112
113 // Replace the instruction.
114 ReplaceInstruction(inst, source, line_number, col_number);
115 }
116 }
117 },
118 /* run_on_debug_line_insts = */ true);
119 return modified;
120 }
121
IsFragmentShaderOnlyInstruction(Instruction * inst)122 bool ReplaceInvalidOpcodePass::IsFragmentShaderOnlyInstruction(
123 Instruction* inst) {
124 switch (inst->opcode()) {
125 case SpvOpDPdx:
126 case SpvOpDPdy:
127 case SpvOpFwidth:
128 case SpvOpDPdxFine:
129 case SpvOpDPdyFine:
130 case SpvOpFwidthFine:
131 case SpvOpDPdxCoarse:
132 case SpvOpDPdyCoarse:
133 case SpvOpFwidthCoarse:
134 case SpvOpImageSampleImplicitLod:
135 case SpvOpImageSampleDrefImplicitLod:
136 case SpvOpImageSampleProjImplicitLod:
137 case SpvOpImageSampleProjDrefImplicitLod:
138 case SpvOpImageSparseSampleImplicitLod:
139 case SpvOpImageSparseSampleDrefImplicitLod:
140 case SpvOpImageQueryLod:
141 // TODO: Teach |ReplaceInstruction| to handle block terminators. Then
142 // uncomment the OpKill case.
143 // case SpvOpKill:
144 // case SpvOpTerminateInstruction:
145 return true;
146 default:
147 return false;
148 }
149 }
150
ReplaceInstruction(Instruction * inst,const char * source,uint32_t line_number,uint32_t column_number)151 void ReplaceInvalidOpcodePass::ReplaceInstruction(Instruction* inst,
152 const char* source,
153 uint32_t line_number,
154 uint32_t column_number) {
155 if (inst->result_id() != 0) {
156 uint32_t const_id = GetSpecialConstant(inst->type_id());
157 context()->KillNamesAndDecorates(inst);
158 context()->ReplaceAllUsesWith(inst->result_id(), const_id);
159 }
160 assert(!inst->IsBlockTerminator() &&
161 "We cannot simply delete a block terminator. It must be replaced "
162 "with something.");
163 if (consumer()) {
164 std::string message = BuildWarningMessage(inst->opcode());
165 consumer()(SPV_MSG_WARNING, source, {line_number, column_number, 0},
166 message.c_str());
167 }
168 context()->KillInst(inst);
169 }
170
GetSpecialConstant(uint32_t type_id)171 uint32_t ReplaceInvalidOpcodePass::GetSpecialConstant(uint32_t type_id) {
172 const analysis::Constant* special_const = nullptr;
173 analysis::ConstantManager* const_mgr = context()->get_constant_mgr();
174 analysis::TypeManager* type_mgr = context()->get_type_mgr();
175
176 Instruction* type = context()->get_def_use_mgr()->GetDef(type_id);
177 if (type->opcode() == SpvOpTypeVector) {
178 uint32_t component_const =
179 GetSpecialConstant(type->GetSingleWordInOperand(0));
180 std::vector<uint32_t> ids;
181 for (uint32_t i = 0; i < type->GetSingleWordInOperand(1); ++i) {
182 ids.push_back(component_const);
183 }
184 special_const = const_mgr->GetConstant(type_mgr->GetType(type_id), ids);
185 } else {
186 assert(type->opcode() == SpvOpTypeInt || type->opcode() == SpvOpTypeFloat);
187 std::vector<uint32_t> literal_words;
188 for (uint32_t i = 0; i < type->GetSingleWordInOperand(0); i += 32) {
189 literal_words.push_back(0xDEADBEEF);
190 }
191 special_const =
192 const_mgr->GetConstant(type_mgr->GetType(type_id), literal_words);
193 }
194 assert(special_const != nullptr);
195 return const_mgr->GetDefiningInstruction(special_const)->result_id();
196 }
197
BuildWarningMessage(SpvOp opcode)198 std::string ReplaceInvalidOpcodePass::BuildWarningMessage(SpvOp opcode) {
199 spv_opcode_desc opcode_info;
200 context()->grammar().lookupOpcode(opcode, &opcode_info);
201 std::string message = "Removing ";
202 message += opcode_info->name;
203 message += " instruction because of incompatible execution model.";
204 return message;
205 }
206
207 } // namespace opt
208 } // namespace spvtools
209