blob: 926c980deeeb6f1b33158de57b81e5fdc8ea0580 [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,
Steven Perronbb7802b2017-10-13 14:25:21 -0400129 ir::BasicBlock::iterator call_inst_itr,
Greg Fischer04fcc662016-11-10 10:11:50 -0700130 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) {
Steven Perronbb7802b2017-10-13 14:25:21 -0400148 std::unique_ptr<ir::Instruction> var_inst(callee_var_itr->Clone());
Greg Fischer04fcc662016-11-10 10:11:50 -0700149 uint32_t newId = TakeNextId();
150 var_inst->SetResultId(newId);
151 (*callee2caller)[callee_var_itr->result_id()] = newId;
152 new_vars->push_back(std::move(var_inst));
Greg Fischerbba812f2017-05-04 20:55:53 -0600153 ++callee_var_itr;
Greg Fischer04fcc662016-11-10 10:11:50 -0700154 }
155}
156
157uint32_t InlinePass::CreateReturnVar(
158 ir::Function* calleeFn,
159 std::vector<std::unique_ptr<ir::Instruction>>* new_vars) {
160 uint32_t returnVarId = 0;
161 const uint32_t calleeTypeId = calleeFn->type_id();
162 const ir::Instruction* calleeType =
163 def_use_mgr_->id_to_defs().find(calleeTypeId)->second;
164 if (calleeType->opcode() != SpvOpTypeVoid) {
165 // Find or create ptr to callee return type.
166 uint32_t returnVarTypeId =
167 FindPointerToType(calleeTypeId, SpvStorageClassFunction);
168 if (returnVarTypeId == 0)
169 returnVarTypeId = AddPointerToType(calleeTypeId, SpvStorageClassFunction);
170 // Add return var to new function scope variables.
171 returnVarId = TakeNextId();
172 std::unique_ptr<ir::Instruction> var_inst(new ir::Instruction(
173 SpvOpVariable, returnVarTypeId, returnVarId,
174 {{spv_operand_type_t::SPV_OPERAND_TYPE_STORAGE_CLASS,
175 {SpvStorageClassFunction}}}));
176 new_vars->push_back(std::move(var_inst));
177 }
178 return returnVarId;
179}
180
181bool InlinePass::IsSameBlockOp(const ir::Instruction* inst) const {
182 return inst->opcode() == SpvOpSampledImage || inst->opcode() == SpvOpImage;
183}
184
185void InlinePass::CloneSameBlockOps(
186 std::unique_ptr<ir::Instruction>* inst,
187 std::unordered_map<uint32_t, uint32_t>* postCallSB,
188 std::unordered_map<uint32_t, ir::Instruction*>* preCallSB,
189 std::unique_ptr<ir::BasicBlock>* block_ptr) {
190 (*inst)
191 ->ForEachInId([&postCallSB, &preCallSB, &block_ptr, this](uint32_t* iid) {
192 const auto mapItr = (*postCallSB).find(*iid);
193 if (mapItr == (*postCallSB).end()) {
194 const auto mapItr2 = (*preCallSB).find(*iid);
195 if (mapItr2 != (*preCallSB).end()) {
196 // Clone pre-call same-block ops, map result id.
197 const ir::Instruction* inInst = mapItr2->second;
Steven Perronbb7802b2017-10-13 14:25:21 -0400198 std::unique_ptr<ir::Instruction> sb_inst(inInst->Clone());
Greg Fischer04fcc662016-11-10 10:11:50 -0700199 CloneSameBlockOps(&sb_inst, postCallSB, preCallSB, block_ptr);
200 const uint32_t rid = sb_inst->result_id();
201 const uint32_t nid = this->TakeNextId();
202 sb_inst->SetResultId(nid);
203 (*postCallSB)[rid] = nid;
204 *iid = nid;
205 (*block_ptr)->AddInstruction(std::move(sb_inst));
206 }
207 } else {
208 // Reset same-block op operand.
209 *iid = mapItr->second;
210 }
211 });
212}
213
214void InlinePass::GenInlineCode(
215 std::vector<std::unique_ptr<ir::BasicBlock>>* new_blocks,
216 std::vector<std::unique_ptr<ir::Instruction>>* new_vars,
Steven Perronbb7802b2017-10-13 14:25:21 -0400217 ir::BasicBlock::iterator call_inst_itr,
Greg Fischer04fcc662016-11-10 10:11:50 -0700218 ir::UptrVectorIterator<ir::BasicBlock> call_block_itr) {
219 // Map from all ids in the callee to their equivalent id in the caller
220 // as callee instructions are copied into caller.
221 std::unordered_map<uint32_t, uint32_t> callee2caller;
222 // Pre-call same-block insts
223 std::unordered_map<uint32_t, ir::Instruction*> preCallSB;
224 // Post-call same-block op ids
225 std::unordered_map<uint32_t, uint32_t> postCallSB;
226
227 ir::Function* calleeFn = id2function_[call_inst_itr->GetSingleWordOperand(
228 kSpvFunctionCallFunctionId)];
229
David Neto2a1014b2017-08-09 14:59:04 -0400230 // Check for multiple returns in the callee.
231 auto fi = multi_return_funcs_.find(calleeFn->result_id());
232 const bool multiReturn = fi != multi_return_funcs_.end();
Greg Fischerbba812f2017-05-04 20:55:53 -0600233
Greg Fischer04fcc662016-11-10 10:11:50 -0700234 // Map parameters to actual arguments.
235 MapParams(calleeFn, call_inst_itr, &callee2caller);
236
237 // Define caller local variables for all callee variables and create map to
238 // them.
239 CloneAndMapLocals(calleeFn, new_vars, &callee2caller);
240
241 // Create return var if needed.
242 uint32_t returnVarId = CreateReturnVar(calleeFn, new_vars);
243
GregFa699d1a2017-08-29 18:35:05 -0600244 // Create set of callee result ids. Used to detect forward references
245 std::unordered_set<uint32_t> callee_result_ids;
246 calleeFn->ForEachInst([&callee_result_ids](
247 const ir::Instruction* cpi) {
248 const uint32_t rid = cpi->result_id();
249 if (rid != 0)
250 callee_result_ids.insert(rid);
251 });
252
David Netoefff5fa2017-08-31 15:47:31 -0400253 // If the caller is in a single-block loop, and the callee has multiple
254 // blocks, then the normal inlining logic will place the OpLoopMerge in
255 // the last of several blocks in the loop. Instead, it should be placed
256 // at the end of the first block. First determine if the caller is in a
257 // single block loop. We'll wait to move the OpLoopMerge until the end
258 // of the regular inlining logic, and only if necessary.
259 bool caller_is_single_block_loop = false;
David Neto25ddfec2017-09-02 19:01:03 -0400260 bool caller_is_loop_header = false;
David Netoefff5fa2017-08-31 15:47:31 -0400261 if (auto* loop_merge = call_block_itr->GetLoopMergeInst()) {
David Neto25ddfec2017-09-02 19:01:03 -0400262 caller_is_loop_header = true;
David Netoefff5fa2017-08-31 15:47:31 -0400263 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 Neto25ddfec2017-09-02 19:01:03 -0400286 &returnLabelId, &returnVarId, caller_is_loop_header,
David Netoefff5fa2017-08-31 15:47:31 -0400287 callee_begins_with_structured_header, &calleeTypeId,
David Neto2a1014b2017-08-09 14:59:04 -0400288 &multiBlocks, &postCallSB, &preCallSB, multiReturn,
Greg Fischerbba812f2017-05-04 20:55:53 -0600289 &singleTripLoopHeaderId, &singleTripLoopContinueId,
David Netoefff5fa2017-08-31 15:47:31 -0400290 &callee_result_ids, this](const ir::Instruction* cpi) {
Greg Fischer04fcc662016-11-10 10:11:50 -0700291 switch (cpi->opcode()) {
292 case SpvOpFunction:
293 case SpvOpFunctionParameter:
294 case SpvOpVariable:
295 // Already processed
296 break;
297 case SpvOpLabel: {
298 // If previous instruction was early return, insert branch
299 // instruction to return block.
300 if (prevInstWasReturn) {
301 if (returnLabelId == 0) returnLabelId = this->TakeNextId();
302 AddBranch(returnLabelId, &new_blk_ptr);
303 prevInstWasReturn = false;
304 }
305 // Finish current block (if it exists) and get label for next block.
306 uint32_t labelId;
307 bool firstBlock = false;
308 if (new_blk_ptr != nullptr) {
309 new_blocks->push_back(std::move(new_blk_ptr));
310 // If result id is already mapped, use it, otherwise get a new
311 // one.
312 const uint32_t rid = cpi->result_id();
313 const auto mapItr = callee2caller.find(rid);
314 labelId = (mapItr != callee2caller.end()) ? mapItr->second
315 : this->TakeNextId();
316 } else {
317 // First block needs to use label of original block
318 // but map callee label in case of phi reference.
Greg Fischerbba812f2017-05-04 20:55:53 -0600319 labelId = call_block_itr->id();
Greg Fischer04fcc662016-11-10 10:11:50 -0700320 callee2caller[cpi->result_id()] = labelId;
321 firstBlock = true;
322 }
323 // Create first/next block.
324 new_blk_ptr.reset(new ir::BasicBlock(NewLabel(labelId)));
325 if (firstBlock) {
326 // Copy contents of original caller block up to call instruction.
327 for (auto cii = call_block_itr->begin(); cii != call_inst_itr;
Greg Fischerbba812f2017-05-04 20:55:53 -0600328 ++cii) {
Steven Perronbb7802b2017-10-13 14:25:21 -0400329 std::unique_ptr<ir::Instruction> cp_inst(cii->Clone());
Greg Fischer04fcc662016-11-10 10:11:50 -0700330 // Remember same-block ops for possible regeneration.
331 if (IsSameBlockOp(&*cp_inst)) {
332 auto* sb_inst_ptr = cp_inst.get();
333 preCallSB[cp_inst->result_id()] = sb_inst_ptr;
334 }
335 new_blk_ptr->AddInstruction(std::move(cp_inst));
336 }
David Neto25ddfec2017-09-02 19:01:03 -0400337 if (caller_is_loop_header &&
David Netoefff5fa2017-08-31 15:47:31 -0400338 callee_begins_with_structured_header) {
339 // We can't place both the caller's merge instruction and another
340 // merge instruction in the same block. So split the calling block.
341 // Insert an unconditional branch to a new guard block. Later,
342 // once we know the ID of the last block, we will move the caller's
343 // OpLoopMerge from the last generated block into the first block.
344 // We also wait to avoid invalidating various iterators.
345 const auto guard_block_id = this->TakeNextId();
346 AddBranch(guard_block_id, &new_blk_ptr);
347 new_blocks->push_back(std::move(new_blk_ptr));
348 // Start the next block.
349 new_blk_ptr.reset(new ir::BasicBlock(NewLabel(guard_block_id)));
350 // Reset the mapping of the callee's entry block to point to
351 // the guard block. Do this so we can fix up phis later on to
352 // satisfy dominance.
353 callee2caller[cpi->result_id()] = guard_block_id;
354 }
355 // If callee has multiple returns, insert a header block for
David Neto2a1014b2017-08-09 14:59:04 -0400356 // single-trip loop that will encompass callee code. Start postheader
Greg Fischerbba812f2017-05-04 20:55:53 -0600357 // block.
David Netoefff5fa2017-08-31 15:47:31 -0400358 //
359 // Note: Consider the following combination:
360 // - the caller is a single block loop
361 // - the callee does not begin with a structure header
362 // - the callee has multiple returns.
363 // We still need to split the caller block and insert a guard block.
364 // But we only need to do it once. We haven't done it yet, but the
365 // single-trip loop header will serve the same purpose.
David Neto2a1014b2017-08-09 14:59:04 -0400366 if (multiReturn) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600367 singleTripLoopHeaderId = this->TakeNextId();
368 AddBranch(singleTripLoopHeaderId, &new_blk_ptr);
369 new_blocks->push_back(std::move(new_blk_ptr));
370 new_blk_ptr.reset(new ir::BasicBlock(NewLabel(
371 singleTripLoopHeaderId)));
372 returnLabelId = this->TakeNextId();
373 singleTripLoopContinueId = this->TakeNextId();
374 AddLoopMerge(returnLabelId, singleTripLoopContinueId, &new_blk_ptr);
375 uint32_t postHeaderId = this->TakeNextId();
376 AddBranch(postHeaderId, &new_blk_ptr);
377 new_blocks->push_back(std::move(new_blk_ptr));
378 new_blk_ptr.reset(new ir::BasicBlock(NewLabel(postHeaderId)));
379 multiBlocks = true;
David Neto860c4192017-08-31 17:33:44 -0400380 // Reset the mapping of the callee's entry block to point to
381 // the post-header block. Do this so we can fix up phis later
382 // on to satisfy dominance.
383 callee2caller[cpi->result_id()] = postHeaderId;
Greg Fischerbba812f2017-05-04 20:55:53 -0600384 }
Greg Fischer04fcc662016-11-10 10:11:50 -0700385 } else {
386 multiBlocks = true;
387 }
388 } break;
389 case SpvOpReturnValue: {
390 // Store return value to return variable.
391 assert(returnVarId != 0);
392 uint32_t valId = cpi->GetInOperand(kSpvReturnValueId).words[0];
393 const auto mapItr = callee2caller.find(valId);
394 if (mapItr != callee2caller.end()) {
395 valId = mapItr->second;
396 }
397 AddStore(returnVarId, valId, &new_blk_ptr);
398
399 // Remember we saw a return; if followed by a label, will need to
400 // insert branch.
401 prevInstWasReturn = true;
402 } break;
403 case SpvOpReturn: {
404 // Remember we saw a return; if followed by a label, will need to
405 // insert branch.
406 prevInstWasReturn = true;
407 } break;
408 case SpvOpFunctionEnd: {
David Neto2a1014b2017-08-09 14:59:04 -0400409 // If there was an early return, we generated a return label id
410 // for it. Now we have to generate the return block with that Id.
Greg Fischer04fcc662016-11-10 10:11:50 -0700411 if (returnLabelId != 0) {
David Neto2a1014b2017-08-09 14:59:04 -0400412 // If previous instruction was return, insert branch instruction
413 // to return block.
Greg Fischer04fcc662016-11-10 10:11:50 -0700414 if (prevInstWasReturn) AddBranch(returnLabelId, &new_blk_ptr);
David Neto2a1014b2017-08-09 14:59:04 -0400415 if (multiReturn) {
416 // If we generated a loop header to for the single-trip loop
417 // to accommodate multiple returns, insert the continue
418 // target block now, with a false branch back to the loop header.
419 new_blocks->push_back(std::move(new_blk_ptr));
420 new_blk_ptr.reset(
421 new ir::BasicBlock(NewLabel(singleTripLoopContinueId)));
422 AddBranchCond(GetFalseId(), singleTripLoopHeaderId, returnLabelId,
423 &new_blk_ptr);
424 }
425 // Generate the return block.
Greg Fischerbba812f2017-05-04 20:55:53 -0600426 new_blocks->push_back(std::move(new_blk_ptr));
Greg Fischer04fcc662016-11-10 10:11:50 -0700427 new_blk_ptr.reset(new ir::BasicBlock(NewLabel(returnLabelId)));
428 multiBlocks = true;
429 }
430 // Load return value into result id of call, if it exists.
431 if (returnVarId != 0) {
432 const uint32_t resId = call_inst_itr->result_id();
433 assert(resId != 0);
434 AddLoad(calleeTypeId, resId, returnVarId, &new_blk_ptr);
435 }
436 // Copy remaining instructions from caller block.
437 auto cii = call_inst_itr;
Greg Fischerbba812f2017-05-04 20:55:53 -0600438 for (++cii; cii != call_block_itr->end(); ++cii) {
Steven Perronbb7802b2017-10-13 14:25:21 -0400439 std::unique_ptr<ir::Instruction> cp_inst(cii->Clone());
Greg Fischer04fcc662016-11-10 10:11:50 -0700440 // If multiple blocks generated, regenerate any same-block
441 // instruction that has not been seen in this last block.
442 if (multiBlocks) {
443 CloneSameBlockOps(&cp_inst, &postCallSB, &preCallSB, &new_blk_ptr);
444 // Remember same-block ops in this block.
445 if (IsSameBlockOp(&*cp_inst)) {
446 const uint32_t rid = cp_inst->result_id();
447 postCallSB[rid] = rid;
448 }
449 }
450 new_blk_ptr->AddInstruction(std::move(cp_inst));
451 }
452 // Finalize inline code.
453 new_blocks->push_back(std::move(new_blk_ptr));
454 } break;
455 default: {
456 // Copy callee instruction and remap all input Ids.
Steven Perronbb7802b2017-10-13 14:25:21 -0400457 std::unique_ptr<ir::Instruction> cp_inst(cpi->Clone());
David Netoefff5fa2017-08-31 15:47:31 -0400458 cp_inst->ForEachInId([&callee2caller, &callee_result_ids,
459 this](uint32_t* iid) {
Greg Fischer04fcc662016-11-10 10:11:50 -0700460 const auto mapItr = callee2caller.find(*iid);
461 if (mapItr != callee2caller.end()) {
462 *iid = mapItr->second;
GregFa699d1a2017-08-29 18:35:05 -0600463 } else if (callee_result_ids.find(*iid) != callee_result_ids.end()) {
464 // Forward reference. Allocate a new id, map it,
465 // use it and check for it when remapping result ids
466 const uint32_t nid = this->TakeNextId();
467 callee2caller[*iid] = nid;
468 *iid = nid;
Greg Fischer04fcc662016-11-10 10:11:50 -0700469 }
470 });
GregFa699d1a2017-08-29 18:35:05 -0600471 // If result id is non-zero, remap it. If already mapped, use mapped
472 // value, else use next id.
Greg Fischer04fcc662016-11-10 10:11:50 -0700473 const uint32_t rid = cp_inst->result_id();
474 if (rid != 0) {
GregFa699d1a2017-08-29 18:35:05 -0600475 const auto mapItr = callee2caller.find(rid);
476 uint32_t nid;
477 if (mapItr != callee2caller.end()) {
478 nid = mapItr->second;
479 }
480 else {
481 nid = this->TakeNextId();
482 callee2caller[rid] = nid;
483 }
Greg Fischer04fcc662016-11-10 10:11:50 -0700484 cp_inst->SetResultId(nid);
485 }
486 new_blk_ptr->AddInstruction(std::move(cp_inst));
487 } break;
488 }
489 });
David Netoefff5fa2017-08-31 15:47:31 -0400490
David Neto25ddfec2017-09-02 19:01:03 -0400491 if (caller_is_loop_header && (new_blocks->size() > 1)) {
David Netoefff5fa2017-08-31 15:47:31 -0400492 // Move the OpLoopMerge from the last block back to the first, where
David Neto25ddfec2017-09-02 19:01:03 -0400493 // it belongs.
David Netoefff5fa2017-08-31 15:47:31 -0400494 auto& first = new_blocks->front();
495 auto& last = new_blocks->back();
496 assert(first != last);
497
498 // Insert a modified copy of the loop merge into the first block.
499 auto loop_merge_itr = last->tail();
500 --loop_merge_itr;
501 assert(loop_merge_itr->opcode() == SpvOpLoopMerge);
Steven Perronbb7802b2017-10-13 14:25:21 -0400502 std::unique_ptr<ir::Instruction> cp_inst(loop_merge_itr->Clone());
David Neto25ddfec2017-09-02 19:01:03 -0400503 if (caller_is_single_block_loop) {
504 // Also, update its continue target to point to the last block.
505 cp_inst->SetInOperand(kSpvLoopMergeContinueTargetIdInIdx, {last->id()});
506 }
David Netoefff5fa2017-08-31 15:47:31 -0400507 first->tail().InsertBefore(std::move(cp_inst));
508
509 // Remove the loop merge from the last block.
Steven Perronbb7802b2017-10-13 14:25:21 -0400510 loop_merge_itr->RemoveFromList();
511 delete &*loop_merge_itr;
David Netoefff5fa2017-08-31 15:47:31 -0400512 }
513
Greg Fischer04fcc662016-11-10 10:11:50 -0700514 // Update block map given replacement blocks.
515 for (auto& blk : *new_blocks) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600516 id2block_[blk->id()] = &*blk;
Greg Fischer04fcc662016-11-10 10:11:50 -0700517 }
518}
519
David Netoceb1d4f2017-03-31 10:36:58 -0400520bool InlinePass::IsInlinableFunctionCall(const ir::Instruction* inst) {
521 if (inst->opcode() != SpvOp::SpvOpFunctionCall) return false;
GregFa107d342017-04-25 13:57:20 -0600522 const uint32_t calleeFnId =
523 inst->GetSingleWordOperand(kSpvFunctionCallFunctionId);
524 const auto ci = inlinable_.find(calleeFnId);
525 return ci != inlinable_.cend();
David Netoceb1d4f2017-03-31 10:36:58 -0400526}
527
GregFe28bd392017-08-01 17:20:13 -0600528void InlinePass::UpdateSucceedingPhis(
529 std::vector<std::unique_ptr<ir::BasicBlock>>& new_blocks) {
530 const auto firstBlk = new_blocks.begin();
531 const auto lastBlk = new_blocks.end() - 1;
532 const uint32_t firstId = (*firstBlk)->id();
533 const uint32_t lastId = (*lastBlk)->id();
534 (*lastBlk)->ForEachSuccessorLabel(
535 [&firstId, &lastId, this](uint32_t succ) {
536 ir::BasicBlock* sbp = this->id2block_[succ];
537 sbp->ForEachPhiInst([&firstId, &lastId](ir::Instruction* phi) {
538 phi->ForEachInId([&firstId, &lastId](uint32_t* id) {
539 if (*id == firstId) *id = lastId;
540 });
541 });
542 });
Greg Fischer04fcc662016-11-10 10:11:50 -0700543}
544
Greg Fischerbba812f2017-05-04 20:55:53 -0600545bool InlinePass::HasMultipleReturns(ir::Function* func) {
546 bool seenReturn = false;
547 bool multipleReturns = false;
548 for (auto& blk : *func) {
549 auto terminal_ii = blk.cend();
550 --terminal_ii;
551 if (terminal_ii->opcode() == SpvOpReturn ||
552 terminal_ii->opcode() == SpvOpReturnValue) {
553 if (seenReturn) {
554 multipleReturns = true;
555 break;
556 }
557 seenReturn = true;
558 }
559 }
560 return multipleReturns;
561}
562
563uint32_t InlinePass::MergeBlockIdIfAny(const ir::BasicBlock& blk) {
564 auto merge_ii = blk.cend();
565 --merge_ii;
566 uint32_t mbid = 0;
567 if (merge_ii != blk.cbegin()) {
568 --merge_ii;
569 if (merge_ii->opcode() == SpvOpLoopMerge)
570 mbid = merge_ii->GetSingleWordOperand(kSpvLoopMergeMergeBlockId);
571 else if (merge_ii->opcode() == SpvOpSelectionMerge)
572 mbid = merge_ii->GetSingleWordOperand(kSpvSelectionMergeMergeBlockId);
573 }
574 return mbid;
575}
576
577void InlinePass::ComputeStructuredSuccessors(ir::Function* func) {
578 // If header, make merge block first successor.
579 for (auto& blk : *func) {
580 uint32_t mbid = MergeBlockIdIfAny(blk);
581 if (mbid != 0)
582 block2structured_succs_[&blk].push_back(id2block_[mbid]);
583 // add true successors
584 blk.ForEachSuccessorLabel([&blk, this](uint32_t sbid) {
585 block2structured_succs_[&blk].push_back(id2block_[sbid]);
586 });
587 }
588}
589
590InlinePass::GetBlocksFunction InlinePass::StructuredSuccessorsFunction() {
591 return [this](const ir::BasicBlock* block) {
592 return &(block2structured_succs_[block]);
593 };
594}
595
596bool InlinePass::HasNoReturnInLoop(ir::Function* func) {
597 // If control not structured, do not do loop/return analysis
598 // TODO: Analyze returns in non-structured control flow
599 if (!module_->HasCapability(SpvCapabilityShader))
600 return false;
601 // Compute structured block order. This order has the property
602 // that dominators are before all blocks they dominate and merge blocks
603 // are after all blocks that are in the control constructs of their header.
604 ComputeStructuredSuccessors(func);
605 auto ignore_block = [](cbb_ptr) {};
606 auto ignore_edge = [](cbb_ptr, cbb_ptr) {};
607 std::list<const ir::BasicBlock*> structuredOrder;
608 spvtools::CFA<ir::BasicBlock>::DepthFirstTraversal(
609 &*func->begin(), StructuredSuccessorsFunction(), ignore_block,
610 [&](cbb_ptr b) { structuredOrder.push_front(b); }, ignore_edge);
611 // Search for returns in loops. Only need to track outermost loop
612 bool return_in_loop = false;
613 uint32_t outerLoopMergeId = 0;
614 for (auto& blk : structuredOrder) {
615 // Exiting current outer loop
616 if (blk->id() == outerLoopMergeId)
617 outerLoopMergeId = 0;
618 // Return block
619 auto terminal_ii = blk->cend();
620 --terminal_ii;
621 if (terminal_ii->opcode() == SpvOpReturn ||
622 terminal_ii->opcode() == SpvOpReturnValue) {
623 if (outerLoopMergeId != 0) {
624 return_in_loop = true;
625 break;
626 }
627 }
628 else if (terminal_ii != blk->cbegin()) {
629 auto merge_ii = terminal_ii;
630 --merge_ii;
631 // Entering outermost loop
632 if (merge_ii->opcode() == SpvOpLoopMerge && outerLoopMergeId == 0)
633 outerLoopMergeId = merge_ii->GetSingleWordOperand(
634 kSpvLoopMergeMergeBlockId);
635 }
636 }
637 return !return_in_loop;
638}
639
640void InlinePass::AnalyzeReturns(ir::Function* func) {
641 // Look for multiple returns
642 if (!HasMultipleReturns(func)) {
643 no_return_in_loop_.insert(func->result_id());
644 return;
645 }
David Neto2a1014b2017-08-09 14:59:04 -0400646 multi_return_funcs_.insert(func->result_id());
Greg Fischerbba812f2017-05-04 20:55:53 -0600647 // If multiple returns, see if any are in a loop
648 if (HasNoReturnInLoop(func))
649 no_return_in_loop_.insert(func->result_id());
650}
651
652bool InlinePass::IsInlinableFunction(ir::Function* func) {
GregFa107d342017-04-25 13:57:20 -0600653 // We can only inline a function if it has blocks.
654 if (func->cbegin() == func->cend())
655 return false;
Greg Fischerbba812f2017-05-04 20:55:53 -0600656 // Do not inline functions with returns in loops. Currently early return
657 // functions are inlined by wrapping them in a one trip loop and implementing
658 // the returns as a branch to the loop's merge block. However, this can only
659 // done validly if the return was not in a loop in the original function.
660 // Also remember functions with multiple (early) returns.
661 AnalyzeReturns(func);
David Netoefff5fa2017-08-31 15:47:31 -0400662 return no_return_in_loop_.find(func->result_id()) !=
663 no_return_in_loop_.cend();
GregFa107d342017-04-25 13:57:20 -0600664}
665
GregFe28bd392017-08-01 17:20:13 -0600666void InlinePass::InitializeInline(ir::Module* module) {
Greg Fischer04fcc662016-11-10 10:11:50 -0700667 def_use_mgr_.reset(new analysis::DefUseManager(consumer(), module));
668
669 // Initialize next unused Id.
670 next_id_ = module->id_bound();
671
672 // Save module.
673 module_ = module;
674
Greg Fischerbba812f2017-05-04 20:55:53 -0600675 false_id_ = 0;
676
GregFe28bd392017-08-01 17:20:13 -0600677 // clear collections
Greg Fischer04fcc662016-11-10 10:11:50 -0700678 id2function_.clear();
679 id2block_.clear();
Greg Fischerbba812f2017-05-04 20:55:53 -0600680 block2structured_succs_.clear();
GregFa107d342017-04-25 13:57:20 -0600681 inlinable_.clear();
GregFe28bd392017-08-01 17:20:13 -0600682 no_return_in_loop_.clear();
David Neto2a1014b2017-08-09 14:59:04 -0400683 multi_return_funcs_.clear();
GregFe28bd392017-08-01 17:20:13 -0600684
Greg Fischer04fcc662016-11-10 10:11:50 -0700685 for (auto& fn : *module_) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600686 // Initialize function and block maps.
Greg Fischer04fcc662016-11-10 10:11:50 -0700687 id2function_[fn.result_id()] = &fn;
688 for (auto& blk : fn) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600689 id2block_[blk.id()] = &blk;
Greg Fischer04fcc662016-11-10 10:11:50 -0700690 }
Greg Fischerbba812f2017-05-04 20:55:53 -0600691 // Compute inlinability
GregFa107d342017-04-25 13:57:20 -0600692 if (IsInlinableFunction(&fn))
693 inlinable_.insert(fn.result_id());
Greg Fischer04fcc662016-11-10 10:11:50 -0700694 }
695};
696
Greg Fischer04fcc662016-11-10 10:11:50 -0700697
698InlinePass::InlinePass()
699 : module_(nullptr), def_use_mgr_(nullptr), next_id_(0) {}
700
Greg Fischer04fcc662016-11-10 10:11:50 -0700701} // namespace opt
702} // namespace spvtools