• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2015-2016 The Khronos Group Inc.
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 "validate.h"
16 #include "cfa.h"
17 
18 #include <algorithm>
19 #include <cassert>
20 #include <functional>
21 #include <iostream>
22 #include <map>
23 #include <string>
24 #include <tuple>
25 #include <unordered_map>
26 #include <unordered_set>
27 #include <utility>
28 #include <vector>
29 
30 #include "spirv_validator_options.h"
31 #include "val/basic_block.h"
32 #include "val/construct.h"
33 #include "val/function.h"
34 #include "val/validation_state.h"
35 
36 using std::find;
37 using std::function;
38 using std::get;
39 using std::ignore;
40 using std::make_pair;
41 using std::make_tuple;
42 using std::numeric_limits;
43 using std::pair;
44 using std::string;
45 using std::tie;
46 using std::transform;
47 using std::tuple;
48 using std::unordered_map;
49 using std::unordered_set;
50 using std::vector;
51 
52 using libspirv::BasicBlock;
53 
54 namespace libspirv {
55 
56 namespace {
57 
58 using bb_ptr = BasicBlock*;
59 using cbb_ptr = const BasicBlock*;
60 using bb_iter = vector<BasicBlock*>::const_iterator;
61 
62 }  // namespace
63 
printDominatorList(const BasicBlock & b)64 void printDominatorList(const BasicBlock& b) {
65   std::cout << b.id() << " is dominated by: ";
66   const BasicBlock* bb = &b;
67   while (bb->immediate_dominator() != bb) {
68     bb = bb->immediate_dominator();
69     std::cout << bb->id() << " ";
70   }
71 }
72 
73 #define CFG_ASSERT(ASSERT_FUNC, TARGET) \
74   if (spv_result_t rcode = ASSERT_FUNC(_, TARGET)) return rcode
75 
FirstBlockAssert(ValidationState_t & _,uint32_t target)76 spv_result_t FirstBlockAssert(ValidationState_t& _, uint32_t target) {
77   if (_.current_function().IsFirstBlock(target)) {
78     return _.diag(SPV_ERROR_INVALID_CFG)
79            << "First block " << _.getIdName(target) << " of function "
80            << _.getIdName(_.current_function().id()) << " is targeted by block "
81            << _.getIdName(_.current_function().current_block()->id());
82   }
83   return SPV_SUCCESS;
84 }
85 
MergeBlockAssert(ValidationState_t & _,uint32_t merge_block)86 spv_result_t MergeBlockAssert(ValidationState_t& _, uint32_t merge_block) {
87   if (_.current_function().IsBlockType(merge_block, kBlockTypeMerge)) {
88     return _.diag(SPV_ERROR_INVALID_CFG)
89            << "Block " << _.getIdName(merge_block)
90            << " is already a merge block for another header";
91   }
92   return SPV_SUCCESS;
93 }
94 
95 /// Update the continue construct's exit blocks once the backedge blocks are
96 /// identified in the CFG.
UpdateContinueConstructExitBlocks(Function & function,const vector<pair<uint32_t,uint32_t>> & back_edges)97 void UpdateContinueConstructExitBlocks(
98     Function& function, const vector<pair<uint32_t, uint32_t>>& back_edges) {
99   auto& constructs = function.constructs();
100   // TODO(umar): Think of a faster way to do this
101   for (auto& edge : back_edges) {
102     uint32_t back_edge_block_id;
103     uint32_t loop_header_block_id;
104     tie(back_edge_block_id, loop_header_block_id) = edge;
105     auto is_this_header = [=](Construct& c) {
106       return c.type() == ConstructType::kLoop &&
107              c.entry_block()->id() == loop_header_block_id;
108     };
109 
110     for (auto construct : constructs) {
111       if (is_this_header(construct)) {
112         Construct* continue_construct =
113             construct.corresponding_constructs().back();
114         assert(continue_construct->type() == ConstructType::kContinue);
115 
116         BasicBlock* back_edge_block;
117         tie(back_edge_block, ignore) = function.GetBlock(back_edge_block_id);
118         continue_construct->set_exit(back_edge_block);
119       }
120     }
121   }
122 }
123 
ConstructNames(ConstructType type)124 tuple<string, string, string> ConstructNames(ConstructType type) {
125   string construct_name, header_name, exit_name;
126 
127   switch (type) {
128     case ConstructType::kSelection:
129       construct_name = "selection";
130       header_name = "selection header";
131       exit_name = "merge block";
132       break;
133     case ConstructType::kLoop:
134       construct_name = "loop";
135       header_name = "loop header";
136       exit_name = "merge block";
137       break;
138     case ConstructType::kContinue:
139       construct_name = "continue";
140       header_name = "continue target";
141       exit_name = "back-edge block";
142       break;
143     case ConstructType::kCase:
144       construct_name = "case";
145       header_name = "case entry block";
146       exit_name = "case exit block";
147       break;
148     default:
149       assert(1 == 0 && "Not defined type");
150   }
151 
152   return make_tuple(construct_name, header_name, exit_name);
153 }
154 
155 /// Constructs an error message for construct validation errors
ConstructErrorString(const Construct & construct,const string & header_string,const string & exit_string,const string & dominate_text)156 string ConstructErrorString(const Construct& construct,
157                             const string& header_string,
158                             const string& exit_string,
159                             const string& dominate_text) {
160   string construct_name, header_name, exit_name;
161   tie(construct_name, header_name, exit_name) =
162       ConstructNames(construct.type());
163 
164   // TODO(umar): Add header block for continue constructs to error message
165   return "The " + construct_name + " construct with the " + header_name + " " +
166          header_string + " " + dominate_text + " the " + exit_name + " " +
167          exit_string;
168 }
169 
StructuredControlFlowChecks(const ValidationState_t & _,const Function & function,const vector<pair<uint32_t,uint32_t>> & back_edges)170 spv_result_t StructuredControlFlowChecks(
171     const ValidationState_t& _, const Function& function,
172     const vector<pair<uint32_t, uint32_t>>& back_edges) {
173   /// Check all backedges target only loop headers and have exactly one
174   /// back-edge branching to it
175 
176   // Map a loop header to blocks with back-edges to the loop header.
177   std::map<uint32_t, std::unordered_set<uint32_t>> loop_latch_blocks;
178   for (auto back_edge : back_edges) {
179     uint32_t back_edge_block;
180     uint32_t header_block;
181     tie(back_edge_block, header_block) = back_edge;
182     if (!function.IsBlockType(header_block, kBlockTypeLoop)) {
183       return _.diag(SPV_ERROR_INVALID_CFG)
184              << "Back-edges (" << _.getIdName(back_edge_block) << " -> "
185              << _.getIdName(header_block)
186              << ") can only be formed between a block and a loop header.";
187     }
188     loop_latch_blocks[header_block].insert(back_edge_block);
189   }
190 
191   // Check the loop headers have exactly one back-edge branching to it
192   for (BasicBlock* loop_header : function.ordered_blocks()) {
193     if (!loop_header->reachable()) continue;
194     if (!loop_header->is_type(kBlockTypeLoop)) continue;
195     auto loop_header_id = loop_header->id();
196     auto num_latch_blocks = loop_latch_blocks[loop_header_id].size();
197     if (num_latch_blocks != 1) {
198       return _.diag(SPV_ERROR_INVALID_CFG)
199              << "Loop header " << _.getIdName(loop_header_id)
200              << " is targeted by " << num_latch_blocks
201              << " back-edge blocks but the standard requires exactly one";
202     }
203   }
204 
205   // Check construct rules
206   for (const Construct& construct : function.constructs()) {
207     auto header = construct.entry_block();
208     auto merge = construct.exit_block();
209 
210     if (header->reachable() && !merge) {
211       string construct_name, header_name, exit_name;
212       tie(construct_name, header_name, exit_name) =
213           ConstructNames(construct.type());
214       return _.diag(SPV_ERROR_INTERNAL)
215              << "Construct " + construct_name + " with " + header_name + " " +
216                     _.getIdName(header->id()) + " does not have a " +
217                     exit_name + ". This may be a bug in the validator.";
218     }
219 
220     // If the exit block is reachable then it's dominated by the
221     // header.
222     if (merge && merge->reachable()) {
223       if (!header->dominates(*merge)) {
224         return _.diag(SPV_ERROR_INVALID_CFG) << ConstructErrorString(
225                    construct, _.getIdName(header->id()),
226                    _.getIdName(merge->id()), "does not dominate");
227       }
228       // If it's really a merge block for a selection or loop, then it must be
229       // *strictly* dominated by the header.
230       if (construct.ExitBlockIsMergeBlock() && (header == merge)) {
231         return _.diag(SPV_ERROR_INVALID_CFG) << ConstructErrorString(
232                    construct, _.getIdName(header->id()),
233                    _.getIdName(merge->id()), "does not strictly dominate");
234       }
235     }
236     // Check post-dominance for continue constructs.  But dominance and
237     // post-dominance only make sense when the construct is reachable.
238     if (header->reachable() && construct.type() == ConstructType::kContinue) {
239       if (!merge->postdominates(*header)) {
240         return _.diag(SPV_ERROR_INVALID_CFG) << ConstructErrorString(
241                    construct, _.getIdName(header->id()),
242                    _.getIdName(merge->id()), "is not post dominated by");
243       }
244     }
245     // TODO(umar):  an OpSwitch block dominates all its defined case
246     // constructs
247     // TODO(umar):  each case construct has at most one branch to another
248     // case construct
249     // TODO(umar):  each case construct is branched to by at most one other
250     // case construct
251     // TODO(umar):  if Target T1 branches to Target T2, or if Target T1
252     // branches to the Default and the Default branches to Target T2, then
253     // T1 must immediately precede T2 in the list of the OpSwitch Target
254     // operands
255   }
256   return SPV_SUCCESS;
257 }
258 
PerformCfgChecks(ValidationState_t & _)259 spv_result_t PerformCfgChecks(ValidationState_t& _) {
260   for (auto& function : _.functions()) {
261     // Check all referenced blocks are defined within a function
262     if (function.undefined_block_count() != 0) {
263       string undef_blocks("{");
264       for (auto undefined_block : function.undefined_blocks()) {
265         undef_blocks += _.getIdName(undefined_block) + " ";
266       }
267       return _.diag(SPV_ERROR_INVALID_CFG)
268              << "Block(s) " << undef_blocks << "\b}"
269              << " are referenced but not defined in function "
270              << _.getIdName(function.id());
271     }
272 
273     // Set each block's immediate dominator and immediate postdominator,
274     // and find all back-edges.
275     //
276     // We want to analyze all the blocks in the function, even in degenerate
277     // control flow cases including unreachable blocks.  So use the augmented
278     // CFG to ensure we cover all the blocks.
279     vector<const BasicBlock*> postorder;
280     vector<const BasicBlock*> postdom_postorder;
281     vector<pair<uint32_t, uint32_t>> back_edges;
282     auto ignore_block = [](cbb_ptr) {};
283     auto ignore_edge = [](cbb_ptr, cbb_ptr) {};
284     if (!function.ordered_blocks().empty()) {
285       /// calculate dominators
286       spvtools::CFA<libspirv::BasicBlock>::DepthFirstTraversal(
287           function.first_block(), function.AugmentedCFGSuccessorsFunction(),
288           ignore_block, [&](cbb_ptr b) { postorder.push_back(b); },
289           ignore_edge);
290       auto edges = spvtools::CFA<libspirv::BasicBlock>::CalculateDominators(
291           postorder, function.AugmentedCFGPredecessorsFunction());
292       for (auto edge : edges) {
293         edge.first->SetImmediateDominator(edge.second);
294       }
295 
296       /// calculate post dominators
297       spvtools::CFA<libspirv::BasicBlock>::DepthFirstTraversal(
298           function.pseudo_exit_block(),
299           function.AugmentedCFGPredecessorsFunction(), ignore_block,
300           [&](cbb_ptr b) { postdom_postorder.push_back(b); }, ignore_edge);
301       auto postdom_edges = spvtools::CFA<libspirv::BasicBlock>::CalculateDominators(
302           postdom_postorder, function.AugmentedCFGSuccessorsFunction());
303       for (auto edge : postdom_edges) {
304         edge.first->SetImmediatePostDominator(edge.second);
305       }
306       /// calculate back edges.
307       spvtools::CFA<libspirv::BasicBlock>::DepthFirstTraversal(
308           function.pseudo_entry_block(),
309           function
310               .AugmentedCFGSuccessorsFunctionIncludingHeaderToContinueEdge(),
311           ignore_block, ignore_block, [&](cbb_ptr from, cbb_ptr to) {
312             back_edges.emplace_back(from->id(), to->id());
313           });
314     }
315     UpdateContinueConstructExitBlocks(function, back_edges);
316 
317     auto& blocks = function.ordered_blocks();
318     if (!blocks.empty()) {
319       // Check if the order of blocks in the binary appear before the blocks
320       // they dominate
321       for (auto block = begin(blocks) + 1; block != end(blocks); ++block) {
322         if (auto idom = (*block)->immediate_dominator()) {
323           if (idom != function.pseudo_entry_block() &&
324               block == std::find(begin(blocks), block, idom)) {
325             return _.diag(SPV_ERROR_INVALID_CFG)
326                    << "Block " << _.getIdName((*block)->id())
327                    << " appears in the binary before its dominator "
328                    << _.getIdName(idom->id());
329           }
330         }
331       }
332       // If we have structed control flow, check that no block has a control
333       // flow nesting depth larger than the limit.
334       if (_.HasCapability(SpvCapabilityShader)) {
335         const int control_flow_nesting_depth_limit =
336             _.options()->universal_limits_.max_control_flow_nesting_depth;
337         for (auto block = begin(blocks); block != end(blocks); ++block) {
338           if (function.GetBlockDepth(*block) >
339               control_flow_nesting_depth_limit) {
340             return _.diag(SPV_ERROR_INVALID_CFG)
341                    << "Maximum Control Flow nesting depth exceeded.";
342           }
343         }
344       }
345     }
346 
347     /// Structured control flow checks are only required for shader capabilities
348     if (_.HasCapability(SpvCapabilityShader)) {
349       if (auto error = StructuredControlFlowChecks(_, function, back_edges))
350         return error;
351     }
352   }
353   return SPV_SUCCESS;
354 }
355 
CfgPass(ValidationState_t & _,const spv_parsed_instruction_t * inst)356 spv_result_t CfgPass(ValidationState_t& _,
357                      const spv_parsed_instruction_t* inst) {
358   SpvOp opcode = static_cast<SpvOp>(inst->opcode);
359   switch (opcode) {
360     case SpvOpLabel:
361       if (auto error = _.current_function().RegisterBlock(inst->result_id))
362         return error;
363       break;
364     case SpvOpLoopMerge: {
365       uint32_t merge_block = inst->words[inst->operands[0].offset];
366       uint32_t continue_block = inst->words[inst->operands[1].offset];
367       CFG_ASSERT(MergeBlockAssert, merge_block);
368 
369       if (auto error = _.current_function().RegisterLoopMerge(merge_block,
370                                                               continue_block))
371         return error;
372     } break;
373     case SpvOpSelectionMerge: {
374       uint32_t merge_block = inst->words[inst->operands[0].offset];
375       CFG_ASSERT(MergeBlockAssert, merge_block);
376 
377       if (auto error = _.current_function().RegisterSelectionMerge(merge_block))
378         return error;
379     } break;
380     case SpvOpBranch: {
381       uint32_t target = inst->words[inst->operands[0].offset];
382       CFG_ASSERT(FirstBlockAssert, target);
383 
384       _.current_function().RegisterBlockEnd({target}, opcode);
385     } break;
386     case SpvOpBranchConditional: {
387       uint32_t tlabel = inst->words[inst->operands[1].offset];
388       uint32_t flabel = inst->words[inst->operands[2].offset];
389       CFG_ASSERT(FirstBlockAssert, tlabel);
390       CFG_ASSERT(FirstBlockAssert, flabel);
391 
392       _.current_function().RegisterBlockEnd({tlabel, flabel}, opcode);
393     } break;
394 
395     case SpvOpSwitch: {
396       vector<uint32_t> cases;
397       for (int i = 1; i < inst->num_operands; i += 2) {
398         uint32_t target = inst->words[inst->operands[i].offset];
399         CFG_ASSERT(FirstBlockAssert, target);
400         cases.push_back(target);
401       }
402       _.current_function().RegisterBlockEnd({cases}, opcode);
403     } break;
404     case SpvOpKill:
405     case SpvOpReturn:
406     case SpvOpReturnValue:
407     case SpvOpUnreachable:
408       _.current_function().RegisterBlockEnd(vector<uint32_t>(), opcode);
409       break;
410     default:
411       break;
412   }
413   return SPV_SUCCESS;
414 }
415 }  // namespace libspirv
416