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