blob: 5a88ef5d3fa07fde373378e597a4ce7ae036338b [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
dan sinclaireda2cfb2018-08-03 15:06:09 -040017#include "source/opt/inline_pass.h"
GregFe28bd392017-08-01 17:20:13 -060018
dan sinclaireda2cfb2018-08-03 15:06:09 -040019#include <unordered_set>
20#include <utility>
21
22#include "source/cfa.h"
dan sinclair1963a2d2018-08-14 15:01:50 -040023#include "source/util/make_unique.h"
Greg Fischer04fcc662016-11-10 10:11:50 -070024
25// Indices of operands in SPIR-V instructions
26
Greg Fischer04fcc662016-11-10 10:11:50 -070027static const int kSpvFunctionCallFunctionId = 2;
28static const int kSpvFunctionCallArgumentId = 3;
29static const int kSpvReturnValueId = 0;
Greg Fischerbba812f2017-05-04 20:55:53 -060030static const int kSpvLoopMergeMergeBlockId = 0;
David Netoefff5fa2017-08-31 15:47:31 -040031static const int kSpvLoopMergeContinueTargetIdInIdx = 1;
Greg Fischer04fcc662016-11-10 10:11:50 -070032
33namespace spvtools {
34namespace opt {
35
Greg Fischer04fcc662016-11-10 10:11:50 -070036uint32_t InlinePass::AddPointerToType(uint32_t type_id,
37 SpvStorageClass storage_class) {
38 uint32_t resultId = TakeNextId();
dan sinclairc7da51a2018-07-12 15:14:43 -040039 std::unique_ptr<Instruction> type_inst(
40 new Instruction(context(), SpvOpTypePointer, 0, resultId,
41 {{spv_operand_type_t::SPV_OPERAND_TYPE_STORAGE_CLASS,
42 {uint32_t(storage_class)}},
43 {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {type_id}}}));
Steven Perron476cae62017-10-30 11:13:24 -040044 context()->AddType(std::move(type_inst));
Alan Baker61690852017-12-08 15:33:19 -050045 analysis::Type* pointeeTy;
46 std::unique_ptr<analysis::Pointer> pointerTy;
47 std::tie(pointeeTy, pointerTy) =
48 context()->get_type_mgr()->GetTypeAndPointerType(type_id,
49 SpvStorageClassFunction);
50 context()->get_type_mgr()->RegisterType(resultId, *pointerTy);
Greg Fischer04fcc662016-11-10 10:11:50 -070051 return resultId;
52}
53
54void InlinePass::AddBranch(uint32_t label_id,
dan sinclairc7da51a2018-07-12 15:14:43 -040055 std::unique_ptr<BasicBlock>* block_ptr) {
56 std::unique_ptr<Instruction> newBranch(
57 new Instruction(context(), SpvOpBranch, 0, 0,
58 {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {label_id}}}));
Greg Fischer04fcc662016-11-10 10:11:50 -070059 (*block_ptr)->AddInstruction(std::move(newBranch));
60}
61
Greg Fischerbba812f2017-05-04 20:55:53 -060062void InlinePass::AddBranchCond(uint32_t cond_id, uint32_t true_id,
Diego Novillod2938e42017-11-08 12:40:02 -050063 uint32_t false_id,
dan sinclairc7da51a2018-07-12 15:14:43 -040064 std::unique_ptr<BasicBlock>* block_ptr) {
65 std::unique_ptr<Instruction> newBranch(
66 new Instruction(context(), SpvOpBranchConditional, 0, 0,
67 {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {cond_id}},
68 {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {true_id}},
69 {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {false_id}}}));
Greg Fischerbba812f2017-05-04 20:55:53 -060070 (*block_ptr)->AddInstruction(std::move(newBranch));
71}
72
73void InlinePass::AddLoopMerge(uint32_t merge_id, uint32_t continue_id,
dan sinclairc7da51a2018-07-12 15:14:43 -040074 std::unique_ptr<BasicBlock>* block_ptr) {
75 std::unique_ptr<Instruction> newLoopMerge(new Instruction(
Alan Bakera7717132017-11-14 14:11:50 -050076 context(), SpvOpLoopMerge, 0, 0,
Greg Fischerbba812f2017-05-04 20:55:53 -060077 {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {merge_id}},
78 {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {continue_id}},
79 {spv_operand_type_t::SPV_OPERAND_TYPE_LOOP_CONTROL, {0}}}));
80 (*block_ptr)->AddInstruction(std::move(newLoopMerge));
81}
82
Greg Fischer04fcc662016-11-10 10:11:50 -070083void InlinePass::AddStore(uint32_t ptr_id, uint32_t val_id,
dan sinclairc7da51a2018-07-12 15:14:43 -040084 std::unique_ptr<BasicBlock>* block_ptr) {
85 std::unique_ptr<Instruction> newStore(
86 new Instruction(context(), SpvOpStore, 0, 0,
87 {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {ptr_id}},
88 {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {val_id}}}));
Greg Fischer04fcc662016-11-10 10:11:50 -070089 (*block_ptr)->AddInstruction(std::move(newStore));
90}
91
92void InlinePass::AddLoad(uint32_t type_id, uint32_t resultId, uint32_t ptr_id,
dan sinclairc7da51a2018-07-12 15:14:43 -040093 std::unique_ptr<BasicBlock>* block_ptr) {
94 std::unique_ptr<Instruction> newLoad(
95 new Instruction(context(), SpvOpLoad, type_id, resultId,
96 {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {ptr_id}}}));
Greg Fischer04fcc662016-11-10 10:11:50 -070097 (*block_ptr)->AddInstruction(std::move(newLoad));
98}
99
dan sinclairc7da51a2018-07-12 15:14:43 -0400100std::unique_ptr<Instruction> InlinePass::NewLabel(uint32_t label_id) {
101 std::unique_ptr<Instruction> newLabel(
102 new Instruction(context(), SpvOpLabel, 0, label_id, {}));
Greg Fischer04fcc662016-11-10 10:11:50 -0700103 return newLabel;
104}
105
Greg Fischerbba812f2017-05-04 20:55:53 -0600106uint32_t InlinePass::GetFalseId() {
Diego Novillod2938e42017-11-08 12:40:02 -0500107 if (false_id_ != 0) return false_id_;
Diego Novillo1040a952017-10-25 13:26:25 -0400108 false_id_ = get_module()->GetGlobalValue(SpvOpConstantFalse);
Diego Novillod2938e42017-11-08 12:40:02 -0500109 if (false_id_ != 0) return false_id_;
Diego Novillo1040a952017-10-25 13:26:25 -0400110 uint32_t boolId = get_module()->GetGlobalValue(SpvOpTypeBool);
Greg Fischerbba812f2017-05-04 20:55:53 -0600111 if (boolId == 0) {
112 boolId = TakeNextId();
Diego Novillo1040a952017-10-25 13:26:25 -0400113 get_module()->AddGlobalValue(SpvOpTypeBool, boolId, 0);
Greg Fischerbba812f2017-05-04 20:55:53 -0600114 }
115 false_id_ = TakeNextId();
Diego Novillo1040a952017-10-25 13:26:25 -0400116 get_module()->AddGlobalValue(SpvOpConstantFalse, false_id_, boolId);
Greg Fischerbba812f2017-05-04 20:55:53 -0600117 return false_id_;
118}
119
Greg Fischer04fcc662016-11-10 10:11:50 -0700120void InlinePass::MapParams(
dan sinclairc7da51a2018-07-12 15:14:43 -0400121 Function* calleeFn, BasicBlock::iterator call_inst_itr,
Greg Fischer04fcc662016-11-10 10:11:50 -0700122 std::unordered_map<uint32_t, uint32_t>* callee2caller) {
123 int param_idx = 0;
dan sinclaire6b95332018-07-09 11:32:29 -0400124 calleeFn->ForEachParam([&call_inst_itr, &param_idx,
dan sinclairc7da51a2018-07-12 15:14:43 -0400125 &callee2caller](const Instruction* cpi) {
dan sinclaire6b95332018-07-09 11:32:29 -0400126 const uint32_t pid = cpi->result_id();
127 (*callee2caller)[pid] = call_inst_itr->GetSingleWordOperand(
128 kSpvFunctionCallArgumentId + param_idx);
129 ++param_idx;
130 });
Greg Fischer04fcc662016-11-10 10:11:50 -0700131}
132
133void InlinePass::CloneAndMapLocals(
dan sinclairc7da51a2018-07-12 15:14:43 -0400134 Function* calleeFn, std::vector<std::unique_ptr<Instruction>>* new_vars,
Greg Fischer04fcc662016-11-10 10:11:50 -0700135 std::unordered_map<uint32_t, uint32_t>* callee2caller) {
136 auto callee_block_itr = calleeFn->begin();
137 auto callee_var_itr = callee_block_itr->begin();
138 while (callee_var_itr->opcode() == SpvOp::SpvOpVariable) {
dan sinclairc7da51a2018-07-12 15:14:43 -0400139 std::unique_ptr<Instruction> var_inst(callee_var_itr->Clone(context()));
Greg Fischer04fcc662016-11-10 10:11:50 -0700140 uint32_t newId = TakeNextId();
Pierre Moreau5bd55f12018-02-20 19:19:57 +0100141 get_decoration_mgr()->CloneDecorations(callee_var_itr->result_id(), newId);
Greg Fischer04fcc662016-11-10 10:11:50 -0700142 var_inst->SetResultId(newId);
143 (*callee2caller)[callee_var_itr->result_id()] = newId;
144 new_vars->push_back(std::move(var_inst));
Greg Fischerbba812f2017-05-04 20:55:53 -0600145 ++callee_var_itr;
Greg Fischer04fcc662016-11-10 10:11:50 -0700146 }
147}
148
149uint32_t InlinePass::CreateReturnVar(
dan sinclairc7da51a2018-07-12 15:14:43 -0400150 Function* calleeFn, std::vector<std::unique_ptr<Instruction>>* new_vars) {
Greg Fischer04fcc662016-11-10 10:11:50 -0700151 uint32_t returnVarId = 0;
152 const uint32_t calleeTypeId = calleeFn->type_id();
Steven Perron06b437d2018-02-09 20:33:06 -0500153 analysis::Type* calleeType = context()->get_type_mgr()->GetType(calleeTypeId);
154 if (calleeType->AsVoid() == nullptr) {
Greg Fischer04fcc662016-11-10 10:11:50 -0700155 // Find or create ptr to callee return type.
Steven Perronb86eb682017-12-11 13:10:24 -0500156 uint32_t returnVarTypeId = context()->get_type_mgr()->FindPointerToType(
157 calleeTypeId, SpvStorageClassFunction);
Greg Fischer04fcc662016-11-10 10:11:50 -0700158 if (returnVarTypeId == 0)
159 returnVarTypeId = AddPointerToType(calleeTypeId, SpvStorageClassFunction);
160 // Add return var to new function scope variables.
161 returnVarId = TakeNextId();
dan sinclairc7da51a2018-07-12 15:14:43 -0400162 std::unique_ptr<Instruction> var_inst(
163 new Instruction(context(), SpvOpVariable, returnVarTypeId, returnVarId,
164 {{spv_operand_type_t::SPV_OPERAND_TYPE_STORAGE_CLASS,
165 {SpvStorageClassFunction}}}));
Greg Fischer04fcc662016-11-10 10:11:50 -0700166 new_vars->push_back(std::move(var_inst));
167 }
Pierre Moreau5bd55f12018-02-20 19:19:57 +0100168 get_decoration_mgr()->CloneDecorations(calleeFn->result_id(), returnVarId);
Greg Fischer04fcc662016-11-10 10:11:50 -0700169 return returnVarId;
170}
171
dan sinclairc7da51a2018-07-12 15:14:43 -0400172bool InlinePass::IsSameBlockOp(const Instruction* inst) const {
Greg Fischer04fcc662016-11-10 10:11:50 -0700173 return inst->opcode() == SpvOpSampledImage || inst->opcode() == SpvOpImage;
174}
175
176void InlinePass::CloneSameBlockOps(
dan sinclairc7da51a2018-07-12 15:14:43 -0400177 std::unique_ptr<Instruction>* inst,
Greg Fischer04fcc662016-11-10 10:11:50 -0700178 std::unordered_map<uint32_t, uint32_t>* postCallSB,
dan sinclairc7da51a2018-07-12 15:14:43 -0400179 std::unordered_map<uint32_t, Instruction*>* preCallSB,
180 std::unique_ptr<BasicBlock>* block_ptr) {
Pierre Moreau5bd55f12018-02-20 19:19:57 +0100181 (*inst)->ForEachInId(
182 [&postCallSB, &preCallSB, &block_ptr, this](uint32_t* iid) {
183 const auto mapItr = (*postCallSB).find(*iid);
184 if (mapItr == (*postCallSB).end()) {
185 const auto mapItr2 = (*preCallSB).find(*iid);
186 if (mapItr2 != (*preCallSB).end()) {
187 // Clone pre-call same-block ops, map result id.
dan sinclairc7da51a2018-07-12 15:14:43 -0400188 const Instruction* inInst = mapItr2->second;
189 std::unique_ptr<Instruction> sb_inst(inInst->Clone(context()));
Pierre Moreau5bd55f12018-02-20 19:19:57 +0100190 CloneSameBlockOps(&sb_inst, postCallSB, preCallSB, block_ptr);
191 const uint32_t rid = sb_inst->result_id();
192 const uint32_t nid = this->TakeNextId();
193 get_decoration_mgr()->CloneDecorations(rid, nid);
194 sb_inst->SetResultId(nid);
195 (*postCallSB)[rid] = nid;
196 *iid = nid;
197 (*block_ptr)->AddInstruction(std::move(sb_inst));
198 }
199 } else {
200 // Reset same-block op operand.
201 *iid = mapItr->second;
202 }
203 });
Greg Fischer04fcc662016-11-10 10:11:50 -0700204}
205
206void InlinePass::GenInlineCode(
dan sinclairc7da51a2018-07-12 15:14:43 -0400207 std::vector<std::unique_ptr<BasicBlock>>* new_blocks,
208 std::vector<std::unique_ptr<Instruction>>* new_vars,
209 BasicBlock::iterator call_inst_itr,
210 UptrVectorIterator<BasicBlock> call_block_itr) {
Greg Fischer04fcc662016-11-10 10:11:50 -0700211 // Map from all ids in the callee to their equivalent id in the caller
212 // as callee instructions are copied into caller.
213 std::unordered_map<uint32_t, uint32_t> callee2caller;
214 // Pre-call same-block insts
dan sinclairc7da51a2018-07-12 15:14:43 -0400215 std::unordered_map<uint32_t, Instruction*> preCallSB;
Greg Fischer04fcc662016-11-10 10:11:50 -0700216 // Post-call same-block op ids
217 std::unordered_map<uint32_t, uint32_t> postCallSB;
218
Steven Perronb3daa932018-03-06 11:20:28 -0500219 // Invalidate the def-use chains. They are not kept up to date while
220 // inlining. However, certain calls try to keep them up-to-date if they are
221 // valid. These operations can fail.
dan sinclairc7da51a2018-07-12 15:14:43 -0400222 context()->InvalidateAnalyses(IRContext::kAnalysisDefUse);
Steven Perronb3daa932018-03-06 11:20:28 -0500223
dan sinclairc7da51a2018-07-12 15:14:43 -0400224 Function* calleeFn = id2function_[call_inst_itr->GetSingleWordOperand(
Greg Fischer04fcc662016-11-10 10:11:50 -0700225 kSpvFunctionCallFunctionId)];
226
David Neto2a1014b2017-08-09 14:59:04 -0400227 // Check for multiple returns in the callee.
228 auto fi = multi_return_funcs_.find(calleeFn->result_id());
229 const bool multiReturn = fi != multi_return_funcs_.end();
Greg Fischerbba812f2017-05-04 20:55:53 -0600230
Greg Fischer04fcc662016-11-10 10:11:50 -0700231 // Map parameters to actual arguments.
232 MapParams(calleeFn, call_inst_itr, &callee2caller);
233
234 // Define caller local variables for all callee variables and create map to
235 // them.
236 CloneAndMapLocals(calleeFn, new_vars, &callee2caller);
237
238 // Create return var if needed.
239 uint32_t returnVarId = CreateReturnVar(calleeFn, new_vars);
240
GregFa699d1a2017-08-29 18:35:05 -0600241 // Create set of callee result ids. Used to detect forward references
242 std::unordered_set<uint32_t> callee_result_ids;
dan sinclairc7da51a2018-07-12 15:14:43 -0400243 calleeFn->ForEachInst([&callee_result_ids](const Instruction* cpi) {
GregFa699d1a2017-08-29 18:35:05 -0600244 const uint32_t rid = cpi->result_id();
Diego Novillod2938e42017-11-08 12:40:02 -0500245 if (rid != 0) callee_result_ids.insert(rid);
GregFa699d1a2017-08-29 18:35:05 -0600246 });
247
David Netoefff5fa2017-08-31 15:47:31 -0400248 // If the caller is in a single-block loop, and the callee has multiple
249 // blocks, then the normal inlining logic will place the OpLoopMerge in
250 // the last of several blocks in the loop. Instead, it should be placed
251 // at the end of the first block. First determine if the caller is in a
252 // single block loop. We'll wait to move the OpLoopMerge until the end
253 // of the regular inlining logic, and only if necessary.
254 bool caller_is_single_block_loop = false;
David Neto25ddfec2017-09-02 19:01:03 -0400255 bool caller_is_loop_header = false;
David Netoefff5fa2017-08-31 15:47:31 -0400256 if (auto* loop_merge = call_block_itr->GetLoopMergeInst()) {
David Neto25ddfec2017-09-02 19:01:03 -0400257 caller_is_loop_header = true;
David Netoefff5fa2017-08-31 15:47:31 -0400258 caller_is_single_block_loop =
259 call_block_itr->id() ==
260 loop_merge->GetSingleWordInOperand(kSpvLoopMergeContinueTargetIdInIdx);
261 }
262
263 bool callee_begins_with_structured_header =
264 (*(calleeFn->begin())).GetMergeInst() != nullptr;
265
Greg Fischer04fcc662016-11-10 10:11:50 -0700266 // Clone and map callee code. Copy caller block code to beginning of
267 // first block and end of last block.
268 bool prevInstWasReturn = false;
Greg Fischerbba812f2017-05-04 20:55:53 -0600269 uint32_t singleTripLoopHeaderId = 0;
270 uint32_t singleTripLoopContinueId = 0;
Greg Fischer04fcc662016-11-10 10:11:50 -0700271 uint32_t returnLabelId = 0;
272 bool multiBlocks = false;
273 const uint32_t calleeTypeId = calleeFn->type_id();
David Neto2a1014b2017-08-09 14:59:04 -0400274 // new_blk_ptr is a new basic block in the caller. New instructions are
275 // written to it. It is created when we encounter the OpLabel
David Netoefff5fa2017-08-31 15:47:31 -0400276 // of the first callee block. It is appended to new_blocks only when
277 // it is complete.
dan sinclairc7da51a2018-07-12 15:14:43 -0400278 std::unique_ptr<BasicBlock> new_blk_ptr;
Greg Fischer04fcc662016-11-10 10:11:50 -0700279 calleeFn->ForEachInst([&new_blocks, &callee2caller, &call_block_itr,
280 &call_inst_itr, &new_blk_ptr, &prevInstWasReturn,
David Neto25ddfec2017-09-02 19:01:03 -0400281 &returnLabelId, &returnVarId, caller_is_loop_header,
David Netoefff5fa2017-08-31 15:47:31 -0400282 callee_begins_with_structured_header, &calleeTypeId,
David Neto2a1014b2017-08-09 14:59:04 -0400283 &multiBlocks, &postCallSB, &preCallSB, multiReturn,
Greg Fischerbba812f2017-05-04 20:55:53 -0600284 &singleTripLoopHeaderId, &singleTripLoopContinueId,
dan sinclairc7da51a2018-07-12 15:14:43 -0400285 &callee_result_ids, this](const Instruction* cpi) {
Greg Fischer04fcc662016-11-10 10:11:50 -0700286 switch (cpi->opcode()) {
287 case SpvOpFunction:
288 case SpvOpFunctionParameter:
Greg Fischer04fcc662016-11-10 10:11:50 -0700289 // Already processed
290 break;
Steven Perron9a008832018-05-31 20:28:19 -0400291 case SpvOpVariable:
292 if (cpi->NumInOperands() == 2) {
293 assert(callee2caller.count(cpi->result_id()) &&
294 "Expected the variable to have already been mapped.");
295 uint32_t new_var_id = callee2caller.at(cpi->result_id());
296
297 // The initializer must be a constant or global value. No mapped
298 // should be used.
299 uint32_t val_id = cpi->GetSingleWordInOperand(1);
300 AddStore(new_var_id, val_id, &new_blk_ptr);
301 }
302 break;
Alan Baker4246abd2018-04-26 12:22:08 -0400303 case SpvOpUnreachable:
304 case SpvOpKill: {
305 // Generate a return label so that we split the block with the function
306 // call. Copy the terminator into the new block.
307 if (returnLabelId == 0) returnLabelId = this->TakeNextId();
dan sinclairc7da51a2018-07-12 15:14:43 -0400308 std::unique_ptr<Instruction> terminator(
309 new Instruction(context(), cpi->opcode(), 0, 0, {}));
Alan Baker4246abd2018-04-26 12:22:08 -0400310 new_blk_ptr->AddInstruction(std::move(terminator));
311 break;
312 }
Greg Fischer04fcc662016-11-10 10:11:50 -0700313 case SpvOpLabel: {
314 // If previous instruction was early return, insert branch
315 // instruction to return block.
316 if (prevInstWasReturn) {
317 if (returnLabelId == 0) returnLabelId = this->TakeNextId();
318 AddBranch(returnLabelId, &new_blk_ptr);
319 prevInstWasReturn = false;
320 }
321 // Finish current block (if it exists) and get label for next block.
322 uint32_t labelId;
323 bool firstBlock = false;
324 if (new_blk_ptr != nullptr) {
325 new_blocks->push_back(std::move(new_blk_ptr));
326 // If result id is already mapped, use it, otherwise get a new
327 // one.
328 const uint32_t rid = cpi->result_id();
329 const auto mapItr = callee2caller.find(rid);
330 labelId = (mapItr != callee2caller.end()) ? mapItr->second
331 : this->TakeNextId();
332 } else {
333 // First block needs to use label of original block
334 // but map callee label in case of phi reference.
Greg Fischerbba812f2017-05-04 20:55:53 -0600335 labelId = call_block_itr->id();
Greg Fischer04fcc662016-11-10 10:11:50 -0700336 callee2caller[cpi->result_id()] = labelId;
337 firstBlock = true;
338 }
339 // Create first/next block.
dan sinclair1963a2d2018-08-14 15:01:50 -0400340 new_blk_ptr = MakeUnique<BasicBlock>(NewLabel(labelId));
Greg Fischer04fcc662016-11-10 10:11:50 -0700341 if (firstBlock) {
342 // Copy contents of original caller block up to call instruction.
343 for (auto cii = call_block_itr->begin(); cii != call_inst_itr;
Steven Perron51ecc732018-02-20 11:24:08 -0500344 cii = call_block_itr->begin()) {
dan sinclairc7da51a2018-07-12 15:14:43 -0400345 Instruction* inst = &*cii;
Steven Perron51ecc732018-02-20 11:24:08 -0500346 inst->RemoveFromList();
dan sinclairc7da51a2018-07-12 15:14:43 -0400347 std::unique_ptr<Instruction> cp_inst(inst);
Greg Fischer04fcc662016-11-10 10:11:50 -0700348 // Remember same-block ops for possible regeneration.
349 if (IsSameBlockOp(&*cp_inst)) {
350 auto* sb_inst_ptr = cp_inst.get();
351 preCallSB[cp_inst->result_id()] = sb_inst_ptr;
352 }
353 new_blk_ptr->AddInstruction(std::move(cp_inst));
354 }
Diego Novillod2938e42017-11-08 12:40:02 -0500355 if (caller_is_loop_header && callee_begins_with_structured_header) {
David Netoefff5fa2017-08-31 15:47:31 -0400356 // We can't place both the caller's merge instruction and another
357 // merge instruction in the same block. So split the calling block.
358 // Insert an unconditional branch to a new guard block. Later,
359 // once we know the ID of the last block, we will move the caller's
360 // OpLoopMerge from the last generated block into the first block.
361 // We also wait to avoid invalidating various iterators.
362 const auto guard_block_id = this->TakeNextId();
363 AddBranch(guard_block_id, &new_blk_ptr);
364 new_blocks->push_back(std::move(new_blk_ptr));
365 // Start the next block.
dan sinclair1963a2d2018-08-14 15:01:50 -0400366 new_blk_ptr = MakeUnique<BasicBlock>(NewLabel(guard_block_id));
David Netoefff5fa2017-08-31 15:47:31 -0400367 // Reset the mapping of the callee's entry block to point to
368 // the guard block. Do this so we can fix up phis later on to
369 // satisfy dominance.
370 callee2caller[cpi->result_id()] = guard_block_id;
371 }
372 // If callee has multiple returns, insert a header block for
David Neto2a1014b2017-08-09 14:59:04 -0400373 // single-trip loop that will encompass callee code. Start postheader
Greg Fischerbba812f2017-05-04 20:55:53 -0600374 // block.
David Netoefff5fa2017-08-31 15:47:31 -0400375 //
376 // Note: Consider the following combination:
377 // - the caller is a single block loop
378 // - the callee does not begin with a structure header
379 // - the callee has multiple returns.
380 // We still need to split the caller block and insert a guard block.
381 // But we only need to do it once. We haven't done it yet, but the
382 // single-trip loop header will serve the same purpose.
David Neto2a1014b2017-08-09 14:59:04 -0400383 if (multiReturn) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600384 singleTripLoopHeaderId = this->TakeNextId();
385 AddBranch(singleTripLoopHeaderId, &new_blk_ptr);
386 new_blocks->push_back(std::move(new_blk_ptr));
dan sinclair1963a2d2018-08-14 15:01:50 -0400387 new_blk_ptr =
388 MakeUnique<BasicBlock>(NewLabel(singleTripLoopHeaderId));
Greg Fischerbba812f2017-05-04 20:55:53 -0600389 returnLabelId = this->TakeNextId();
390 singleTripLoopContinueId = this->TakeNextId();
391 AddLoopMerge(returnLabelId, singleTripLoopContinueId, &new_blk_ptr);
392 uint32_t postHeaderId = this->TakeNextId();
393 AddBranch(postHeaderId, &new_blk_ptr);
394 new_blocks->push_back(std::move(new_blk_ptr));
dan sinclair1963a2d2018-08-14 15:01:50 -0400395 new_blk_ptr = MakeUnique<BasicBlock>(NewLabel(postHeaderId));
Greg Fischerbba812f2017-05-04 20:55:53 -0600396 multiBlocks = true;
David Neto860c4192017-08-31 17:33:44 -0400397 // Reset the mapping of the callee's entry block to point to
398 // the post-header block. Do this so we can fix up phis later
399 // on to satisfy dominance.
400 callee2caller[cpi->result_id()] = postHeaderId;
Greg Fischerbba812f2017-05-04 20:55:53 -0600401 }
Greg Fischer04fcc662016-11-10 10:11:50 -0700402 } else {
403 multiBlocks = true;
404 }
405 } break;
406 case SpvOpReturnValue: {
407 // Store return value to return variable.
408 assert(returnVarId != 0);
409 uint32_t valId = cpi->GetInOperand(kSpvReturnValueId).words[0];
410 const auto mapItr = callee2caller.find(valId);
411 if (mapItr != callee2caller.end()) {
412 valId = mapItr->second;
413 }
414 AddStore(returnVarId, valId, &new_blk_ptr);
415
416 // Remember we saw a return; if followed by a label, will need to
417 // insert branch.
418 prevInstWasReturn = true;
419 } break;
420 case SpvOpReturn: {
421 // Remember we saw a return; if followed by a label, will need to
422 // insert branch.
423 prevInstWasReturn = true;
424 } break;
425 case SpvOpFunctionEnd: {
David Neto2a1014b2017-08-09 14:59:04 -0400426 // If there was an early return, we generated a return label id
427 // for it. Now we have to generate the return block with that Id.
Greg Fischer04fcc662016-11-10 10:11:50 -0700428 if (returnLabelId != 0) {
David Neto2a1014b2017-08-09 14:59:04 -0400429 // If previous instruction was return, insert branch instruction
430 // to return block.
Greg Fischer04fcc662016-11-10 10:11:50 -0700431 if (prevInstWasReturn) AddBranch(returnLabelId, &new_blk_ptr);
David Neto2a1014b2017-08-09 14:59:04 -0400432 if (multiReturn) {
433 // If we generated a loop header to for the single-trip loop
434 // to accommodate multiple returns, insert the continue
435 // target block now, with a false branch back to the loop header.
436 new_blocks->push_back(std::move(new_blk_ptr));
dan sinclair1963a2d2018-08-14 15:01:50 -0400437 new_blk_ptr =
438 MakeUnique<BasicBlock>(NewLabel(singleTripLoopContinueId));
David Neto2a1014b2017-08-09 14:59:04 -0400439 AddBranchCond(GetFalseId(), singleTripLoopHeaderId, returnLabelId,
440 &new_blk_ptr);
441 }
442 // Generate the return block.
Greg Fischerbba812f2017-05-04 20:55:53 -0600443 new_blocks->push_back(std::move(new_blk_ptr));
dan sinclair1963a2d2018-08-14 15:01:50 -0400444 new_blk_ptr = MakeUnique<BasicBlock>(NewLabel(returnLabelId));
Greg Fischer04fcc662016-11-10 10:11:50 -0700445 multiBlocks = true;
446 }
447 // Load return value into result id of call, if it exists.
448 if (returnVarId != 0) {
449 const uint32_t resId = call_inst_itr->result_id();
450 assert(resId != 0);
451 AddLoad(calleeTypeId, resId, returnVarId, &new_blk_ptr);
452 }
453 // Copy remaining instructions from caller block.
dan sinclairc7da51a2018-07-12 15:14:43 -0400454 for (Instruction* inst = call_inst_itr->NextNode(); inst;
Steven Perron51ecc732018-02-20 11:24:08 -0500455 inst = call_inst_itr->NextNode()) {
456 inst->RemoveFromList();
dan sinclairc7da51a2018-07-12 15:14:43 -0400457 std::unique_ptr<Instruction> cp_inst(inst);
Greg Fischer04fcc662016-11-10 10:11:50 -0700458 // If multiple blocks generated, regenerate any same-block
459 // instruction that has not been seen in this last block.
460 if (multiBlocks) {
461 CloneSameBlockOps(&cp_inst, &postCallSB, &preCallSB, &new_blk_ptr);
462 // Remember same-block ops in this block.
463 if (IsSameBlockOp(&*cp_inst)) {
464 const uint32_t rid = cp_inst->result_id();
465 postCallSB[rid] = rid;
466 }
467 }
468 new_blk_ptr->AddInstruction(std::move(cp_inst));
469 }
470 // Finalize inline code.
471 new_blocks->push_back(std::move(new_blk_ptr));
472 } break;
473 default: {
474 // Copy callee instruction and remap all input Ids.
dan sinclairc7da51a2018-07-12 15:14:43 -0400475 std::unique_ptr<Instruction> cp_inst(cpi->Clone(context()));
David Netoefff5fa2017-08-31 15:47:31 -0400476 cp_inst->ForEachInId([&callee2caller, &callee_result_ids,
477 this](uint32_t* iid) {
Greg Fischer04fcc662016-11-10 10:11:50 -0700478 const auto mapItr = callee2caller.find(*iid);
479 if (mapItr != callee2caller.end()) {
480 *iid = mapItr->second;
GregFa699d1a2017-08-29 18:35:05 -0600481 } else if (callee_result_ids.find(*iid) != callee_result_ids.end()) {
482 // Forward reference. Allocate a new id, map it,
483 // use it and check for it when remapping result ids
484 const uint32_t nid = this->TakeNextId();
485 callee2caller[*iid] = nid;
486 *iid = nid;
Greg Fischer04fcc662016-11-10 10:11:50 -0700487 }
488 });
GregFa699d1a2017-08-29 18:35:05 -0600489 // If result id is non-zero, remap it. If already mapped, use mapped
490 // value, else use next id.
Greg Fischer04fcc662016-11-10 10:11:50 -0700491 const uint32_t rid = cp_inst->result_id();
492 if (rid != 0) {
GregFa699d1a2017-08-29 18:35:05 -0600493 const auto mapItr = callee2caller.find(rid);
494 uint32_t nid;
495 if (mapItr != callee2caller.end()) {
496 nid = mapItr->second;
Diego Novillod2938e42017-11-08 12:40:02 -0500497 } else {
GregFa699d1a2017-08-29 18:35:05 -0600498 nid = this->TakeNextId();
499 callee2caller[rid] = nid;
500 }
Greg Fischer04fcc662016-11-10 10:11:50 -0700501 cp_inst->SetResultId(nid);
Pierre Moreau5bd55f12018-02-20 19:19:57 +0100502 get_decoration_mgr()->CloneDecorations(rid, nid);
Greg Fischer04fcc662016-11-10 10:11:50 -0700503 }
504 new_blk_ptr->AddInstruction(std::move(cp_inst));
505 } break;
506 }
507 });
David Netoefff5fa2017-08-31 15:47:31 -0400508
David Neto25ddfec2017-09-02 19:01:03 -0400509 if (caller_is_loop_header && (new_blocks->size() > 1)) {
David Netoefff5fa2017-08-31 15:47:31 -0400510 // Move the OpLoopMerge from the last block back to the first, where
David Neto25ddfec2017-09-02 19:01:03 -0400511 // it belongs.
David Netoefff5fa2017-08-31 15:47:31 -0400512 auto& first = new_blocks->front();
513 auto& last = new_blocks->back();
514 assert(first != last);
515
516 // Insert a modified copy of the loop merge into the first block.
517 auto loop_merge_itr = last->tail();
518 --loop_merge_itr;
519 assert(loop_merge_itr->opcode() == SpvOpLoopMerge);
dan sinclairc7da51a2018-07-12 15:14:43 -0400520 std::unique_ptr<Instruction> cp_inst(loop_merge_itr->Clone(context()));
David Neto25ddfec2017-09-02 19:01:03 -0400521 if (caller_is_single_block_loop) {
522 // Also, update its continue target to point to the last block.
523 cp_inst->SetInOperand(kSpvLoopMergeContinueTargetIdInIdx, {last->id()});
524 }
David Netoefff5fa2017-08-31 15:47:31 -0400525 first->tail().InsertBefore(std::move(cp_inst));
526
527 // Remove the loop merge from the last block.
Steven Perronbb7802b2017-10-13 14:25:21 -0400528 loop_merge_itr->RemoveFromList();
529 delete &*loop_merge_itr;
David Netoefff5fa2017-08-31 15:47:31 -0400530 }
531
Greg Fischer04fcc662016-11-10 10:11:50 -0700532 // Update block map given replacement blocks.
533 for (auto& blk : *new_blocks) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600534 id2block_[blk->id()] = &*blk;
Greg Fischer04fcc662016-11-10 10:11:50 -0700535 }
536}
537
dan sinclairc7da51a2018-07-12 15:14:43 -0400538bool InlinePass::IsInlinableFunctionCall(const Instruction* inst) {
David Netoceb1d4f2017-03-31 10:36:58 -0400539 if (inst->opcode() != SpvOp::SpvOpFunctionCall) return false;
GregFa107d342017-04-25 13:57:20 -0600540 const uint32_t calleeFnId =
541 inst->GetSingleWordOperand(kSpvFunctionCallFunctionId);
542 const auto ci = inlinable_.find(calleeFnId);
543 return ci != inlinable_.cend();
David Netoceb1d4f2017-03-31 10:36:58 -0400544}
545
GregFe28bd392017-08-01 17:20:13 -0600546void InlinePass::UpdateSucceedingPhis(
dan sinclairc7da51a2018-07-12 15:14:43 -0400547 std::vector<std::unique_ptr<BasicBlock>>& new_blocks) {
GregFe28bd392017-08-01 17:20:13 -0600548 const auto firstBlk = new_blocks.begin();
549 const auto lastBlk = new_blocks.end() - 1;
550 const uint32_t firstId = (*firstBlk)->id();
551 const uint32_t lastId = (*lastBlk)->id();
dan sinclairc7da51a2018-07-12 15:14:43 -0400552 const BasicBlock& const_last_block = *lastBlk->get();
David Neto87f9cfa2018-02-02 14:17:42 -0800553 const_last_block.ForEachSuccessorLabel(
554 [&firstId, &lastId, this](const uint32_t succ) {
dan sinclairc7da51a2018-07-12 15:14:43 -0400555 BasicBlock* sbp = this->id2block_[succ];
556 sbp->ForEachPhiInst([&firstId, &lastId](Instruction* phi) {
David Neto87f9cfa2018-02-02 14:17:42 -0800557 phi->ForEachInId([&firstId, &lastId](uint32_t* id) {
558 if (*id == firstId) *id = lastId;
559 });
560 });
GregFe28bd392017-08-01 17:20:13 -0600561 });
Greg Fischer04fcc662016-11-10 10:11:50 -0700562}
563
dan sinclairc7da51a2018-07-12 15:14:43 -0400564bool InlinePass::HasMultipleReturns(Function* func) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600565 bool seenReturn = false;
566 bool multipleReturns = false;
567 for (auto& blk : *func) {
568 auto terminal_ii = blk.cend();
569 --terminal_ii;
Diego Novillod2938e42017-11-08 12:40:02 -0500570 if (terminal_ii->opcode() == SpvOpReturn ||
Greg Fischerbba812f2017-05-04 20:55:53 -0600571 terminal_ii->opcode() == SpvOpReturnValue) {
572 if (seenReturn) {
573 multipleReturns = true;
574 break;
575 }
576 seenReturn = true;
577 }
578 }
579 return multipleReturns;
580}
581
dan sinclairc7da51a2018-07-12 15:14:43 -0400582void InlinePass::ComputeStructuredSuccessors(Function* func) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600583 // If header, make merge block first successor.
584 for (auto& blk : *func) {
Diego Novillofef669f2017-10-30 17:42:26 -0400585 uint32_t mbid = blk.MergeBlockIdIfAny();
586 if (mbid != 0) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600587 block2structured_succs_[&blk].push_back(id2block_[mbid]);
Diego Novillofef669f2017-10-30 17:42:26 -0400588 }
589
590 // Add true successors.
David Neto87f9cfa2018-02-02 14:17:42 -0800591 const auto& const_blk = blk;
592 const_blk.ForEachSuccessorLabel([&blk, this](const uint32_t sbid) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600593 block2structured_succs_[&blk].push_back(id2block_[sbid]);
594 });
595 }
596}
Diego Novillofef669f2017-10-30 17:42:26 -0400597
Greg Fischerbba812f2017-05-04 20:55:53 -0600598InlinePass::GetBlocksFunction InlinePass::StructuredSuccessorsFunction() {
dan sinclairc7da51a2018-07-12 15:14:43 -0400599 return [this](const BasicBlock* block) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600600 return &(block2structured_succs_[block]);
601 };
602}
603
dan sinclairc7da51a2018-07-12 15:14:43 -0400604bool InlinePass::HasNoReturnInLoop(Function* func) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600605 // If control not structured, do not do loop/return analysis
606 // TODO: Analyze returns in non-structured control flow
Steven Perron756b2772017-12-19 14:18:13 -0500607 if (!context()->get_feature_mgr()->HasCapability(SpvCapabilityShader))
608 return false;
Greg Fischerbba812f2017-05-04 20:55:53 -0600609 // Compute structured block order. This order has the property
610 // that dominators are before all blocks they dominate and merge blocks
611 // are after all blocks that are in the control constructs of their header.
612 ComputeStructuredSuccessors(func);
613 auto ignore_block = [](cbb_ptr) {};
614 auto ignore_edge = [](cbb_ptr, cbb_ptr) {};
dan sinclairc7da51a2018-07-12 15:14:43 -0400615 std::list<const BasicBlock*> structuredOrder;
616 CFA<BasicBlock>::DepthFirstTraversal(
Diego Novillod2938e42017-11-08 12:40:02 -0500617 &*func->begin(), StructuredSuccessorsFunction(), ignore_block,
618 [&](cbb_ptr b) { structuredOrder.push_front(b); }, ignore_edge);
Greg Fischerbba812f2017-05-04 20:55:53 -0600619 // Search for returns in loops. Only need to track outermost loop
620 bool return_in_loop = false;
621 uint32_t outerLoopMergeId = 0;
622 for (auto& blk : structuredOrder) {
623 // Exiting current outer loop
Diego Novillod2938e42017-11-08 12:40:02 -0500624 if (blk->id() == outerLoopMergeId) outerLoopMergeId = 0;
Greg Fischerbba812f2017-05-04 20:55:53 -0600625 // Return block
626 auto terminal_ii = blk->cend();
627 --terminal_ii;
Diego Novillod2938e42017-11-08 12:40:02 -0500628 if (terminal_ii->opcode() == SpvOpReturn ||
Greg Fischerbba812f2017-05-04 20:55:53 -0600629 terminal_ii->opcode() == SpvOpReturnValue) {
630 if (outerLoopMergeId != 0) {
631 return_in_loop = true;
632 break;
633 }
Diego Novillod2938e42017-11-08 12:40:02 -0500634 } else if (terminal_ii != blk->cbegin()) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600635 auto merge_ii = terminal_ii;
636 --merge_ii;
637 // Entering outermost loop
638 if (merge_ii->opcode() == SpvOpLoopMerge && outerLoopMergeId == 0)
Diego Novillod2938e42017-11-08 12:40:02 -0500639 outerLoopMergeId =
640 merge_ii->GetSingleWordOperand(kSpvLoopMergeMergeBlockId);
Greg Fischerbba812f2017-05-04 20:55:53 -0600641 }
642 }
643 return !return_in_loop;
644}
645
dan sinclairc7da51a2018-07-12 15:14:43 -0400646void InlinePass::AnalyzeReturns(Function* func) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600647 // Look for multiple returns
648 if (!HasMultipleReturns(func)) {
649 no_return_in_loop_.insert(func->result_id());
650 return;
651 }
David Neto2a1014b2017-08-09 14:59:04 -0400652 multi_return_funcs_.insert(func->result_id());
Greg Fischerbba812f2017-05-04 20:55:53 -0600653 // If multiple returns, see if any are in a loop
Diego Novillod2938e42017-11-08 12:40:02 -0500654 if (HasNoReturnInLoop(func)) no_return_in_loop_.insert(func->result_id());
Greg Fischerbba812f2017-05-04 20:55:53 -0600655}
656
dan sinclairc7da51a2018-07-12 15:14:43 -0400657bool InlinePass::IsInlinableFunction(Function* func) {
GregFa107d342017-04-25 13:57:20 -0600658 // We can only inline a function if it has blocks.
Diego Novillod2938e42017-11-08 12:40:02 -0500659 if (func->cbegin() == func->cend()) return false;
Greg Fischerbba812f2017-05-04 20:55:53 -0600660 // Do not inline functions with returns in loops. Currently early return
661 // functions are inlined by wrapping them in a one trip loop and implementing
662 // the returns as a branch to the loop's merge block. However, this can only
663 // done validly if the return was not in a loop in the original function.
664 // Also remember functions with multiple (early) returns.
665 AnalyzeReturns(func);
David Netoefff5fa2017-08-31 15:47:31 -0400666 return no_return_in_loop_.find(func->result_id()) !=
667 no_return_in_loop_.cend();
GregFa107d342017-04-25 13:57:20 -0600668}
669
dan sinclairf96b7f12018-07-12 09:08:45 -0400670void InlinePass::InitializeInline() {
Greg Fischerbba812f2017-05-04 20:55:53 -0600671 false_id_ = 0;
672
GregFe28bd392017-08-01 17:20:13 -0600673 // clear collections
Greg Fischer04fcc662016-11-10 10:11:50 -0700674 id2function_.clear();
675 id2block_.clear();
Greg Fischerbba812f2017-05-04 20:55:53 -0600676 block2structured_succs_.clear();
GregFa107d342017-04-25 13:57:20 -0600677 inlinable_.clear();
GregFe28bd392017-08-01 17:20:13 -0600678 no_return_in_loop_.clear();
David Neto2a1014b2017-08-09 14:59:04 -0400679 multi_return_funcs_.clear();
GregFe28bd392017-08-01 17:20:13 -0600680
Diego Novillo1040a952017-10-25 13:26:25 -0400681 for (auto& fn : *get_module()) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600682 // Initialize function and block maps.
Greg Fischer04fcc662016-11-10 10:11:50 -0700683 id2function_[fn.result_id()] = &fn;
684 for (auto& blk : fn) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600685 id2block_[blk.id()] = &blk;
Greg Fischer04fcc662016-11-10 10:11:50 -0700686 }
Greg Fischerbba812f2017-05-04 20:55:53 -0600687 // Compute inlinability
Diego Novillod2938e42017-11-08 12:40:02 -0500688 if (IsInlinableFunction(&fn)) inlinable_.insert(fn.result_id());
Greg Fischer04fcc662016-11-10 10:11:50 -0700689 }
Eleni Maria Stea045cc8f2018-03-21 11:15:56 +0200690}
Greg Fischer04fcc662016-11-10 10:11:50 -0700691
Diego Novillo1040a952017-10-25 13:26:25 -0400692InlinePass::InlinePass() {}
Greg Fischer04fcc662016-11-10 10:11:50 -0700693
Greg Fischer04fcc662016-11-10 10:11:50 -0700694} // namespace opt
695} // namespace spvtools