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->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 != 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             uint32_t file_name_id = 0;
104             if (last_line_dbg_inst->opcode() == SpvOpLine) {
105               file_name_id = last_line_dbg_inst->GetSingleWordInOperand(0);
106             } else {  // Shader100::DebugLine
107               uint32_t debug_source_id =
108                   last_line_dbg_inst->GetSingleWordInOperand(2);
109               Instruction* debug_source_inst =
110                   context()->get_def_use_mgr()->GetDef(debug_source_id);
111               file_name_id = debug_source_inst->GetSingleWordInOperand(2);
112             }
113             Instruction* file_name =
114                 context()->get_def_use_mgr()->GetDef(file_name_id);
115             const char* source = reinterpret_cast<const char*>(
116                 &file_name->GetInOperand(0).words[0]);
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, 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 SpvOpDPdx:
136     case SpvOpDPdy:
137     case SpvOpFwidth:
138     case SpvOpDPdxFine:
139     case SpvOpDPdyFine:
140     case SpvOpFwidthFine:
141     case SpvOpDPdxCoarse:
142     case SpvOpDPdyCoarse:
143     case SpvOpFwidthCoarse:
144     case SpvOpImageSampleImplicitLod:
145     case SpvOpImageSampleDrefImplicitLod:
146     case SpvOpImageSampleProjImplicitLod:
147     case SpvOpImageSampleProjDrefImplicitLod:
148     case SpvOpImageSparseSampleImplicitLod:
149     case SpvOpImageSparseSampleDrefImplicitLod:
150     case SpvOpImageQueryLod:
151       // TODO: Teach |ReplaceInstruction| to handle block terminators.  Then
152       // uncomment the OpKill case.
153       // case SpvOpKill:
154       // case SpvOpTerminateInstruction:
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() == SpvOpTypeVector) {
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() == SpvOpTypeInt || type->opcode() == SpvOpTypeFloat);
197     std::vector<uint32_t> literal_words;
198     for (uint32_t i = 0; i < type->GetSingleWordInOperand(0); i += 32) {
199       literal_words.push_back(0xDEADBEEF);
200     }
201     special_const =
202         const_mgr->GetConstant(type_mgr->GetType(type_id), literal_words);
203   }
204   assert(special_const != nullptr);
205   return const_mgr->GetDefiningInstruction(special_const)->result_id();
206 }
207 
BuildWarningMessage(SpvOp opcode)208 std::string ReplaceInvalidOpcodePass::BuildWarningMessage(SpvOp opcode) {
209   spv_opcode_desc opcode_info;
210   context()->grammar().lookupOpcode(opcode, &opcode_info);
211   std::string message = "Removing ";
212   message += opcode_info->name;
213   message += " instruction because of incompatible execution model.";
214   return message;
215 }
216 
217 }  // namespace opt
218 }  // namespace spvtools
219