blob: 631f968ad5100bcd65af92550266c2314997563e [file] [log] [blame]
Greg Fischer04fcc662016-11-10 10:11:50 -07001// 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 "inline_pass.h"
GregFe28bd392017-08-01 17:20:13 -060018
Greg Fischerbba812f2017-05-04 20:55:53 -060019#include "cfa.h"
Greg Fischer04fcc662016-11-10 10:11:50 -070020
21// Indices of operands in SPIR-V instructions
22
Greg Fischer04fcc662016-11-10 10:11:50 -070023static const int kSpvFunctionCallFunctionId = 2;
24static const int kSpvFunctionCallArgumentId = 3;
25static const int kSpvReturnValueId = 0;
26static const int kSpvTypePointerStorageClass = 1;
27static const int kSpvTypePointerTypeId = 2;
Greg Fischerbba812f2017-05-04 20:55:53 -060028static const int kSpvLoopMergeMergeBlockId = 0;
David Netoefff5fa2017-08-31 15:47:31 -040029static const int kSpvLoopMergeContinueTargetIdInIdx = 1;
Greg Fischerbba812f2017-05-04 20:55:53 -060030static const int kSpvSelectionMergeMergeBlockId = 0;
Greg Fischer04fcc662016-11-10 10:11:50 -070031
32namespace spvtools {
33namespace opt {
34
35uint32_t InlinePass::FindPointerToType(uint32_t type_id,
36 SpvStorageClass storage_class) {
37 ir::Module::inst_iterator type_itr = module_->types_values_begin();
38 for (; type_itr != module_->types_values_end(); ++type_itr) {
39 const ir::Instruction* type_inst = &*type_itr;
40 if (type_inst->opcode() == SpvOpTypePointer &&
41 type_inst->GetSingleWordOperand(kSpvTypePointerTypeId) == type_id &&
42 type_inst->GetSingleWordOperand(kSpvTypePointerStorageClass) ==
43 storage_class)
44 return type_inst->result_id();
45 }
46 return 0;
47}
48
49uint32_t InlinePass::AddPointerToType(uint32_t type_id,
50 SpvStorageClass storage_class) {
51 uint32_t resultId = TakeNextId();
52 std::unique_ptr<ir::Instruction> type_inst(new ir::Instruction(
53 SpvOpTypePointer, 0, resultId,
54 {{spv_operand_type_t::SPV_OPERAND_TYPE_STORAGE_CLASS,
55 {uint32_t(storage_class)}},
56 {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {type_id}}}));
57 module_->AddType(std::move(type_inst));
58 return resultId;
59}
60
61void InlinePass::AddBranch(uint32_t label_id,
Greg Fischerbba812f2017-05-04 20:55:53 -060062 std::unique_ptr<ir::BasicBlock>* block_ptr) {
Greg Fischer04fcc662016-11-10 10:11:50 -070063 std::unique_ptr<ir::Instruction> newBranch(new ir::Instruction(
Greg Fischerbba812f2017-05-04 20:55:53 -060064 SpvOpBranch, 0, 0,
65 {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {label_id}}}));
Greg Fischer04fcc662016-11-10 10:11:50 -070066 (*block_ptr)->AddInstruction(std::move(newBranch));
67}
68
Greg Fischerbba812f2017-05-04 20:55:53 -060069void InlinePass::AddBranchCond(uint32_t cond_id, uint32_t true_id,
70 uint32_t false_id, std::unique_ptr<ir::BasicBlock>* block_ptr) {
71 std::unique_ptr<ir::Instruction> newBranch(new ir::Instruction(
72 SpvOpBranchConditional, 0, 0,
73 {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {cond_id}},
74 {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {true_id}},
75 {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {false_id}}}));
76 (*block_ptr)->AddInstruction(std::move(newBranch));
77}
78
79void InlinePass::AddLoopMerge(uint32_t merge_id, uint32_t continue_id,
80 std::unique_ptr<ir::BasicBlock>* block_ptr) {
81 std::unique_ptr<ir::Instruction> newLoopMerge(new ir::Instruction(
82 SpvOpLoopMerge, 0, 0,
83 {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {merge_id}},
84 {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {continue_id}},
85 {spv_operand_type_t::SPV_OPERAND_TYPE_LOOP_CONTROL, {0}}}));
86 (*block_ptr)->AddInstruction(std::move(newLoopMerge));
87}
88
Greg Fischer04fcc662016-11-10 10:11:50 -070089void InlinePass::AddStore(uint32_t ptr_id, uint32_t val_id,
90 std::unique_ptr<ir::BasicBlock>* block_ptr) {
91 std::unique_ptr<ir::Instruction> newStore(new ir::Instruction(
92 SpvOpStore, 0, 0, {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {ptr_id}},
93 {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {val_id}}}));
94 (*block_ptr)->AddInstruction(std::move(newStore));
95}
96
97void InlinePass::AddLoad(uint32_t type_id, uint32_t resultId, uint32_t ptr_id,
98 std::unique_ptr<ir::BasicBlock>* block_ptr) {
99 std::unique_ptr<ir::Instruction> newLoad(new ir::Instruction(
100 SpvOpLoad, type_id, resultId,
101 {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {ptr_id}}}));
102 (*block_ptr)->AddInstruction(std::move(newLoad));
103}
104
105std::unique_ptr<ir::Instruction> InlinePass::NewLabel(uint32_t label_id) {
106 std::unique_ptr<ir::Instruction> newLabel(
107 new ir::Instruction(SpvOpLabel, 0, label_id, {}));
108 return newLabel;
109}
110
Greg Fischerbba812f2017-05-04 20:55:53 -0600111uint32_t InlinePass::GetFalseId() {
112 if (false_id_ != 0)
113 return false_id_;
114 false_id_ = module_->GetGlobalValue(SpvOpConstantFalse);
115 if (false_id_ != 0)
116 return false_id_;
117 uint32_t boolId = module_->GetGlobalValue(SpvOpTypeBool);
118 if (boolId == 0) {
119 boolId = TakeNextId();
120 module_->AddGlobalValue(SpvOpTypeBool, boolId, 0);
121 }
122 false_id_ = TakeNextId();
123 module_->AddGlobalValue(SpvOpConstantFalse, false_id_, boolId);
124 return false_id_;
125}
126
Greg Fischer04fcc662016-11-10 10:11:50 -0700127void InlinePass::MapParams(
128 ir::Function* calleeFn,
129 ir::UptrVectorIterator<ir::Instruction> call_inst_itr,
130 std::unordered_map<uint32_t, uint32_t>* callee2caller) {
131 int param_idx = 0;
132 calleeFn->ForEachParam(
133 [&call_inst_itr, &param_idx, &callee2caller](const ir::Instruction* cpi) {
134 const uint32_t pid = cpi->result_id();
135 (*callee2caller)[pid] = call_inst_itr->GetSingleWordOperand(
136 kSpvFunctionCallArgumentId + param_idx);
Greg Fischerbba812f2017-05-04 20:55:53 -0600137 ++param_idx;
Greg Fischer04fcc662016-11-10 10:11:50 -0700138 });
139}
140
141void InlinePass::CloneAndMapLocals(
142 ir::Function* calleeFn,
143 std::vector<std::unique_ptr<ir::Instruction>>* new_vars,
144 std::unordered_map<uint32_t, uint32_t>* callee2caller) {
145 auto callee_block_itr = calleeFn->begin();
146 auto callee_var_itr = callee_block_itr->begin();
147 while (callee_var_itr->opcode() == SpvOp::SpvOpVariable) {
148 std::unique_ptr<ir::Instruction> var_inst(
149 new ir::Instruction(*callee_var_itr));
150 uint32_t newId = TakeNextId();
151 var_inst->SetResultId(newId);
152 (*callee2caller)[callee_var_itr->result_id()] = newId;
153 new_vars->push_back(std::move(var_inst));
Greg Fischerbba812f2017-05-04 20:55:53 -0600154 ++callee_var_itr;
Greg Fischer04fcc662016-11-10 10:11:50 -0700155 }
156}
157
158uint32_t InlinePass::CreateReturnVar(
159 ir::Function* calleeFn,
160 std::vector<std::unique_ptr<ir::Instruction>>* new_vars) {
161 uint32_t returnVarId = 0;
162 const uint32_t calleeTypeId = calleeFn->type_id();
163 const ir::Instruction* calleeType =
164 def_use_mgr_->id_to_defs().find(calleeTypeId)->second;
165 if (calleeType->opcode() != SpvOpTypeVoid) {
166 // Find or create ptr to callee return type.
167 uint32_t returnVarTypeId =
168 FindPointerToType(calleeTypeId, SpvStorageClassFunction);
169 if (returnVarTypeId == 0)
170 returnVarTypeId = AddPointerToType(calleeTypeId, SpvStorageClassFunction);
171 // Add return var to new function scope variables.
172 returnVarId = TakeNextId();
173 std::unique_ptr<ir::Instruction> var_inst(new ir::Instruction(
174 SpvOpVariable, returnVarTypeId, returnVarId,
175 {{spv_operand_type_t::SPV_OPERAND_TYPE_STORAGE_CLASS,
176 {SpvStorageClassFunction}}}));
177 new_vars->push_back(std::move(var_inst));
178 }
179 return returnVarId;
180}
181
182bool InlinePass::IsSameBlockOp(const ir::Instruction* inst) const {
183 return inst->opcode() == SpvOpSampledImage || inst->opcode() == SpvOpImage;
184}
185
186void InlinePass::CloneSameBlockOps(
187 std::unique_ptr<ir::Instruction>* inst,
188 std::unordered_map<uint32_t, uint32_t>* postCallSB,
189 std::unordered_map<uint32_t, ir::Instruction*>* preCallSB,
190 std::unique_ptr<ir::BasicBlock>* block_ptr) {
191 (*inst)
192 ->ForEachInId([&postCallSB, &preCallSB, &block_ptr, this](uint32_t* iid) {
193 const auto mapItr = (*postCallSB).find(*iid);
194 if (mapItr == (*postCallSB).end()) {
195 const auto mapItr2 = (*preCallSB).find(*iid);
196 if (mapItr2 != (*preCallSB).end()) {
197 // Clone pre-call same-block ops, map result id.
198 const ir::Instruction* inInst = mapItr2->second;
199 std::unique_ptr<ir::Instruction> sb_inst(
200 new ir::Instruction(*inInst));
201 CloneSameBlockOps(&sb_inst, postCallSB, preCallSB, block_ptr);
202 const uint32_t rid = sb_inst->result_id();
203 const uint32_t nid = this->TakeNextId();
204 sb_inst->SetResultId(nid);
205 (*postCallSB)[rid] = nid;
206 *iid = nid;
207 (*block_ptr)->AddInstruction(std::move(sb_inst));
208 }
209 } else {
210 // Reset same-block op operand.
211 *iid = mapItr->second;
212 }
213 });
214}
215
216void InlinePass::GenInlineCode(
217 std::vector<std::unique_ptr<ir::BasicBlock>>* new_blocks,
218 std::vector<std::unique_ptr<ir::Instruction>>* new_vars,
219 ir::UptrVectorIterator<ir::Instruction> call_inst_itr,
220 ir::UptrVectorIterator<ir::BasicBlock> call_block_itr) {
221 // Map from all ids in the callee to their equivalent id in the caller
222 // as callee instructions are copied into caller.
223 std::unordered_map<uint32_t, uint32_t> callee2caller;
224 // Pre-call same-block insts
225 std::unordered_map<uint32_t, ir::Instruction*> preCallSB;
226 // Post-call same-block op ids
227 std::unordered_map<uint32_t, uint32_t> postCallSB;
228
229 ir::Function* calleeFn = id2function_[call_inst_itr->GetSingleWordOperand(
230 kSpvFunctionCallFunctionId)];
231
David Neto2a1014b2017-08-09 14:59:04 -0400232 // Check for multiple returns in the callee.
233 auto fi = multi_return_funcs_.find(calleeFn->result_id());
234 const bool multiReturn = fi != multi_return_funcs_.end();
Greg Fischerbba812f2017-05-04 20:55:53 -0600235
Greg Fischer04fcc662016-11-10 10:11:50 -0700236 // Map parameters to actual arguments.
237 MapParams(calleeFn, call_inst_itr, &callee2caller);
238
239 // Define caller local variables for all callee variables and create map to
240 // them.
241 CloneAndMapLocals(calleeFn, new_vars, &callee2caller);
242
243 // Create return var if needed.
244 uint32_t returnVarId = CreateReturnVar(calleeFn, new_vars);
245
GregFa699d1a2017-08-29 18:35:05 -0600246 // Create set of callee result ids. Used to detect forward references
247 std::unordered_set<uint32_t> callee_result_ids;
248 calleeFn->ForEachInst([&callee_result_ids](
249 const ir::Instruction* cpi) {
250 const uint32_t rid = cpi->result_id();
251 if (rid != 0)
252 callee_result_ids.insert(rid);
253 });
254
David Netoefff5fa2017-08-31 15:47:31 -0400255 // If the caller is in a single-block loop, and the callee has multiple
256 // blocks, then the normal inlining logic will place the OpLoopMerge in
257 // the last of several blocks in the loop. Instead, it should be placed
258 // at the end of the first block. First determine if the caller is in a
259 // single block loop. We'll wait to move the OpLoopMerge until the end
260 // of the regular inlining logic, and only if necessary.
261 bool caller_is_single_block_loop = false;
262 if (auto* loop_merge = call_block_itr->GetLoopMergeInst()) {
263 caller_is_single_block_loop =
264 call_block_itr->id() ==
265 loop_merge->GetSingleWordInOperand(kSpvLoopMergeContinueTargetIdInIdx);
266 }
267
268 bool callee_begins_with_structured_header =
269 (*(calleeFn->begin())).GetMergeInst() != nullptr;
270
Greg Fischer04fcc662016-11-10 10:11:50 -0700271 // Clone and map callee code. Copy caller block code to beginning of
272 // first block and end of last block.
273 bool prevInstWasReturn = false;
Greg Fischerbba812f2017-05-04 20:55:53 -0600274 uint32_t singleTripLoopHeaderId = 0;
275 uint32_t singleTripLoopContinueId = 0;
Greg Fischer04fcc662016-11-10 10:11:50 -0700276 uint32_t returnLabelId = 0;
277 bool multiBlocks = false;
278 const uint32_t calleeTypeId = calleeFn->type_id();
David Neto2a1014b2017-08-09 14:59:04 -0400279 // new_blk_ptr is a new basic block in the caller. New instructions are
280 // written to it. It is created when we encounter the OpLabel
David Netoefff5fa2017-08-31 15:47:31 -0400281 // of the first callee block. It is appended to new_blocks only when
282 // it is complete.
Greg Fischer04fcc662016-11-10 10:11:50 -0700283 std::unique_ptr<ir::BasicBlock> new_blk_ptr;
284 calleeFn->ForEachInst([&new_blocks, &callee2caller, &call_block_itr,
285 &call_inst_itr, &new_blk_ptr, &prevInstWasReturn,
David Netoefff5fa2017-08-31 15:47:31 -0400286 &returnLabelId, &returnVarId,
287 caller_is_single_block_loop,
288 callee_begins_with_structured_header, &calleeTypeId,
David Neto2a1014b2017-08-09 14:59:04 -0400289 &multiBlocks, &postCallSB, &preCallSB, multiReturn,
Greg Fischerbba812f2017-05-04 20:55:53 -0600290 &singleTripLoopHeaderId, &singleTripLoopContinueId,
David Netoefff5fa2017-08-31 15:47:31 -0400291 &callee_result_ids, this](const ir::Instruction* cpi) {
Greg Fischer04fcc662016-11-10 10:11:50 -0700292 switch (cpi->opcode()) {
293 case SpvOpFunction:
294 case SpvOpFunctionParameter:
295 case SpvOpVariable:
296 // Already processed
297 break;
298 case SpvOpLabel: {
299 // If previous instruction was early return, insert branch
300 // instruction to return block.
301 if (prevInstWasReturn) {
302 if (returnLabelId == 0) returnLabelId = this->TakeNextId();
303 AddBranch(returnLabelId, &new_blk_ptr);
304 prevInstWasReturn = false;
305 }
306 // Finish current block (if it exists) and get label for next block.
307 uint32_t labelId;
308 bool firstBlock = false;
309 if (new_blk_ptr != nullptr) {
310 new_blocks->push_back(std::move(new_blk_ptr));
311 // If result id is already mapped, use it, otherwise get a new
312 // one.
313 const uint32_t rid = cpi->result_id();
314 const auto mapItr = callee2caller.find(rid);
315 labelId = (mapItr != callee2caller.end()) ? mapItr->second
316 : this->TakeNextId();
317 } else {
318 // First block needs to use label of original block
319 // but map callee label in case of phi reference.
Greg Fischerbba812f2017-05-04 20:55:53 -0600320 labelId = call_block_itr->id();
Greg Fischer04fcc662016-11-10 10:11:50 -0700321 callee2caller[cpi->result_id()] = labelId;
322 firstBlock = true;
323 }
324 // Create first/next block.
325 new_blk_ptr.reset(new ir::BasicBlock(NewLabel(labelId)));
326 if (firstBlock) {
327 // Copy contents of original caller block up to call instruction.
328 for (auto cii = call_block_itr->begin(); cii != call_inst_itr;
Greg Fischerbba812f2017-05-04 20:55:53 -0600329 ++cii) {
Greg Fischer04fcc662016-11-10 10:11:50 -0700330 std::unique_ptr<ir::Instruction> cp_inst(new ir::Instruction(*cii));
331 // Remember same-block ops for possible regeneration.
332 if (IsSameBlockOp(&*cp_inst)) {
333 auto* sb_inst_ptr = cp_inst.get();
334 preCallSB[cp_inst->result_id()] = sb_inst_ptr;
335 }
336 new_blk_ptr->AddInstruction(std::move(cp_inst));
337 }
David Netoefff5fa2017-08-31 15:47:31 -0400338 if (caller_is_single_block_loop &&
339 callee_begins_with_structured_header) {
340 // We can't place both the caller's merge instruction and another
341 // merge instruction in the same block. So split the calling block.
342 // Insert an unconditional branch to a new guard block. Later,
343 // once we know the ID of the last block, we will move the caller's
344 // OpLoopMerge from the last generated block into the first block.
345 // We also wait to avoid invalidating various iterators.
346 const auto guard_block_id = this->TakeNextId();
347 AddBranch(guard_block_id, &new_blk_ptr);
348 new_blocks->push_back(std::move(new_blk_ptr));
349 // Start the next block.
350 new_blk_ptr.reset(new ir::BasicBlock(NewLabel(guard_block_id)));
351 // Reset the mapping of the callee's entry block to point to
352 // the guard block. Do this so we can fix up phis later on to
353 // satisfy dominance.
354 callee2caller[cpi->result_id()] = guard_block_id;
355 }
356 // If callee has multiple returns, insert a header block for
David Neto2a1014b2017-08-09 14:59:04 -0400357 // single-trip loop that will encompass callee code. Start postheader
Greg Fischerbba812f2017-05-04 20:55:53 -0600358 // block.
David Netoefff5fa2017-08-31 15:47:31 -0400359 //
360 // Note: Consider the following combination:
361 // - the caller is a single block loop
362 // - the callee does not begin with a structure header
363 // - the callee has multiple returns.
364 // We still need to split the caller block and insert a guard block.
365 // But we only need to do it once. We haven't done it yet, but the
366 // single-trip loop header will serve the same purpose.
David Neto2a1014b2017-08-09 14:59:04 -0400367 if (multiReturn) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600368 singleTripLoopHeaderId = this->TakeNextId();
369 AddBranch(singleTripLoopHeaderId, &new_blk_ptr);
370 new_blocks->push_back(std::move(new_blk_ptr));
371 new_blk_ptr.reset(new ir::BasicBlock(NewLabel(
372 singleTripLoopHeaderId)));
373 returnLabelId = this->TakeNextId();
374 singleTripLoopContinueId = this->TakeNextId();
375 AddLoopMerge(returnLabelId, singleTripLoopContinueId, &new_blk_ptr);
376 uint32_t postHeaderId = this->TakeNextId();
377 AddBranch(postHeaderId, &new_blk_ptr);
378 new_blocks->push_back(std::move(new_blk_ptr));
379 new_blk_ptr.reset(new ir::BasicBlock(NewLabel(postHeaderId)));
380 multiBlocks = true;
381 }
Greg Fischer04fcc662016-11-10 10:11:50 -0700382 } else {
383 multiBlocks = true;
384 }
385 } break;
386 case SpvOpReturnValue: {
387 // Store return value to return variable.
388 assert(returnVarId != 0);
389 uint32_t valId = cpi->GetInOperand(kSpvReturnValueId).words[0];
390 const auto mapItr = callee2caller.find(valId);
391 if (mapItr != callee2caller.end()) {
392 valId = mapItr->second;
393 }
394 AddStore(returnVarId, valId, &new_blk_ptr);
395
396 // Remember we saw a return; if followed by a label, will need to
397 // insert branch.
398 prevInstWasReturn = true;
399 } break;
400 case SpvOpReturn: {
401 // Remember we saw a return; if followed by a label, will need to
402 // insert branch.
403 prevInstWasReturn = true;
404 } break;
405 case SpvOpFunctionEnd: {
David Neto2a1014b2017-08-09 14:59:04 -0400406 // If there was an early return, we generated a return label id
407 // for it. Now we have to generate the return block with that Id.
Greg Fischer04fcc662016-11-10 10:11:50 -0700408 if (returnLabelId != 0) {
David Neto2a1014b2017-08-09 14:59:04 -0400409 // If previous instruction was return, insert branch instruction
410 // to return block.
Greg Fischer04fcc662016-11-10 10:11:50 -0700411 if (prevInstWasReturn) AddBranch(returnLabelId, &new_blk_ptr);
David Neto2a1014b2017-08-09 14:59:04 -0400412 if (multiReturn) {
413 // If we generated a loop header to for the single-trip loop
414 // to accommodate multiple returns, insert the continue
415 // target block now, with a false branch back to the loop header.
416 new_blocks->push_back(std::move(new_blk_ptr));
417 new_blk_ptr.reset(
418 new ir::BasicBlock(NewLabel(singleTripLoopContinueId)));
419 AddBranchCond(GetFalseId(), singleTripLoopHeaderId, returnLabelId,
420 &new_blk_ptr);
421 }
422 // Generate the return block.
Greg Fischerbba812f2017-05-04 20:55:53 -0600423 new_blocks->push_back(std::move(new_blk_ptr));
Greg Fischer04fcc662016-11-10 10:11:50 -0700424 new_blk_ptr.reset(new ir::BasicBlock(NewLabel(returnLabelId)));
425 multiBlocks = true;
426 }
427 // Load return value into result id of call, if it exists.
428 if (returnVarId != 0) {
429 const uint32_t resId = call_inst_itr->result_id();
430 assert(resId != 0);
431 AddLoad(calleeTypeId, resId, returnVarId, &new_blk_ptr);
432 }
433 // Copy remaining instructions from caller block.
434 auto cii = call_inst_itr;
Greg Fischerbba812f2017-05-04 20:55:53 -0600435 for (++cii; cii != call_block_itr->end(); ++cii) {
Greg Fischer04fcc662016-11-10 10:11:50 -0700436 std::unique_ptr<ir::Instruction> cp_inst(new ir::Instruction(*cii));
437 // If multiple blocks generated, regenerate any same-block
438 // instruction that has not been seen in this last block.
439 if (multiBlocks) {
440 CloneSameBlockOps(&cp_inst, &postCallSB, &preCallSB, &new_blk_ptr);
441 // Remember same-block ops in this block.
442 if (IsSameBlockOp(&*cp_inst)) {
443 const uint32_t rid = cp_inst->result_id();
444 postCallSB[rid] = rid;
445 }
446 }
447 new_blk_ptr->AddInstruction(std::move(cp_inst));
448 }
449 // Finalize inline code.
450 new_blocks->push_back(std::move(new_blk_ptr));
451 } break;
452 default: {
453 // Copy callee instruction and remap all input Ids.
454 std::unique_ptr<ir::Instruction> cp_inst(new ir::Instruction(*cpi));
David Netoefff5fa2017-08-31 15:47:31 -0400455 cp_inst->ForEachInId([&callee2caller, &callee_result_ids,
456 this](uint32_t* iid) {
Greg Fischer04fcc662016-11-10 10:11:50 -0700457 const auto mapItr = callee2caller.find(*iid);
458 if (mapItr != callee2caller.end()) {
459 *iid = mapItr->second;
GregFa699d1a2017-08-29 18:35:05 -0600460 } else if (callee_result_ids.find(*iid) != callee_result_ids.end()) {
461 // Forward reference. Allocate a new id, map it,
462 // use it and check for it when remapping result ids
463 const uint32_t nid = this->TakeNextId();
464 callee2caller[*iid] = nid;
465 *iid = nid;
Greg Fischer04fcc662016-11-10 10:11:50 -0700466 }
467 });
GregFa699d1a2017-08-29 18:35:05 -0600468 // If result id is non-zero, remap it. If already mapped, use mapped
469 // value, else use next id.
Greg Fischer04fcc662016-11-10 10:11:50 -0700470 const uint32_t rid = cp_inst->result_id();
471 if (rid != 0) {
GregFa699d1a2017-08-29 18:35:05 -0600472 const auto mapItr = callee2caller.find(rid);
473 uint32_t nid;
474 if (mapItr != callee2caller.end()) {
475 nid = mapItr->second;
476 }
477 else {
478 nid = this->TakeNextId();
479 callee2caller[rid] = nid;
480 }
Greg Fischer04fcc662016-11-10 10:11:50 -0700481 cp_inst->SetResultId(nid);
482 }
483 new_blk_ptr->AddInstruction(std::move(cp_inst));
484 } break;
485 }
486 });
David Netoefff5fa2017-08-31 15:47:31 -0400487
488 if (caller_is_single_block_loop && (new_blocks->size() > 1)) {
489 // Move the OpLoopMerge from the last block back to the first, where
490 // it belongs. Also, update its continue target to point to the last
491 // block.
492 auto& first = new_blocks->front();
493 auto& last = new_blocks->back();
494 assert(first != last);
495
496 // Insert a modified copy of the loop merge into the first block.
497 auto loop_merge_itr = last->tail();
498 --loop_merge_itr;
499 assert(loop_merge_itr->opcode() == SpvOpLoopMerge);
500 std::unique_ptr<ir::Instruction> cp_inst(new ir::Instruction(*loop_merge_itr));
501 cp_inst->SetInOperand(kSpvLoopMergeContinueTargetIdInIdx, {last->id()});
502 first->tail().InsertBefore(std::move(cp_inst));
503
504 // Remove the loop merge from the last block.
505 loop_merge_itr.Erase();
506 }
507
Greg Fischer04fcc662016-11-10 10:11:50 -0700508 // Update block map given replacement blocks.
509 for (auto& blk : *new_blocks) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600510 id2block_[blk->id()] = &*blk;
Greg Fischer04fcc662016-11-10 10:11:50 -0700511 }
512}
513
David Netoceb1d4f2017-03-31 10:36:58 -0400514bool InlinePass::IsInlinableFunctionCall(const ir::Instruction* inst) {
515 if (inst->opcode() != SpvOp::SpvOpFunctionCall) return false;
GregFa107d342017-04-25 13:57:20 -0600516 const uint32_t calleeFnId =
517 inst->GetSingleWordOperand(kSpvFunctionCallFunctionId);
518 const auto ci = inlinable_.find(calleeFnId);
519 return ci != inlinable_.cend();
David Netoceb1d4f2017-03-31 10:36:58 -0400520}
521
GregFe28bd392017-08-01 17:20:13 -0600522void InlinePass::UpdateSucceedingPhis(
523 std::vector<std::unique_ptr<ir::BasicBlock>>& new_blocks) {
524 const auto firstBlk = new_blocks.begin();
525 const auto lastBlk = new_blocks.end() - 1;
526 const uint32_t firstId = (*firstBlk)->id();
527 const uint32_t lastId = (*lastBlk)->id();
528 (*lastBlk)->ForEachSuccessorLabel(
529 [&firstId, &lastId, this](uint32_t succ) {
530 ir::BasicBlock* sbp = this->id2block_[succ];
531 sbp->ForEachPhiInst([&firstId, &lastId](ir::Instruction* phi) {
532 phi->ForEachInId([&firstId, &lastId](uint32_t* id) {
533 if (*id == firstId) *id = lastId;
534 });
535 });
536 });
Greg Fischer04fcc662016-11-10 10:11:50 -0700537}
538
Greg Fischerbba812f2017-05-04 20:55:53 -0600539bool InlinePass::HasMultipleReturns(ir::Function* func) {
540 bool seenReturn = false;
541 bool multipleReturns = false;
542 for (auto& blk : *func) {
543 auto terminal_ii = blk.cend();
544 --terminal_ii;
545 if (terminal_ii->opcode() == SpvOpReturn ||
546 terminal_ii->opcode() == SpvOpReturnValue) {
547 if (seenReturn) {
548 multipleReturns = true;
549 break;
550 }
551 seenReturn = true;
552 }
553 }
554 return multipleReturns;
555}
556
557uint32_t InlinePass::MergeBlockIdIfAny(const ir::BasicBlock& blk) {
558 auto merge_ii = blk.cend();
559 --merge_ii;
560 uint32_t mbid = 0;
561 if (merge_ii != blk.cbegin()) {
562 --merge_ii;
563 if (merge_ii->opcode() == SpvOpLoopMerge)
564 mbid = merge_ii->GetSingleWordOperand(kSpvLoopMergeMergeBlockId);
565 else if (merge_ii->opcode() == SpvOpSelectionMerge)
566 mbid = merge_ii->GetSingleWordOperand(kSpvSelectionMergeMergeBlockId);
567 }
568 return mbid;
569}
570
571void InlinePass::ComputeStructuredSuccessors(ir::Function* func) {
572 // If header, make merge block first successor.
573 for (auto& blk : *func) {
574 uint32_t mbid = MergeBlockIdIfAny(blk);
575 if (mbid != 0)
576 block2structured_succs_[&blk].push_back(id2block_[mbid]);
577 // add true successors
578 blk.ForEachSuccessorLabel([&blk, this](uint32_t sbid) {
579 block2structured_succs_[&blk].push_back(id2block_[sbid]);
580 });
581 }
582}
583
584InlinePass::GetBlocksFunction InlinePass::StructuredSuccessorsFunction() {
585 return [this](const ir::BasicBlock* block) {
586 return &(block2structured_succs_[block]);
587 };
588}
589
590bool InlinePass::HasNoReturnInLoop(ir::Function* func) {
591 // If control not structured, do not do loop/return analysis
592 // TODO: Analyze returns in non-structured control flow
593 if (!module_->HasCapability(SpvCapabilityShader))
594 return false;
595 // Compute structured block order. This order has the property
596 // that dominators are before all blocks they dominate and merge blocks
597 // are after all blocks that are in the control constructs of their header.
598 ComputeStructuredSuccessors(func);
599 auto ignore_block = [](cbb_ptr) {};
600 auto ignore_edge = [](cbb_ptr, cbb_ptr) {};
601 std::list<const ir::BasicBlock*> structuredOrder;
602 spvtools::CFA<ir::BasicBlock>::DepthFirstTraversal(
603 &*func->begin(), StructuredSuccessorsFunction(), ignore_block,
604 [&](cbb_ptr b) { structuredOrder.push_front(b); }, ignore_edge);
605 // Search for returns in loops. Only need to track outermost loop
606 bool return_in_loop = false;
607 uint32_t outerLoopMergeId = 0;
608 for (auto& blk : structuredOrder) {
609 // Exiting current outer loop
610 if (blk->id() == outerLoopMergeId)
611 outerLoopMergeId = 0;
612 // Return block
613 auto terminal_ii = blk->cend();
614 --terminal_ii;
615 if (terminal_ii->opcode() == SpvOpReturn ||
616 terminal_ii->opcode() == SpvOpReturnValue) {
617 if (outerLoopMergeId != 0) {
618 return_in_loop = true;
619 break;
620 }
621 }
622 else if (terminal_ii != blk->cbegin()) {
623 auto merge_ii = terminal_ii;
624 --merge_ii;
625 // Entering outermost loop
626 if (merge_ii->opcode() == SpvOpLoopMerge && outerLoopMergeId == 0)
627 outerLoopMergeId = merge_ii->GetSingleWordOperand(
628 kSpvLoopMergeMergeBlockId);
629 }
630 }
631 return !return_in_loop;
632}
633
634void InlinePass::AnalyzeReturns(ir::Function* func) {
635 // Look for multiple returns
636 if (!HasMultipleReturns(func)) {
637 no_return_in_loop_.insert(func->result_id());
638 return;
639 }
David Neto2a1014b2017-08-09 14:59:04 -0400640 multi_return_funcs_.insert(func->result_id());
Greg Fischerbba812f2017-05-04 20:55:53 -0600641 // If multiple returns, see if any are in a loop
642 if (HasNoReturnInLoop(func))
643 no_return_in_loop_.insert(func->result_id());
644}
645
646bool InlinePass::IsInlinableFunction(ir::Function* func) {
GregFa107d342017-04-25 13:57:20 -0600647 // We can only inline a function if it has blocks.
648 if (func->cbegin() == func->cend())
649 return false;
Greg Fischerbba812f2017-05-04 20:55:53 -0600650 // Do not inline functions with returns in loops. Currently early return
651 // functions are inlined by wrapping them in a one trip loop and implementing
652 // the returns as a branch to the loop's merge block. However, this can only
653 // done validly if the return was not in a loop in the original function.
654 // Also remember functions with multiple (early) returns.
655 AnalyzeReturns(func);
David Netoefff5fa2017-08-31 15:47:31 -0400656 return no_return_in_loop_.find(func->result_id()) !=
657 no_return_in_loop_.cend();
GregFa107d342017-04-25 13:57:20 -0600658}
659
GregFe28bd392017-08-01 17:20:13 -0600660void InlinePass::InitializeInline(ir::Module* module) {
Greg Fischer04fcc662016-11-10 10:11:50 -0700661 def_use_mgr_.reset(new analysis::DefUseManager(consumer(), module));
662
663 // Initialize next unused Id.
664 next_id_ = module->id_bound();
665
666 // Save module.
667 module_ = module;
668
Greg Fischerbba812f2017-05-04 20:55:53 -0600669 false_id_ = 0;
670
GregFe28bd392017-08-01 17:20:13 -0600671 // clear collections
Greg Fischer04fcc662016-11-10 10:11:50 -0700672 id2function_.clear();
673 id2block_.clear();
Greg Fischerbba812f2017-05-04 20:55:53 -0600674 block2structured_succs_.clear();
GregFa107d342017-04-25 13:57:20 -0600675 inlinable_.clear();
GregFe28bd392017-08-01 17:20:13 -0600676 no_return_in_loop_.clear();
David Neto2a1014b2017-08-09 14:59:04 -0400677 multi_return_funcs_.clear();
GregFe28bd392017-08-01 17:20:13 -0600678
Greg Fischer04fcc662016-11-10 10:11:50 -0700679 for (auto& fn : *module_) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600680 // Initialize function and block maps.
Greg Fischer04fcc662016-11-10 10:11:50 -0700681 id2function_[fn.result_id()] = &fn;
682 for (auto& blk : fn) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600683 id2block_[blk.id()] = &blk;
Greg Fischer04fcc662016-11-10 10:11:50 -0700684 }
Greg Fischerbba812f2017-05-04 20:55:53 -0600685 // Compute inlinability
GregFa107d342017-04-25 13:57:20 -0600686 if (IsInlinableFunction(&fn))
687 inlinable_.insert(fn.result_id());
Greg Fischer04fcc662016-11-10 10:11:50 -0700688 }
689};
690
Greg Fischer04fcc662016-11-10 10:11:50 -0700691
692InlinePass::InlinePass()
693 : module_(nullptr), def_use_mgr_(nullptr), next_id_(0) {}
694
Greg Fischer04fcc662016-11-10 10:11:50 -0700695} // namespace opt
696} // namespace spvtools