• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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(spv::Capability::Linkage)) {
27     return Status::SuccessWithoutChange;
28   }
29 
30   spv::ExecutionModel execution_model = GetExecutionModel();
31   if (execution_model == spv::ExecutionModel::Kernel) {
32     // We do not handle kernels.
33     return Status::SuccessWithoutChange;
34   }
35   if (execution_model == spv::ExecutionModel::Max) {
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 spv::ExecutionModel ReplaceInvalidOpcodePass::GetExecutionModel() {
48   spv::ExecutionModel result = spv::ExecutionModel::Max;
49   bool first = true;
50   for (Instruction& entry_point : get_module()->entry_points()) {
51     if (first) {
52       result = static_cast<spv::ExecutionModel>(
53           entry_point.GetSingleWordInOperand(0));
54       first = false;
55     } else {
56       spv::ExecutionModel current_model = static_cast<spv::ExecutionModel>(
57           entry_point.GetSingleWordInOperand(0));
58       if (current_model != result) {
59         result = spv::ExecutionModel::Max;
60         break;
61       }
62     }
63   }
64   return result;
65 }
66 
RewriteFunction(Function * function,spv::ExecutionModel model)67 bool ReplaceInvalidOpcodePass::RewriteFunction(Function* function,
68                                                spv::ExecutionModel 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() == spv::Op::OpLabel || inst->IsNoLine()) {
75           last_line_dbg_inst = nullptr;
76           return;
77         } else if (inst->IsLine()) {
78           last_line_dbg_inst = inst;
79           return;
80         }
81 
82         bool replace = false;
83         if (model != spv::ExecutionModel::Fragment &&
84             IsFragmentShaderOnlyInstruction(inst)) {
85           replace = true;
86         }
87 
88         if (model != spv::ExecutionModel::TessellationControl &&
89             model != spv::ExecutionModel::GLCompute &&
90             !context()->IsTargetEnvAtLeast(SPV_ENV_UNIVERSAL_1_3)) {
91           if (inst->opcode() == spv::Op::OpControlBarrier) {
92             assert(model != spv::ExecutionModel::Kernel &&
93                    "Expecting to be working on a shader module.");
94             replace = true;
95           }
96         }
97 
98         if (replace) {
99           modified = true;
100           if (last_line_dbg_inst == nullptr) {
101             ReplaceInstruction(inst, nullptr, 0, 0);
102           } else {
103             // Get the name of the source file.
104             uint32_t file_name_id = 0;
105             if (last_line_dbg_inst->opcode() == spv::Op::OpLine) {
106               file_name_id = last_line_dbg_inst->GetSingleWordInOperand(0);
107             } else {  // Shader100::DebugLine
108               uint32_t debug_source_id =
109                   last_line_dbg_inst->GetSingleWordInOperand(2);
110               Instruction* debug_source_inst =
111                   context()->get_def_use_mgr()->GetDef(debug_source_id);
112               file_name_id = debug_source_inst->GetSingleWordInOperand(2);
113             }
114             Instruction* file_name =
115                 context()->get_def_use_mgr()->GetDef(file_name_id);
116             const std::string source = file_name->GetInOperand(0).AsString();
117 
118             // Get the line number and column number.
119             uint32_t line_number =
120                 last_line_dbg_inst->GetSingleWordInOperand(1);
121             uint32_t col_number = last_line_dbg_inst->GetSingleWordInOperand(2);
122 
123             // Replace the instruction.
124             ReplaceInstruction(inst, source.c_str(), line_number, col_number);
125           }
126         }
127       },
128       /* run_on_debug_line_insts = */ true);
129   return modified;
130 }
131 
IsFragmentShaderOnlyInstruction(Instruction * inst)132 bool ReplaceInvalidOpcodePass::IsFragmentShaderOnlyInstruction(
133     Instruction* inst) {
134   switch (inst->opcode()) {
135     case spv::Op::OpDPdx:
136     case spv::Op::OpDPdy:
137     case spv::Op::OpFwidth:
138     case spv::Op::OpDPdxFine:
139     case spv::Op::OpDPdyFine:
140     case spv::Op::OpFwidthFine:
141     case spv::Op::OpDPdxCoarse:
142     case spv::Op::OpDPdyCoarse:
143     case spv::Op::OpFwidthCoarse:
144     case spv::Op::OpImageSampleImplicitLod:
145     case spv::Op::OpImageSampleDrefImplicitLod:
146     case spv::Op::OpImageSampleProjImplicitLod:
147     case spv::Op::OpImageSampleProjDrefImplicitLod:
148     case spv::Op::OpImageSparseSampleImplicitLod:
149     case spv::Op::OpImageSparseSampleDrefImplicitLod:
150     case spv::Op::OpImageQueryLod:
151       // TODO: Teach |ReplaceInstruction| to handle block terminators.  Then
152       // uncomment the OpKill case.
153       // case spv::Op::OpKill:
154       // case spv::Op::OpTerminateInstruction:
155       return true;
156     default:
157       return false;
158   }
159 }
160 
ReplaceInstruction(Instruction * inst,const char * source,uint32_t line_number,uint32_t column_number)161 void ReplaceInvalidOpcodePass::ReplaceInstruction(Instruction* inst,
162                                                   const char* source,
163                                                   uint32_t line_number,
164                                                   uint32_t column_number) {
165   if (inst->result_id() != 0) {
166     uint32_t const_id = GetSpecialConstant(inst->type_id());
167     context()->KillNamesAndDecorates(inst);
168     context()->ReplaceAllUsesWith(inst->result_id(), const_id);
169   }
170   assert(!inst->IsBlockTerminator() &&
171          "We cannot simply delete a block terminator.  It must be replaced "
172          "with something.");
173   if (consumer()) {
174     std::string message = BuildWarningMessage(inst->opcode());
175     consumer()(SPV_MSG_WARNING, source, {line_number, column_number, 0},
176                message.c_str());
177   }
178   context()->KillInst(inst);
179 }
180 
GetSpecialConstant(uint32_t type_id)181 uint32_t ReplaceInvalidOpcodePass::GetSpecialConstant(uint32_t type_id) {
182   const analysis::Constant* special_const = nullptr;
183   analysis::ConstantManager* const_mgr = context()->get_constant_mgr();
184   analysis::TypeManager* type_mgr = context()->get_type_mgr();
185 
186   Instruction* type = context()->get_def_use_mgr()->GetDef(type_id);
187   if (type->opcode() == spv::Op::OpTypeVector) {
188     uint32_t component_const =
189         GetSpecialConstant(type->GetSingleWordInOperand(0));
190     std::vector<uint32_t> ids;
191     for (uint32_t i = 0; i < type->GetSingleWordInOperand(1); ++i) {
192       ids.push_back(component_const);
193     }
194     special_const = const_mgr->GetConstant(type_mgr->GetType(type_id), ids);
195   } else {
196     assert(type->opcode() == spv::Op::OpTypeInt ||
197            type->opcode() == spv::Op::OpTypeFloat);
198     std::vector<uint32_t> literal_words;
199     for (uint32_t i = 0; i < type->GetSingleWordInOperand(0); i += 32) {
200       literal_words.push_back(0xDEADBEEF);
201     }
202     special_const =
203         const_mgr->GetConstant(type_mgr->GetType(type_id), literal_words);
204   }
205   assert(special_const != nullptr);
206   return const_mgr->GetDefiningInstruction(special_const)->result_id();
207 }
208 
BuildWarningMessage(spv::Op opcode)209 std::string ReplaceInvalidOpcodePass::BuildWarningMessage(spv::Op opcode) {
210   spv_opcode_desc opcode_info;
211   context()->grammar().lookupOpcode(opcode, &opcode_info);
212   std::string message = "Removing ";
213   message += opcode_info->name;
214   message += " instruction because of incompatible execution model.";
215   return message;
216 }
217 
218 }  // namespace opt
219 }  // namespace spvtools
220