1 // Copyright (c) 2017 The Khronos Group Inc.
2 // Copyright (c) 2017 Valve Corporation
3 // Copyright (c) 2017 LunarG Inc.
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 // http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16
17 #include "source/opt/mem_pass.h"
18
19 #include <memory>
20 #include <set>
21 #include <vector>
22
23 #include "source/cfa.h"
24 #include "source/opt/basic_block.h"
25 #include "source/opt/dominator_analysis.h"
26 #include "source/opt/ir_context.h"
27 #include "source/opt/iterator.h"
28
29 namespace spvtools {
30 namespace opt {
31 namespace {
32 constexpr uint32_t kCopyObjectOperandInIdx = 0;
33 constexpr uint32_t kTypePointerStorageClassInIdx = 0;
34 constexpr uint32_t kTypePointerTypeIdInIdx = 1;
35 } // namespace
36
IsBaseTargetType(const Instruction * typeInst) const37 bool MemPass::IsBaseTargetType(const Instruction* typeInst) const {
38 switch (typeInst->opcode()) {
39 case spv::Op::OpTypeInt:
40 case spv::Op::OpTypeFloat:
41 case spv::Op::OpTypeBool:
42 case spv::Op::OpTypeVector:
43 case spv::Op::OpTypeMatrix:
44 case spv::Op::OpTypeImage:
45 case spv::Op::OpTypeSampler:
46 case spv::Op::OpTypeSampledImage:
47 case spv::Op::OpTypePointer:
48 return true;
49 default:
50 break;
51 }
52 return false;
53 }
54
IsTargetType(const Instruction * typeInst) const55 bool MemPass::IsTargetType(const Instruction* typeInst) const {
56 if (IsBaseTargetType(typeInst)) return true;
57 if (typeInst->opcode() == spv::Op::OpTypeArray) {
58 if (!IsTargetType(
59 get_def_use_mgr()->GetDef(typeInst->GetSingleWordOperand(1)))) {
60 return false;
61 }
62 return true;
63 }
64 if (typeInst->opcode() != spv::Op::OpTypeStruct) return false;
65 // All struct members must be math type
66 return typeInst->WhileEachInId([this](const uint32_t* tid) {
67 Instruction* compTypeInst = get_def_use_mgr()->GetDef(*tid);
68 if (!IsTargetType(compTypeInst)) return false;
69 return true;
70 });
71 }
72
IsNonPtrAccessChain(const spv::Op opcode) const73 bool MemPass::IsNonPtrAccessChain(const spv::Op opcode) const {
74 return opcode == spv::Op::OpAccessChain ||
75 opcode == spv::Op::OpInBoundsAccessChain;
76 }
77
IsPtr(uint32_t ptrId)78 bool MemPass::IsPtr(uint32_t ptrId) {
79 uint32_t varId = ptrId;
80 Instruction* ptrInst = get_def_use_mgr()->GetDef(varId);
81 while (ptrInst->opcode() == spv::Op::OpCopyObject) {
82 varId = ptrInst->GetSingleWordInOperand(kCopyObjectOperandInIdx);
83 ptrInst = get_def_use_mgr()->GetDef(varId);
84 }
85 const spv::Op op = ptrInst->opcode();
86 if (op == spv::Op::OpVariable || IsNonPtrAccessChain(op)) return true;
87 const uint32_t varTypeId = ptrInst->type_id();
88 if (varTypeId == 0) return false;
89 const Instruction* varTypeInst = get_def_use_mgr()->GetDef(varTypeId);
90 return varTypeInst->opcode() == spv::Op::OpTypePointer;
91 }
92
GetPtr(uint32_t ptrId,uint32_t * varId)93 Instruction* MemPass::GetPtr(uint32_t ptrId, uint32_t* varId) {
94 *varId = ptrId;
95 Instruction* ptrInst = get_def_use_mgr()->GetDef(*varId);
96 Instruction* varInst;
97
98 if (ptrInst->opcode() == spv::Op::OpConstantNull) {
99 *varId = 0;
100 return ptrInst;
101 }
102
103 if (ptrInst->opcode() != spv::Op::OpVariable &&
104 ptrInst->opcode() != spv::Op::OpFunctionParameter) {
105 varInst = ptrInst->GetBaseAddress();
106 } else {
107 varInst = ptrInst;
108 }
109 if (varInst->opcode() == spv::Op::OpVariable) {
110 *varId = varInst->result_id();
111 } else {
112 *varId = 0;
113 }
114
115 while (ptrInst->opcode() == spv::Op::OpCopyObject) {
116 uint32_t temp = ptrInst->GetSingleWordInOperand(0);
117 ptrInst = get_def_use_mgr()->GetDef(temp);
118 }
119
120 return ptrInst;
121 }
122
GetPtr(Instruction * ip,uint32_t * varId)123 Instruction* MemPass::GetPtr(Instruction* ip, uint32_t* varId) {
124 assert(ip->opcode() == spv::Op::OpStore || ip->opcode() == spv::Op::OpLoad ||
125 ip->opcode() == spv::Op::OpImageTexelPointer ||
126 ip->IsAtomicWithLoad());
127
128 // All of these opcode place the pointer in position 0.
129 const uint32_t ptrId = ip->GetSingleWordInOperand(0);
130 return GetPtr(ptrId, varId);
131 }
132
HasOnlyNamesAndDecorates(uint32_t id) const133 bool MemPass::HasOnlyNamesAndDecorates(uint32_t id) const {
134 return get_def_use_mgr()->WhileEachUser(id, [this](Instruction* user) {
135 spv::Op op = user->opcode();
136 if (op != spv::Op::OpName && !IsNonTypeDecorate(op)) {
137 return false;
138 }
139 return true;
140 });
141 }
142
KillAllInsts(BasicBlock * bp,bool killLabel)143 void MemPass::KillAllInsts(BasicBlock* bp, bool killLabel) {
144 bp->KillAllInsts(killLabel);
145 }
146
HasLoads(uint32_t varId) const147 bool MemPass::HasLoads(uint32_t varId) const {
148 return !get_def_use_mgr()->WhileEachUser(varId, [this](Instruction* user) {
149 spv::Op op = user->opcode();
150 // TODO(): The following is slightly conservative. Could be
151 // better handling of non-store/name.
152 if (IsNonPtrAccessChain(op) || op == spv::Op::OpCopyObject) {
153 if (HasLoads(user->result_id())) {
154 return false;
155 }
156 } else if (op != spv::Op::OpStore && op != spv::Op::OpName &&
157 !IsNonTypeDecorate(op)) {
158 return false;
159 }
160 return true;
161 });
162 }
163
IsLiveVar(uint32_t varId) const164 bool MemPass::IsLiveVar(uint32_t varId) const {
165 const Instruction* varInst = get_def_use_mgr()->GetDef(varId);
166 // assume live if not a variable eg. function parameter
167 if (varInst->opcode() != spv::Op::OpVariable) return true;
168 // non-function scope vars are live
169 const uint32_t varTypeId = varInst->type_id();
170 const Instruction* varTypeInst = get_def_use_mgr()->GetDef(varTypeId);
171 if (spv::StorageClass(varTypeInst->GetSingleWordInOperand(
172 kTypePointerStorageClassInIdx)) != spv::StorageClass::Function)
173 return true;
174 // test if variable is loaded from
175 return HasLoads(varId);
176 }
177
AddStores(uint32_t ptr_id,std::queue<Instruction * > * insts)178 void MemPass::AddStores(uint32_t ptr_id, std::queue<Instruction*>* insts) {
179 get_def_use_mgr()->ForEachUser(ptr_id, [this, insts](Instruction* user) {
180 spv::Op op = user->opcode();
181 if (IsNonPtrAccessChain(op)) {
182 AddStores(user->result_id(), insts);
183 } else if (op == spv::Op::OpStore) {
184 insts->push(user);
185 }
186 });
187 }
188
DCEInst(Instruction * inst,const std::function<void (Instruction *)> & call_back)189 void MemPass::DCEInst(Instruction* inst,
190 const std::function<void(Instruction*)>& call_back) {
191 std::queue<Instruction*> deadInsts;
192 deadInsts.push(inst);
193 while (!deadInsts.empty()) {
194 Instruction* di = deadInsts.front();
195 // Don't delete labels
196 if (di->opcode() == spv::Op::OpLabel) {
197 deadInsts.pop();
198 continue;
199 }
200 // Remember operands
201 std::set<uint32_t> ids;
202 di->ForEachInId([&ids](uint32_t* iid) { ids.insert(*iid); });
203 uint32_t varId = 0;
204 // Remember variable if dead load
205 if (di->opcode() == spv::Op::OpLoad) (void)GetPtr(di, &varId);
206 if (call_back) {
207 call_back(di);
208 }
209 context()->KillInst(di);
210 // For all operands with no remaining uses, add their instruction
211 // to the dead instruction queue.
212 for (auto id : ids)
213 if (HasOnlyNamesAndDecorates(id)) {
214 Instruction* odi = get_def_use_mgr()->GetDef(id);
215 if (context()->IsCombinatorInstruction(odi)) deadInsts.push(odi);
216 }
217 // if a load was deleted and it was the variable's
218 // last load, add all its stores to dead queue
219 if (varId != 0 && !IsLiveVar(varId)) AddStores(varId, &deadInsts);
220 deadInsts.pop();
221 }
222 }
223
MemPass()224 MemPass::MemPass() {}
225
HasOnlySupportedRefs(uint32_t varId)226 bool MemPass::HasOnlySupportedRefs(uint32_t varId) {
227 return get_def_use_mgr()->WhileEachUser(varId, [this](Instruction* user) {
228 auto dbg_op = user->GetCommonDebugOpcode();
229 if (dbg_op == CommonDebugInfoDebugDeclare ||
230 dbg_op == CommonDebugInfoDebugValue) {
231 return true;
232 }
233 spv::Op op = user->opcode();
234 if (op != spv::Op::OpStore && op != spv::Op::OpLoad &&
235 op != spv::Op::OpName && !IsNonTypeDecorate(op)) {
236 return false;
237 }
238 return true;
239 });
240 }
241
Type2Undef(uint32_t type_id)242 uint32_t MemPass::Type2Undef(uint32_t type_id) {
243 const auto uitr = type2undefs_.find(type_id);
244 if (uitr != type2undefs_.end()) return uitr->second;
245 const uint32_t undefId = TakeNextId();
246 if (undefId == 0) {
247 return 0;
248 }
249
250 std::unique_ptr<Instruction> undef_inst(
251 new Instruction(context(), spv::Op::OpUndef, type_id, undefId, {}));
252 get_def_use_mgr()->AnalyzeInstDefUse(&*undef_inst);
253 get_module()->AddGlobalValue(std::move(undef_inst));
254 type2undefs_[type_id] = undefId;
255 return undefId;
256 }
257
IsTargetVar(uint32_t varId)258 bool MemPass::IsTargetVar(uint32_t varId) {
259 if (varId == 0) {
260 return false;
261 }
262
263 if (seen_non_target_vars_.find(varId) != seen_non_target_vars_.end())
264 return false;
265 if (seen_target_vars_.find(varId) != seen_target_vars_.end()) return true;
266 const Instruction* varInst = get_def_use_mgr()->GetDef(varId);
267 if (varInst->opcode() != spv::Op::OpVariable) return false;
268 const uint32_t varTypeId = varInst->type_id();
269 const Instruction* varTypeInst = get_def_use_mgr()->GetDef(varTypeId);
270 if (spv::StorageClass(varTypeInst->GetSingleWordInOperand(
271 kTypePointerStorageClassInIdx)) != spv::StorageClass::Function) {
272 seen_non_target_vars_.insert(varId);
273 return false;
274 }
275 const uint32_t varPteTypeId =
276 varTypeInst->GetSingleWordInOperand(kTypePointerTypeIdInIdx);
277 Instruction* varPteTypeInst = get_def_use_mgr()->GetDef(varPteTypeId);
278 if (!IsTargetType(varPteTypeInst)) {
279 seen_non_target_vars_.insert(varId);
280 return false;
281 }
282 seen_target_vars_.insert(varId);
283 return true;
284 }
285
286 // Remove all |phi| operands coming from unreachable blocks (i.e., blocks not in
287 // |reachable_blocks|). There are two types of removal that this function can
288 // perform:
289 //
290 // 1- Any operand that comes directly from an unreachable block is completely
291 // removed. Since the block is unreachable, the edge between the unreachable
292 // block and the block holding |phi| has been removed.
293 //
294 // 2- Any operand that comes via a live block and was defined at an unreachable
295 // block gets its value replaced with an OpUndef value. Since the argument
296 // was generated in an unreachable block, it no longer exists, so it cannot
297 // be referenced. However, since the value does not reach |phi| directly
298 // from the unreachable block, the operand cannot be removed from |phi|.
299 // Therefore, we replace the argument value with OpUndef.
300 //
301 // For example, in the switch() below, assume that we want to remove the
302 // argument with value %11 coming from block %41.
303 //
304 // [ ... ]
305 // %41 = OpLabel <--- Unreachable block
306 // %11 = OpLoad %int %y
307 // [ ... ]
308 // OpSelectionMerge %16 None
309 // OpSwitch %12 %16 10 %13 13 %14 18 %15
310 // %13 = OpLabel
311 // OpBranch %16
312 // %14 = OpLabel
313 // OpStore %outparm %int_14
314 // OpBranch %16
315 // %15 = OpLabel
316 // OpStore %outparm %int_15
317 // OpBranch %16
318 // %16 = OpLabel
319 // %30 = OpPhi %int %11 %41 %int_42 %13 %11 %14 %11 %15
320 //
321 // Since %41 is now an unreachable block, the first operand of |phi| needs to
322 // be removed completely. But the operands (%11 %14) and (%11 %15) cannot be
323 // removed because %14 and %15 are reachable blocks. Since %11 no longer exist,
324 // in those arguments, we replace all references to %11 with an OpUndef value.
325 // This results in |phi| looking like:
326 //
327 // %50 = OpUndef %int
328 // [ ... ]
329 // %30 = OpPhi %int %int_42 %13 %50 %14 %50 %15
RemovePhiOperands(Instruction * phi,const std::unordered_set<BasicBlock * > & reachable_blocks)330 void MemPass::RemovePhiOperands(
331 Instruction* phi, const std::unordered_set<BasicBlock*>& reachable_blocks) {
332 std::vector<Operand> keep_operands;
333 uint32_t type_id = 0;
334 // The id of an undefined value we've generated.
335 uint32_t undef_id = 0;
336
337 // Traverse all the operands in |phi|. Build the new operand vector by adding
338 // all the original operands from |phi| except the unwanted ones.
339 for (uint32_t i = 0; i < phi->NumOperands();) {
340 if (i < 2) {
341 // The first two arguments are always preserved.
342 keep_operands.push_back(phi->GetOperand(i));
343 ++i;
344 continue;
345 }
346
347 // The remaining Phi arguments come in pairs. Index 'i' contains the
348 // variable id, index 'i + 1' is the originating block id.
349 assert(i % 2 == 0 && i < phi->NumOperands() - 1 &&
350 "malformed Phi arguments");
351
352 BasicBlock* in_block = cfg()->block(phi->GetSingleWordOperand(i + 1));
353 if (reachable_blocks.find(in_block) == reachable_blocks.end()) {
354 // If the incoming block is unreachable, remove both operands as this
355 // means that the |phi| has lost an incoming edge.
356 i += 2;
357 continue;
358 }
359
360 // In all other cases, the operand must be kept but may need to be changed.
361 uint32_t arg_id = phi->GetSingleWordOperand(i);
362 Instruction* arg_def_instr = get_def_use_mgr()->GetDef(arg_id);
363 BasicBlock* def_block = context()->get_instr_block(arg_def_instr);
364 if (def_block &&
365 reachable_blocks.find(def_block) == reachable_blocks.end()) {
366 // If the current |phi| argument was defined in an unreachable block, it
367 // means that this |phi| argument is no longer defined. Replace it with
368 // |undef_id|.
369 if (!undef_id) {
370 type_id = arg_def_instr->type_id();
371 undef_id = Type2Undef(type_id);
372 }
373 keep_operands.push_back(
374 Operand(spv_operand_type_t::SPV_OPERAND_TYPE_ID, {undef_id}));
375 } else {
376 // Otherwise, the argument comes from a reachable block or from no block
377 // at all (meaning that it was defined in the global section of the
378 // program). In both cases, keep the argument intact.
379 keep_operands.push_back(phi->GetOperand(i));
380 }
381
382 keep_operands.push_back(phi->GetOperand(i + 1));
383
384 i += 2;
385 }
386
387 context()->ForgetUses(phi);
388 phi->ReplaceOperands(keep_operands);
389 context()->AnalyzeUses(phi);
390 }
391
RemoveBlock(Function::iterator * bi)392 void MemPass::RemoveBlock(Function::iterator* bi) {
393 auto& rm_block = **bi;
394
395 // Remove instructions from the block.
396 rm_block.ForEachInst([&rm_block, this](Instruction* inst) {
397 // Note that we do not kill the block label instruction here. The label
398 // instruction is needed to identify the block, which is needed by the
399 // removal of phi operands.
400 if (inst != rm_block.GetLabelInst()) {
401 context()->KillInst(inst);
402 }
403 });
404
405 // Remove the label instruction last.
406 auto label = rm_block.GetLabelInst();
407 context()->KillInst(label);
408
409 *bi = bi->Erase();
410 }
411
RemoveUnreachableBlocks(Function * func)412 bool MemPass::RemoveUnreachableBlocks(Function* func) {
413 bool modified = false;
414
415 // Mark reachable all blocks reachable from the function's entry block.
416 std::unordered_set<BasicBlock*> reachable_blocks;
417 std::unordered_set<BasicBlock*> visited_blocks;
418 std::queue<BasicBlock*> worklist;
419 reachable_blocks.insert(func->entry().get());
420
421 // Initially mark the function entry point as reachable.
422 worklist.push(func->entry().get());
423
424 auto mark_reachable = [&reachable_blocks, &visited_blocks, &worklist,
425 this](uint32_t label_id) {
426 auto successor = cfg()->block(label_id);
427 if (visited_blocks.count(successor) == 0) {
428 reachable_blocks.insert(successor);
429 worklist.push(successor);
430 visited_blocks.insert(successor);
431 }
432 };
433
434 // Transitively mark all blocks reachable from the entry as reachable.
435 while (!worklist.empty()) {
436 BasicBlock* block = worklist.front();
437 worklist.pop();
438
439 // All the successors of a live block are also live.
440 static_cast<const BasicBlock*>(block)->ForEachSuccessorLabel(
441 mark_reachable);
442
443 // All the Merge and ContinueTarget blocks of a live block are also live.
444 block->ForMergeAndContinueLabel(mark_reachable);
445 }
446
447 // Update operands of Phi nodes that reference unreachable blocks.
448 for (auto& block : *func) {
449 // If the block is about to be removed, don't bother updating its
450 // Phi instructions.
451 if (reachable_blocks.count(&block) == 0) {
452 continue;
453 }
454
455 // If the block is reachable and has Phi instructions, remove all
456 // operands from its Phi instructions that reference unreachable blocks.
457 // If the block has no Phi instructions, this is a no-op.
458 block.ForEachPhiInst([&reachable_blocks, this](Instruction* phi) {
459 RemovePhiOperands(phi, reachable_blocks);
460 });
461 }
462
463 // Erase unreachable blocks.
464 for (auto ebi = func->begin(); ebi != func->end();) {
465 if (reachable_blocks.count(&*ebi) == 0) {
466 RemoveBlock(&ebi);
467 modified = true;
468 } else {
469 ++ebi;
470 }
471 }
472
473 return modified;
474 }
475
CFGCleanup(Function * func)476 bool MemPass::CFGCleanup(Function* func) {
477 bool modified = false;
478 modified |= RemoveUnreachableBlocks(func);
479 return modified;
480 }
481
CollectTargetVars(Function * func)482 void MemPass::CollectTargetVars(Function* func) {
483 seen_target_vars_.clear();
484 seen_non_target_vars_.clear();
485 type2undefs_.clear();
486
487 // Collect target (and non-) variable sets. Remove variables with
488 // non-load/store refs from target variable set
489 for (auto& blk : *func) {
490 for (auto& inst : blk) {
491 switch (inst.opcode()) {
492 case spv::Op::OpStore:
493 case spv::Op::OpLoad: {
494 uint32_t varId;
495 (void)GetPtr(&inst, &varId);
496 if (!IsTargetVar(varId)) break;
497 if (HasOnlySupportedRefs(varId)) break;
498 seen_non_target_vars_.insert(varId);
499 seen_target_vars_.erase(varId);
500 } break;
501 default:
502 break;
503 }
504 }
505 }
506 }
507
508 } // namespace opt
509 } // namespace spvtools
510