1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
|
// Copyright (c) 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "cfg.h"
#include "cfa.h"
#include "ir_builder.h"
#include "ir_context.h"
#include "module.h"
namespace spvtools {
namespace opt {
namespace {
using cbb_ptr = const opt::BasicBlock*;
// Universal Limit of ResultID + 1
const int kMaxResultId = 0x400000;
} // namespace
CFG::CFG(opt::Module* module)
: module_(module),
pseudo_entry_block_(std::unique_ptr<opt::Instruction>(
new opt::Instruction(module->context(), SpvOpLabel, 0, 0, {}))),
pseudo_exit_block_(std::unique_ptr<opt::Instruction>(new opt::Instruction(
module->context(), SpvOpLabel, 0, kMaxResultId, {}))) {
for (auto& fn : *module) {
for (auto& blk : fn) {
RegisterBlock(&blk);
}
}
}
void CFG::AddEdges(opt::BasicBlock* blk) {
uint32_t blk_id = blk->id();
// Force the creation of an entry, not all basic block have predecessors
// (such as the entry blocks and some unreachables).
label2preds_[blk_id];
const auto* const_blk = blk;
const_blk->ForEachSuccessorLabel(
[blk_id, this](const uint32_t succ_id) { AddEdge(blk_id, succ_id); });
}
void CFG::RemoveNonExistingEdges(uint32_t blk_id) {
std::vector<uint32_t> updated_pred_list;
for (uint32_t id : preds(blk_id)) {
const opt::BasicBlock* pred_blk = block(id);
bool has_branch = false;
pred_blk->ForEachSuccessorLabel([&has_branch, blk_id](uint32_t succ) {
if (succ == blk_id) {
has_branch = true;
}
});
if (has_branch) updated_pred_list.push_back(id);
}
label2preds_.at(blk_id) = std::move(updated_pred_list);
}
void CFG::ComputeStructuredOrder(opt::Function* func, opt::BasicBlock* root,
std::list<opt::BasicBlock*>* order) {
assert(module_->context()->get_feature_mgr()->HasCapability(
SpvCapabilityShader) &&
"This only works on structured control flow");
// Compute structured successors and do DFS.
ComputeStructuredSuccessors(func);
auto ignore_block = [](cbb_ptr) {};
auto ignore_edge = [](cbb_ptr, cbb_ptr) {};
auto get_structured_successors = [this](const opt::BasicBlock* b) {
return &(block2structured_succs_[b]);
};
// TODO(greg-lunarg): Get rid of const_cast by making moving const
// out of the cfa.h prototypes and into the invoking code.
auto post_order = [&](cbb_ptr b) {
order->push_front(const_cast<opt::BasicBlock*>(b));
};
CFA<opt::BasicBlock>::DepthFirstTraversal(
root, get_structured_successors, ignore_block, post_order, ignore_edge);
}
void CFG::ForEachBlockInPostOrder(BasicBlock* bb,
const std::function<void(BasicBlock*)>& f) {
std::vector<BasicBlock*> po;
std::unordered_set<BasicBlock*> seen;
ComputePostOrderTraversal(bb, &po, &seen);
for (BasicBlock* current_bb : po) {
if (!IsPseudoExitBlock(current_bb) && !IsPseudoEntryBlock(current_bb)) {
f(current_bb);
}
}
}
void CFG::ForEachBlockInReversePostOrder(
BasicBlock* bb, const std::function<void(BasicBlock*)>& f) {
std::vector<BasicBlock*> po;
std::unordered_set<BasicBlock*> seen;
ComputePostOrderTraversal(bb, &po, &seen);
for (auto current_bb = po.rbegin(); current_bb != po.rend(); ++current_bb) {
if (!IsPseudoExitBlock(*current_bb) && !IsPseudoEntryBlock(*current_bb)) {
f(*current_bb);
}
}
}
void CFG::ComputeStructuredSuccessors(opt::Function* func) {
block2structured_succs_.clear();
for (auto& blk : *func) {
// If no predecessors in function, make successor to pseudo entry.
if (label2preds_[blk.id()].size() == 0)
block2structured_succs_[&pseudo_entry_block_].push_back(&blk);
// If header, make merge block first successor and continue block second
// successor if there is one.
uint32_t mbid = blk.MergeBlockIdIfAny();
if (mbid != 0) {
block2structured_succs_[&blk].push_back(block(mbid));
uint32_t cbid = blk.ContinueBlockIdIfAny();
if (cbid != 0) {
block2structured_succs_[&blk].push_back(block(cbid));
}
}
// Add true successors.
const auto& const_blk = blk;
const_blk.ForEachSuccessorLabel([&blk, this](const uint32_t sbid) {
block2structured_succs_[&blk].push_back(block(sbid));
});
}
}
void CFG::ComputePostOrderTraversal(BasicBlock* bb, vector<BasicBlock*>* order,
unordered_set<BasicBlock*>* seen) {
seen->insert(bb);
static_cast<const BasicBlock*>(bb)->ForEachSuccessorLabel(
[&order, &seen, this](const uint32_t sbid) {
BasicBlock* succ_bb = id2block_[sbid];
if (!seen->count(succ_bb)) {
ComputePostOrderTraversal(succ_bb, order, seen);
}
});
order->push_back(bb);
}
BasicBlock* CFG::SplitLoopHeader(opt::BasicBlock* bb) {
assert(bb->GetLoopMergeInst() && "Expecting bb to be the header of a loop.");
Function* fn = bb->GetParent();
IRContext* context = module_->context();
// Find the insertion point for the new bb.
Function::iterator header_it = std::find_if(
fn->begin(), fn->end(),
[bb](BasicBlock& block_in_func) { return &block_in_func == bb; });
assert(header_it != fn->end());
const std::vector<uint32_t>& pred = preds(bb->id());
// Find the back edge
opt::BasicBlock* latch_block = nullptr;
Function::iterator latch_block_iter = header_it;
while (++latch_block_iter != fn->end()) {
// If blocks are in the proper order, then the only branch that appears
// after the header is the latch.
if (std::find(pred.begin(), pred.end(), latch_block_iter->id()) !=
pred.end()) {
break;
}
}
assert(latch_block_iter != fn->end() && "Could not find the latch.");
latch_block = &*latch_block_iter;
RemoveSuccessorEdges(bb);
// Create the new header bb basic bb.
// Leave the phi instructions behind.
auto iter = bb->begin();
while (iter->opcode() == SpvOpPhi) {
++iter;
}
std::unique_ptr<opt::BasicBlock> newBlock(
bb->SplitBasicBlock(context, context->TakeNextId(), iter));
// Insert the new bb in the correct position
auto insert_pos = header_it;
++insert_pos;
opt::BasicBlock* new_header = &*insert_pos.InsertBefore(std::move(newBlock));
new_header->SetParent(fn);
uint32_t new_header_id = new_header->id();
context->AnalyzeDefUse(new_header->GetLabelInst());
// Update cfg
RegisterBlock(new_header);
// Update bb mappings.
context->set_instr_block(new_header->GetLabelInst(), new_header);
new_header->ForEachInst([new_header, context](opt::Instruction* inst) {
context->set_instr_block(inst, new_header);
});
// Adjust the OpPhi instructions as needed.
bb->ForEachPhiInst([latch_block, bb, new_header, context](Instruction* phi) {
std::vector<uint32_t> preheader_phi_ops;
std::vector<Operand> header_phi_ops;
// Identify where the original inputs to original OpPhi belong: header or
// preheader.
for (uint32_t i = 0; i < phi->NumInOperands(); i += 2) {
uint32_t def_id = phi->GetSingleWordInOperand(i);
uint32_t branch_id = phi->GetSingleWordInOperand(i + 1);
if (branch_id == latch_block->id()) {
header_phi_ops.push_back({SPV_OPERAND_TYPE_ID, {def_id}});
header_phi_ops.push_back({SPV_OPERAND_TYPE_ID, {branch_id}});
} else {
preheader_phi_ops.push_back(def_id);
preheader_phi_ops.push_back(branch_id);
}
}
// Create a phi instruction if and only if the preheader_phi_ops has more
// than one pair.
if (preheader_phi_ops.size() > 2) {
opt::InstructionBuilder builder(
context, &*bb->begin(),
opt::IRContext::kAnalysisDefUse |
opt::IRContext::kAnalysisInstrToBlockMapping);
opt::Instruction* new_phi =
builder.AddPhi(phi->type_id(), preheader_phi_ops);
// Add the OpPhi to the header bb.
header_phi_ops.push_back({SPV_OPERAND_TYPE_ID, {new_phi->result_id()}});
header_phi_ops.push_back({SPV_OPERAND_TYPE_ID, {bb->id()}});
} else {
// An OpPhi with a single entry is just a copy. In this case use the same
// instruction in the new header.
header_phi_ops.push_back({SPV_OPERAND_TYPE_ID, {preheader_phi_ops[0]}});
header_phi_ops.push_back({SPV_OPERAND_TYPE_ID, {bb->id()}});
}
phi->RemoveFromList();
std::unique_ptr<opt::Instruction> phi_owner(phi);
phi->SetInOperands(std::move(header_phi_ops));
new_header->begin()->InsertBefore(std::move(phi_owner));
context->set_instr_block(phi, new_header);
context->AnalyzeUses(phi);
});
// Add a branch to the new header.
opt::InstructionBuilder branch_builder(
context, bb,
opt::IRContext::kAnalysisDefUse |
opt::IRContext::kAnalysisInstrToBlockMapping);
bb->AddInstruction(MakeUnique<opt::Instruction>(
context, SpvOpBranch, 0, 0,
std::initializer_list<opt::Operand>{
{SPV_OPERAND_TYPE_ID, {new_header->id()}}}));
context->AnalyzeUses(bb->terminator());
context->set_instr_block(bb->terminator(), bb);
label2preds_[new_header->id()].push_back(bb->id());
// Update the latch to branch to the new header.
latch_block->ForEachSuccessorLabel([bb, new_header_id](uint32_t* id) {
if (*id == bb->id()) {
*id = new_header_id;
}
});
opt::Instruction* latch_branch = latch_block->terminator();
context->AnalyzeUses(latch_branch);
label2preds_[new_header->id()].push_back(latch_block->id());
auto& block_preds = label2preds_[bb->id()];
auto latch_pos =
std::find(block_preds.begin(), block_preds.end(), latch_block->id());
assert(latch_pos != block_preds.end() && "The cfg was invalid.");
block_preds.erase(latch_pos);
// Update the loop descriptors
if (context->AreAnalysesValid(opt::IRContext::kAnalysisLoopAnalysis)) {
LoopDescriptor* loop_desc = context->GetLoopDescriptor(bb->GetParent());
Loop* loop = (*loop_desc)[bb->id()];
loop->AddBasicBlock(new_header_id);
loop->SetHeaderBlock(new_header);
loop_desc->SetBasicBlockToLoop(new_header_id, loop);
loop->RemoveBasicBlock(bb->id());
loop->SetPreHeaderBlock(bb);
Loop* parent_loop = loop->GetParent();
if (parent_loop != nullptr) {
parent_loop->AddBasicBlock(bb->id());
loop_desc->SetBasicBlockToLoop(bb->id(), parent_loop);
} else {
loop_desc->SetBasicBlockToLoop(bb->id(), nullptr);
}
}
return new_header;
}
} // namespace opt
} // namespace spvtools
|