• 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/dominator_analysis.h"
26 #include "source/opt/ir_context.h"
27 #include "source/opt/iterator.h"
28 
29 namespace spvtools {
30 namespace opt {
31 
32 namespace {
33 
34 const uint32_t kCopyObjectOperandInIdx = 0;
35 const uint32_t kTypePointerStorageClassInIdx = 0;
36 const uint32_t kTypePointerTypeIdInIdx = 1;
37 
38 }  // namespace
39 
IsBaseTargetType(const Instruction * typeInst) const40 bool MemPass::IsBaseTargetType(const Instruction* typeInst) const {
41   switch (typeInst->opcode()) {
42     case SpvOpTypeInt:
43     case SpvOpTypeFloat:
44     case SpvOpTypeBool:
45     case SpvOpTypeVector:
46     case SpvOpTypeMatrix:
47     case SpvOpTypeImage:
48     case SpvOpTypeSampler:
49     case SpvOpTypeSampledImage:
50     case SpvOpTypePointer:
51       return true;
52     default:
53       break;
54   }
55   return false;
56 }
57 
IsTargetType(const Instruction * typeInst) const58 bool MemPass::IsTargetType(const Instruction* typeInst) const {
59   if (IsBaseTargetType(typeInst)) return true;
60   if (typeInst->opcode() == SpvOpTypeArray) {
61     if (!IsTargetType(
62             get_def_use_mgr()->GetDef(typeInst->GetSingleWordOperand(1)))) {
63       return false;
64     }
65     return true;
66   }
67   if (typeInst->opcode() != SpvOpTypeStruct) return false;
68   // All struct members must be math type
69   return typeInst->WhileEachInId([this](const uint32_t* tid) {
70     Instruction* compTypeInst = get_def_use_mgr()->GetDef(*tid);
71     if (!IsTargetType(compTypeInst)) return false;
72     return true;
73   });
74 }
75 
IsNonPtrAccessChain(const SpvOp opcode) const76 bool MemPass::IsNonPtrAccessChain(const SpvOp opcode) const {
77   return opcode == SpvOpAccessChain || opcode == SpvOpInBoundsAccessChain;
78 }
79 
IsPtr(uint32_t ptrId)80 bool MemPass::IsPtr(uint32_t ptrId) {
81   uint32_t varId = ptrId;
82   Instruction* ptrInst = get_def_use_mgr()->GetDef(varId);
83   while (ptrInst->opcode() == SpvOpCopyObject) {
84     varId = ptrInst->GetSingleWordInOperand(kCopyObjectOperandInIdx);
85     ptrInst = get_def_use_mgr()->GetDef(varId);
86   }
87   const SpvOp op = ptrInst->opcode();
88   if (op == SpvOpVariable || IsNonPtrAccessChain(op)) return true;
89   const uint32_t varTypeId = ptrInst->type_id();
90   if (varTypeId == 0) return false;
91   const Instruction* varTypeInst = get_def_use_mgr()->GetDef(varTypeId);
92   return varTypeInst->opcode() == SpvOpTypePointer;
93 }
94 
GetPtr(uint32_t ptrId,uint32_t * varId)95 Instruction* MemPass::GetPtr(uint32_t ptrId, uint32_t* varId) {
96   *varId = ptrId;
97   Instruction* ptrInst = get_def_use_mgr()->GetDef(*varId);
98   Instruction* varInst;
99 
100   if (ptrInst->opcode() == SpvOpConstantNull) {
101     *varId = 0;
102     return ptrInst;
103   }
104 
105   if (ptrInst->opcode() != SpvOpVariable &&
106       ptrInst->opcode() != SpvOpFunctionParameter) {
107     varInst = ptrInst->GetBaseAddress();
108   } else {
109     varInst = ptrInst;
110   }
111   if (varInst->opcode() == SpvOpVariable) {
112     *varId = varInst->result_id();
113   } else {
114     *varId = 0;
115   }
116 
117   while (ptrInst->opcode() == SpvOpCopyObject) {
118     uint32_t temp = ptrInst->GetSingleWordInOperand(0);
119     ptrInst = get_def_use_mgr()->GetDef(temp);
120   }
121 
122   return ptrInst;
123 }
124 
GetPtr(Instruction * ip,uint32_t * varId)125 Instruction* MemPass::GetPtr(Instruction* ip, uint32_t* varId) {
126   assert(ip->opcode() == SpvOpStore || ip->opcode() == SpvOpLoad ||
127          ip->opcode() == SpvOpImageTexelPointer || ip->IsAtomicWithLoad());
128 
129   // All of these opcode place the pointer in position 0.
130   const uint32_t ptrId = ip->GetSingleWordInOperand(0);
131   return GetPtr(ptrId, varId);
132 }
133 
HasOnlyNamesAndDecorates(uint32_t id) const134 bool MemPass::HasOnlyNamesAndDecorates(uint32_t id) const {
135   return get_def_use_mgr()->WhileEachUser(id, [this](Instruction* user) {
136     SpvOp op = user->opcode();
137     if (op != SpvOpName && !IsNonTypeDecorate(op)) {
138       return false;
139     }
140     return true;
141   });
142 }
143 
KillAllInsts(BasicBlock * bp,bool killLabel)144 void MemPass::KillAllInsts(BasicBlock* bp, bool killLabel) {
145   bp->KillAllInsts(killLabel);
146 }
147 
HasLoads(uint32_t varId) const148 bool MemPass::HasLoads(uint32_t varId) const {
149   return !get_def_use_mgr()->WhileEachUser(varId, [this](Instruction* user) {
150     SpvOp op = user->opcode();
151     // TODO(): The following is slightly conservative. Could be
152     // better handling of non-store/name.
153     if (IsNonPtrAccessChain(op) || op == SpvOpCopyObject) {
154       if (HasLoads(user->result_id())) {
155         return false;
156       }
157     } else if (op != SpvOpStore && op != SpvOpName && !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() != SpvOpVariable) 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 (varTypeInst->GetSingleWordInOperand(kTypePointerStorageClassInIdx) !=
172       SpvStorageClassFunction)
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     SpvOp op = user->opcode();
181     if (IsNonPtrAccessChain(op)) {
182       AddStores(user->result_id(), insts);
183     } else if (op == SpvOpStore) {
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() == SpvOpLabel) {
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() == SpvOpLoad) (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     SpvOp op = user->opcode();
234     if (op != SpvOpStore && op != SpvOpLoad && op != SpvOpName &&
235         !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(), SpvOpUndef, 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() != SpvOpVariable) return false;
268   const uint32_t varTypeId = varInst->type_id();
269   const Instruction* varTypeInst = get_def_use_mgr()->GetDef(varTypeId);
270   if (varTypeInst->GetSingleWordInOperand(kTypePointerStorageClassInIdx) !=
271       SpvStorageClassFunction) {
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 SpvOpStore:
493         case SpvOpLoad: {
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