blob: 8e4808d96a417f48db525099536d4790d017ae8d [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;
Greg Fischerbba812f2017-05-04 20:55:53 -060026static const int kSpvLoopMergeMergeBlockId = 0;
David Netoefff5fa2017-08-31 15:47:31 -040027static const int kSpvLoopMergeContinueTargetIdInIdx = 1;
Greg Fischer04fcc662016-11-10 10:11:50 -070028
29namespace spvtools {
30namespace opt {
31
Greg Fischer04fcc662016-11-10 10:11:50 -070032uint32_t InlinePass::AddPointerToType(uint32_t type_id,
33 SpvStorageClass storage_class) {
34 uint32_t resultId = TakeNextId();
35 std::unique_ptr<ir::Instruction> type_inst(new ir::Instruction(
Alan Bakera7717132017-11-14 14:11:50 -050036 context(), SpvOpTypePointer, 0, resultId,
Greg Fischer04fcc662016-11-10 10:11:50 -070037 {{spv_operand_type_t::SPV_OPERAND_TYPE_STORAGE_CLASS,
38 {uint32_t(storage_class)}},
39 {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {type_id}}}));
Steven Perron476cae62017-10-30 11:13:24 -040040 context()->AddType(std::move(type_inst));
Alan Baker61690852017-12-08 15:33:19 -050041 analysis::Type* pointeeTy;
42 std::unique_ptr<analysis::Pointer> pointerTy;
43 std::tie(pointeeTy, pointerTy) =
44 context()->get_type_mgr()->GetTypeAndPointerType(type_id,
45 SpvStorageClassFunction);
46 context()->get_type_mgr()->RegisterType(resultId, *pointerTy);
Greg Fischer04fcc662016-11-10 10:11:50 -070047 return resultId;
48}
49
50void InlinePass::AddBranch(uint32_t label_id,
Diego Novillod2938e42017-11-08 12:40:02 -050051 std::unique_ptr<ir::BasicBlock>* block_ptr) {
Greg Fischer04fcc662016-11-10 10:11:50 -070052 std::unique_ptr<ir::Instruction> newBranch(new ir::Instruction(
Alan Bakera7717132017-11-14 14:11:50 -050053 context(), SpvOpBranch, 0, 0,
Diego Novillod2938e42017-11-08 12:40:02 -050054 {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {label_id}}}));
Greg Fischer04fcc662016-11-10 10:11:50 -070055 (*block_ptr)->AddInstruction(std::move(newBranch));
56}
57
Greg Fischerbba812f2017-05-04 20:55:53 -060058void InlinePass::AddBranchCond(uint32_t cond_id, uint32_t true_id,
Diego Novillod2938e42017-11-08 12:40:02 -050059 uint32_t false_id,
60 std::unique_ptr<ir::BasicBlock>* block_ptr) {
Greg Fischerbba812f2017-05-04 20:55:53 -060061 std::unique_ptr<ir::Instruction> newBranch(new ir::Instruction(
Alan Bakera7717132017-11-14 14:11:50 -050062 context(), SpvOpBranchConditional, 0, 0,
Diego Novillod2938e42017-11-08 12:40:02 -050063 {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {cond_id}},
64 {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {true_id}},
65 {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {false_id}}}));
Greg Fischerbba812f2017-05-04 20:55:53 -060066 (*block_ptr)->AddInstruction(std::move(newBranch));
67}
68
69void InlinePass::AddLoopMerge(uint32_t merge_id, uint32_t continue_id,
Diego Novillod2938e42017-11-08 12:40:02 -050070 std::unique_ptr<ir::BasicBlock>* block_ptr) {
Greg Fischerbba812f2017-05-04 20:55:53 -060071 std::unique_ptr<ir::Instruction> newLoopMerge(new ir::Instruction(
Alan Bakera7717132017-11-14 14:11:50 -050072 context(), SpvOpLoopMerge, 0, 0,
Greg Fischerbba812f2017-05-04 20:55:53 -060073 {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {merge_id}},
74 {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {continue_id}},
75 {spv_operand_type_t::SPV_OPERAND_TYPE_LOOP_CONTROL, {0}}}));
76 (*block_ptr)->AddInstruction(std::move(newLoopMerge));
77}
78
Greg Fischer04fcc662016-11-10 10:11:50 -070079void InlinePass::AddStore(uint32_t ptr_id, uint32_t val_id,
80 std::unique_ptr<ir::BasicBlock>* block_ptr) {
81 std::unique_ptr<ir::Instruction> newStore(new ir::Instruction(
Alan Bakera7717132017-11-14 14:11:50 -050082 context(), SpvOpStore, 0, 0,
Diego Novillod2938e42017-11-08 12:40:02 -050083 {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {ptr_id}},
84 {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {val_id}}}));
Greg Fischer04fcc662016-11-10 10:11:50 -070085 (*block_ptr)->AddInstruction(std::move(newStore));
86}
87
88void InlinePass::AddLoad(uint32_t type_id, uint32_t resultId, uint32_t ptr_id,
89 std::unique_ptr<ir::BasicBlock>* block_ptr) {
90 std::unique_ptr<ir::Instruction> newLoad(new ir::Instruction(
Alan Bakera7717132017-11-14 14:11:50 -050091 context(), SpvOpLoad, type_id, resultId,
Greg Fischer04fcc662016-11-10 10:11:50 -070092 {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {ptr_id}}}));
93 (*block_ptr)->AddInstruction(std::move(newLoad));
94}
95
96std::unique_ptr<ir::Instruction> InlinePass::NewLabel(uint32_t label_id) {
97 std::unique_ptr<ir::Instruction> newLabel(
Alan Bakera7717132017-11-14 14:11:50 -050098 new ir::Instruction(context(), SpvOpLabel, 0, label_id, {}));
Greg Fischer04fcc662016-11-10 10:11:50 -070099 return newLabel;
100}
101
Greg Fischerbba812f2017-05-04 20:55:53 -0600102uint32_t InlinePass::GetFalseId() {
Diego Novillod2938e42017-11-08 12:40:02 -0500103 if (false_id_ != 0) return false_id_;
Diego Novillo1040a952017-10-25 13:26:25 -0400104 false_id_ = get_module()->GetGlobalValue(SpvOpConstantFalse);
Diego Novillod2938e42017-11-08 12:40:02 -0500105 if (false_id_ != 0) return false_id_;
Diego Novillo1040a952017-10-25 13:26:25 -0400106 uint32_t boolId = get_module()->GetGlobalValue(SpvOpTypeBool);
Greg Fischerbba812f2017-05-04 20:55:53 -0600107 if (boolId == 0) {
108 boolId = TakeNextId();
Diego Novillo1040a952017-10-25 13:26:25 -0400109 get_module()->AddGlobalValue(SpvOpTypeBool, boolId, 0);
Greg Fischerbba812f2017-05-04 20:55:53 -0600110 }
111 false_id_ = TakeNextId();
Diego Novillo1040a952017-10-25 13:26:25 -0400112 get_module()->AddGlobalValue(SpvOpConstantFalse, false_id_, boolId);
Greg Fischerbba812f2017-05-04 20:55:53 -0600113 return false_id_;
114}
115
Greg Fischer04fcc662016-11-10 10:11:50 -0700116void InlinePass::MapParams(
Diego Novillod2938e42017-11-08 12:40:02 -0500117 ir::Function* calleeFn, ir::BasicBlock::iterator call_inst_itr,
Greg Fischer04fcc662016-11-10 10:11:50 -0700118 std::unordered_map<uint32_t, uint32_t>* callee2caller) {
119 int param_idx = 0;
120 calleeFn->ForEachParam(
121 [&call_inst_itr, &param_idx, &callee2caller](const ir::Instruction* cpi) {
122 const uint32_t pid = cpi->result_id();
123 (*callee2caller)[pid] = call_inst_itr->GetSingleWordOperand(
124 kSpvFunctionCallArgumentId + param_idx);
Greg Fischerbba812f2017-05-04 20:55:53 -0600125 ++param_idx;
Greg Fischer04fcc662016-11-10 10:11:50 -0700126 });
127}
128
129void InlinePass::CloneAndMapLocals(
130 ir::Function* calleeFn,
131 std::vector<std::unique_ptr<ir::Instruction>>* new_vars,
132 std::unordered_map<uint32_t, uint32_t>* callee2caller) {
133 auto callee_block_itr = calleeFn->begin();
134 auto callee_var_itr = callee_block_itr->begin();
135 while (callee_var_itr->opcode() == SpvOp::SpvOpVariable) {
Alan Bakera7717132017-11-14 14:11:50 -0500136 std::unique_ptr<ir::Instruction> var_inst(
137 callee_var_itr->Clone(callee_var_itr->context()));
Greg Fischer04fcc662016-11-10 10:11:50 -0700138 uint32_t newId = TakeNextId();
Diego Novillo83228132017-11-27 10:16:41 -0500139 get_decoration_mgr()->CloneDecorations(callee_var_itr->result_id(), newId,
140 update_def_use_mgr_);
Greg Fischer04fcc662016-11-10 10:11:50 -0700141 var_inst->SetResultId(newId);
142 (*callee2caller)[callee_var_itr->result_id()] = newId;
143 new_vars->push_back(std::move(var_inst));
Greg Fischerbba812f2017-05-04 20:55:53 -0600144 ++callee_var_itr;
Greg Fischer04fcc662016-11-10 10:11:50 -0700145 }
146}
147
148uint32_t InlinePass::CreateReturnVar(
149 ir::Function* calleeFn,
150 std::vector<std::unique_ptr<ir::Instruction>>* new_vars) {
151 uint32_t returnVarId = 0;
152 const uint32_t calleeTypeId = calleeFn->type_id();
153 const ir::Instruction* calleeType =
Diego Novillo1040a952017-10-25 13:26:25 -0400154 get_def_use_mgr()->id_to_defs().find(calleeTypeId)->second;
Greg Fischer04fcc662016-11-10 10:11:50 -0700155 if (calleeType->opcode() != SpvOpTypeVoid) {
156 // Find or create ptr to callee return type.
Steven Perronb86eb682017-12-11 13:10:24 -0500157 uint32_t returnVarTypeId = context()->get_type_mgr()->FindPointerToType(
158 calleeTypeId, SpvStorageClassFunction);
Greg Fischer04fcc662016-11-10 10:11:50 -0700159 if (returnVarTypeId == 0)
160 returnVarTypeId = AddPointerToType(calleeTypeId, SpvStorageClassFunction);
161 // Add return var to new function scope variables.
162 returnVarId = TakeNextId();
163 std::unique_ptr<ir::Instruction> var_inst(new ir::Instruction(
Alan Bakera7717132017-11-14 14:11:50 -0500164 context(), SpvOpVariable, returnVarTypeId, returnVarId,
Greg Fischer04fcc662016-11-10 10:11:50 -0700165 {{spv_operand_type_t::SPV_OPERAND_TYPE_STORAGE_CLASS,
166 {SpvStorageClassFunction}}}));
167 new_vars->push_back(std::move(var_inst));
168 }
Diego Novillo83228132017-11-27 10:16:41 -0500169 get_decoration_mgr()->CloneDecorations(calleeFn->result_id(), returnVarId,
170 update_def_use_mgr_);
Greg Fischer04fcc662016-11-10 10:11:50 -0700171 return returnVarId;
172}
173
174bool InlinePass::IsSameBlockOp(const ir::Instruction* inst) const {
175 return inst->opcode() == SpvOpSampledImage || inst->opcode() == SpvOpImage;
176}
177
178void InlinePass::CloneSameBlockOps(
179 std::unique_ptr<ir::Instruction>* inst,
180 std::unordered_map<uint32_t, uint32_t>* postCallSB,
181 std::unordered_map<uint32_t, ir::Instruction*>* preCallSB,
182 std::unique_ptr<ir::BasicBlock>* block_ptr) {
Diego Novillo83228132017-11-27 10:16:41 -0500183 (*inst)->ForEachInId([&postCallSB, &preCallSB, &block_ptr,
184 this](uint32_t* iid) {
185 const auto mapItr = (*postCallSB).find(*iid);
186 if (mapItr == (*postCallSB).end()) {
187 const auto mapItr2 = (*preCallSB).find(*iid);
188 if (mapItr2 != (*preCallSB).end()) {
189 // Clone pre-call same-block ops, map result id.
190 const ir::Instruction* inInst = mapItr2->second;
191 std::unique_ptr<ir::Instruction> sb_inst(
192 inInst->Clone(inInst->context()));
193 CloneSameBlockOps(&sb_inst, postCallSB, preCallSB, block_ptr);
194 const uint32_t rid = sb_inst->result_id();
195 const uint32_t nid = this->TakeNextId();
196 get_decoration_mgr()->CloneDecorations(rid, nid, update_def_use_mgr_);
197 sb_inst->SetResultId(nid);
198 (*postCallSB)[rid] = nid;
199 *iid = nid;
200 (*block_ptr)->AddInstruction(std::move(sb_inst));
201 }
202 } else {
203 // Reset same-block op operand.
204 *iid = mapItr->second;
205 }
206 });
Greg Fischer04fcc662016-11-10 10:11:50 -0700207}
208
209void InlinePass::GenInlineCode(
210 std::vector<std::unique_ptr<ir::BasicBlock>>* new_blocks,
211 std::vector<std::unique_ptr<ir::Instruction>>* new_vars,
Steven Perronbb7802b2017-10-13 14:25:21 -0400212 ir::BasicBlock::iterator call_inst_itr,
Greg Fischer04fcc662016-11-10 10:11:50 -0700213 ir::UptrVectorIterator<ir::BasicBlock> call_block_itr) {
214 // Map from all ids in the callee to their equivalent id in the caller
215 // as callee instructions are copied into caller.
216 std::unordered_map<uint32_t, uint32_t> callee2caller;
217 // Pre-call same-block insts
218 std::unordered_map<uint32_t, ir::Instruction*> preCallSB;
219 // Post-call same-block op ids
220 std::unordered_map<uint32_t, uint32_t> postCallSB;
221
222 ir::Function* calleeFn = id2function_[call_inst_itr->GetSingleWordOperand(
223 kSpvFunctionCallFunctionId)];
224
David Neto2a1014b2017-08-09 14:59:04 -0400225 // Check for multiple returns in the callee.
226 auto fi = multi_return_funcs_.find(calleeFn->result_id());
227 const bool multiReturn = fi != multi_return_funcs_.end();
Greg Fischerbba812f2017-05-04 20:55:53 -0600228
Greg Fischer04fcc662016-11-10 10:11:50 -0700229 // Map parameters to actual arguments.
230 MapParams(calleeFn, call_inst_itr, &callee2caller);
231
232 // Define caller local variables for all callee variables and create map to
233 // them.
234 CloneAndMapLocals(calleeFn, new_vars, &callee2caller);
235
236 // Create return var if needed.
237 uint32_t returnVarId = CreateReturnVar(calleeFn, new_vars);
238
GregFa699d1a2017-08-29 18:35:05 -0600239 // Create set of callee result ids. Used to detect forward references
240 std::unordered_set<uint32_t> callee_result_ids;
Diego Novillod2938e42017-11-08 12:40:02 -0500241 calleeFn->ForEachInst([&callee_result_ids](const ir::Instruction* cpi) {
GregFa699d1a2017-08-29 18:35:05 -0600242 const uint32_t rid = cpi->result_id();
Diego Novillod2938e42017-11-08 12:40:02 -0500243 if (rid != 0) callee_result_ids.insert(rid);
GregFa699d1a2017-08-29 18:35:05 -0600244 });
245
David Netoefff5fa2017-08-31 15:47:31 -0400246 // If the caller is in a single-block loop, and the callee has multiple
247 // blocks, then the normal inlining logic will place the OpLoopMerge in
248 // the last of several blocks in the loop. Instead, it should be placed
249 // at the end of the first block. First determine if the caller is in a
250 // single block loop. We'll wait to move the OpLoopMerge until the end
251 // of the regular inlining logic, and only if necessary.
252 bool caller_is_single_block_loop = false;
David Neto25ddfec2017-09-02 19:01:03 -0400253 bool caller_is_loop_header = false;
David Netoefff5fa2017-08-31 15:47:31 -0400254 if (auto* loop_merge = call_block_itr->GetLoopMergeInst()) {
David Neto25ddfec2017-09-02 19:01:03 -0400255 caller_is_loop_header = true;
David Netoefff5fa2017-08-31 15:47:31 -0400256 caller_is_single_block_loop =
257 call_block_itr->id() ==
258 loop_merge->GetSingleWordInOperand(kSpvLoopMergeContinueTargetIdInIdx);
259 }
260
261 bool callee_begins_with_structured_header =
262 (*(calleeFn->begin())).GetMergeInst() != nullptr;
263
Greg Fischer04fcc662016-11-10 10:11:50 -0700264 // Clone and map callee code. Copy caller block code to beginning of
265 // first block and end of last block.
266 bool prevInstWasReturn = false;
Greg Fischerbba812f2017-05-04 20:55:53 -0600267 uint32_t singleTripLoopHeaderId = 0;
268 uint32_t singleTripLoopContinueId = 0;
Greg Fischer04fcc662016-11-10 10:11:50 -0700269 uint32_t returnLabelId = 0;
270 bool multiBlocks = false;
271 const uint32_t calleeTypeId = calleeFn->type_id();
David Neto2a1014b2017-08-09 14:59:04 -0400272 // new_blk_ptr is a new basic block in the caller. New instructions are
273 // written to it. It is created when we encounter the OpLabel
David Netoefff5fa2017-08-31 15:47:31 -0400274 // of the first callee block. It is appended to new_blocks only when
275 // it is complete.
Greg Fischer04fcc662016-11-10 10:11:50 -0700276 std::unique_ptr<ir::BasicBlock> new_blk_ptr;
277 calleeFn->ForEachInst([&new_blocks, &callee2caller, &call_block_itr,
278 &call_inst_itr, &new_blk_ptr, &prevInstWasReturn,
David Neto25ddfec2017-09-02 19:01:03 -0400279 &returnLabelId, &returnVarId, caller_is_loop_header,
David Netoefff5fa2017-08-31 15:47:31 -0400280 callee_begins_with_structured_header, &calleeTypeId,
David Neto2a1014b2017-08-09 14:59:04 -0400281 &multiBlocks, &postCallSB, &preCallSB, multiReturn,
Greg Fischerbba812f2017-05-04 20:55:53 -0600282 &singleTripLoopHeaderId, &singleTripLoopContinueId,
David Netoefff5fa2017-08-31 15:47:31 -0400283 &callee_result_ids, this](const ir::Instruction* cpi) {
Greg Fischer04fcc662016-11-10 10:11:50 -0700284 switch (cpi->opcode()) {
285 case SpvOpFunction:
286 case SpvOpFunctionParameter:
287 case SpvOpVariable:
288 // Already processed
289 break;
290 case SpvOpLabel: {
291 // If previous instruction was early return, insert branch
292 // instruction to return block.
293 if (prevInstWasReturn) {
294 if (returnLabelId == 0) returnLabelId = this->TakeNextId();
295 AddBranch(returnLabelId, &new_blk_ptr);
296 prevInstWasReturn = false;
297 }
298 // Finish current block (if it exists) and get label for next block.
299 uint32_t labelId;
300 bool firstBlock = false;
301 if (new_blk_ptr != nullptr) {
302 new_blocks->push_back(std::move(new_blk_ptr));
303 // If result id is already mapped, use it, otherwise get a new
304 // one.
305 const uint32_t rid = cpi->result_id();
306 const auto mapItr = callee2caller.find(rid);
307 labelId = (mapItr != callee2caller.end()) ? mapItr->second
308 : this->TakeNextId();
309 } else {
310 // First block needs to use label of original block
311 // but map callee label in case of phi reference.
Greg Fischerbba812f2017-05-04 20:55:53 -0600312 labelId = call_block_itr->id();
Greg Fischer04fcc662016-11-10 10:11:50 -0700313 callee2caller[cpi->result_id()] = labelId;
314 firstBlock = true;
315 }
316 // Create first/next block.
317 new_blk_ptr.reset(new ir::BasicBlock(NewLabel(labelId)));
318 if (firstBlock) {
319 // Copy contents of original caller block up to call instruction.
320 for (auto cii = call_block_itr->begin(); cii != call_inst_itr;
Greg Fischerbba812f2017-05-04 20:55:53 -0600321 ++cii) {
Alan Bakera7717132017-11-14 14:11:50 -0500322 std::unique_ptr<ir::Instruction> cp_inst(cii->Clone(context()));
Greg Fischer04fcc662016-11-10 10:11:50 -0700323 // Remember same-block ops for possible regeneration.
324 if (IsSameBlockOp(&*cp_inst)) {
325 auto* sb_inst_ptr = cp_inst.get();
326 preCallSB[cp_inst->result_id()] = sb_inst_ptr;
327 }
328 new_blk_ptr->AddInstruction(std::move(cp_inst));
329 }
Diego Novillod2938e42017-11-08 12:40:02 -0500330 if (caller_is_loop_header && callee_begins_with_structured_header) {
David Netoefff5fa2017-08-31 15:47:31 -0400331 // We can't place both the caller's merge instruction and another
332 // merge instruction in the same block. So split the calling block.
333 // Insert an unconditional branch to a new guard block. Later,
334 // once we know the ID of the last block, we will move the caller's
335 // OpLoopMerge from the last generated block into the first block.
336 // We also wait to avoid invalidating various iterators.
337 const auto guard_block_id = this->TakeNextId();
338 AddBranch(guard_block_id, &new_blk_ptr);
339 new_blocks->push_back(std::move(new_blk_ptr));
340 // Start the next block.
341 new_blk_ptr.reset(new ir::BasicBlock(NewLabel(guard_block_id)));
342 // Reset the mapping of the callee's entry block to point to
343 // the guard block. Do this so we can fix up phis later on to
344 // satisfy dominance.
345 callee2caller[cpi->result_id()] = guard_block_id;
346 }
347 // If callee has multiple returns, insert a header block for
David Neto2a1014b2017-08-09 14:59:04 -0400348 // single-trip loop that will encompass callee code. Start postheader
Greg Fischerbba812f2017-05-04 20:55:53 -0600349 // block.
David Netoefff5fa2017-08-31 15:47:31 -0400350 //
351 // Note: Consider the following combination:
352 // - the caller is a single block loop
353 // - the callee does not begin with a structure header
354 // - the callee has multiple returns.
355 // We still need to split the caller block and insert a guard block.
356 // But we only need to do it once. We haven't done it yet, but the
357 // single-trip loop header will serve the same purpose.
David Neto2a1014b2017-08-09 14:59:04 -0400358 if (multiReturn) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600359 singleTripLoopHeaderId = this->TakeNextId();
360 AddBranch(singleTripLoopHeaderId, &new_blk_ptr);
361 new_blocks->push_back(std::move(new_blk_ptr));
Diego Novillod2938e42017-11-08 12:40:02 -0500362 new_blk_ptr.reset(
363 new ir::BasicBlock(NewLabel(singleTripLoopHeaderId)));
Greg Fischerbba812f2017-05-04 20:55:53 -0600364 returnLabelId = this->TakeNextId();
365 singleTripLoopContinueId = this->TakeNextId();
366 AddLoopMerge(returnLabelId, singleTripLoopContinueId, &new_blk_ptr);
367 uint32_t postHeaderId = this->TakeNextId();
368 AddBranch(postHeaderId, &new_blk_ptr);
369 new_blocks->push_back(std::move(new_blk_ptr));
370 new_blk_ptr.reset(new ir::BasicBlock(NewLabel(postHeaderId)));
371 multiBlocks = true;
David Neto860c4192017-08-31 17:33:44 -0400372 // Reset the mapping of the callee's entry block to point to
373 // the post-header block. Do this so we can fix up phis later
374 // on to satisfy dominance.
375 callee2caller[cpi->result_id()] = postHeaderId;
Greg Fischerbba812f2017-05-04 20:55:53 -0600376 }
Greg Fischer04fcc662016-11-10 10:11:50 -0700377 } else {
378 multiBlocks = true;
379 }
380 } break;
381 case SpvOpReturnValue: {
382 // Store return value to return variable.
383 assert(returnVarId != 0);
384 uint32_t valId = cpi->GetInOperand(kSpvReturnValueId).words[0];
385 const auto mapItr = callee2caller.find(valId);
386 if (mapItr != callee2caller.end()) {
387 valId = mapItr->second;
388 }
389 AddStore(returnVarId, valId, &new_blk_ptr);
390
391 // Remember we saw a return; if followed by a label, will need to
392 // insert branch.
393 prevInstWasReturn = true;
394 } break;
395 case SpvOpReturn: {
396 // Remember we saw a return; if followed by a label, will need to
397 // insert branch.
398 prevInstWasReturn = true;
399 } break;
400 case SpvOpFunctionEnd: {
David Neto2a1014b2017-08-09 14:59:04 -0400401 // If there was an early return, we generated a return label id
402 // for it. Now we have to generate the return block with that Id.
Greg Fischer04fcc662016-11-10 10:11:50 -0700403 if (returnLabelId != 0) {
David Neto2a1014b2017-08-09 14:59:04 -0400404 // If previous instruction was return, insert branch instruction
405 // to return block.
Greg Fischer04fcc662016-11-10 10:11:50 -0700406 if (prevInstWasReturn) AddBranch(returnLabelId, &new_blk_ptr);
David Neto2a1014b2017-08-09 14:59:04 -0400407 if (multiReturn) {
408 // If we generated a loop header to for the single-trip loop
409 // to accommodate multiple returns, insert the continue
410 // target block now, with a false branch back to the loop header.
411 new_blocks->push_back(std::move(new_blk_ptr));
412 new_blk_ptr.reset(
413 new ir::BasicBlock(NewLabel(singleTripLoopContinueId)));
414 AddBranchCond(GetFalseId(), singleTripLoopHeaderId, returnLabelId,
415 &new_blk_ptr);
416 }
417 // Generate the return block.
Greg Fischerbba812f2017-05-04 20:55:53 -0600418 new_blocks->push_back(std::move(new_blk_ptr));
Greg Fischer04fcc662016-11-10 10:11:50 -0700419 new_blk_ptr.reset(new ir::BasicBlock(NewLabel(returnLabelId)));
420 multiBlocks = true;
421 }
422 // Load return value into result id of call, if it exists.
423 if (returnVarId != 0) {
424 const uint32_t resId = call_inst_itr->result_id();
425 assert(resId != 0);
426 AddLoad(calleeTypeId, resId, returnVarId, &new_blk_ptr);
427 }
428 // Copy remaining instructions from caller block.
429 auto cii = call_inst_itr;
Greg Fischerbba812f2017-05-04 20:55:53 -0600430 for (++cii; cii != call_block_itr->end(); ++cii) {
Alan Bakera7717132017-11-14 14:11:50 -0500431 std::unique_ptr<ir::Instruction> cp_inst(cii->Clone(context()));
Greg Fischer04fcc662016-11-10 10:11:50 -0700432 // If multiple blocks generated, regenerate any same-block
433 // instruction that has not been seen in this last block.
434 if (multiBlocks) {
435 CloneSameBlockOps(&cp_inst, &postCallSB, &preCallSB, &new_blk_ptr);
436 // Remember same-block ops in this block.
437 if (IsSameBlockOp(&*cp_inst)) {
438 const uint32_t rid = cp_inst->result_id();
439 postCallSB[rid] = rid;
440 }
441 }
442 new_blk_ptr->AddInstruction(std::move(cp_inst));
443 }
444 // Finalize inline code.
445 new_blocks->push_back(std::move(new_blk_ptr));
446 } break;
447 default: {
448 // Copy callee instruction and remap all input Ids.
Alan Bakera7717132017-11-14 14:11:50 -0500449 std::unique_ptr<ir::Instruction> cp_inst(cpi->Clone(context()));
David Netoefff5fa2017-08-31 15:47:31 -0400450 cp_inst->ForEachInId([&callee2caller, &callee_result_ids,
451 this](uint32_t* iid) {
Greg Fischer04fcc662016-11-10 10:11:50 -0700452 const auto mapItr = callee2caller.find(*iid);
453 if (mapItr != callee2caller.end()) {
454 *iid = mapItr->second;
GregFa699d1a2017-08-29 18:35:05 -0600455 } else if (callee_result_ids.find(*iid) != callee_result_ids.end()) {
456 // Forward reference. Allocate a new id, map it,
457 // use it and check for it when remapping result ids
458 const uint32_t nid = this->TakeNextId();
459 callee2caller[*iid] = nid;
460 *iid = nid;
Greg Fischer04fcc662016-11-10 10:11:50 -0700461 }
462 });
GregFa699d1a2017-08-29 18:35:05 -0600463 // If result id is non-zero, remap it. If already mapped, use mapped
464 // value, else use next id.
Greg Fischer04fcc662016-11-10 10:11:50 -0700465 const uint32_t rid = cp_inst->result_id();
466 if (rid != 0) {
GregFa699d1a2017-08-29 18:35:05 -0600467 const auto mapItr = callee2caller.find(rid);
468 uint32_t nid;
469 if (mapItr != callee2caller.end()) {
470 nid = mapItr->second;
Diego Novillod2938e42017-11-08 12:40:02 -0500471 } else {
GregFa699d1a2017-08-29 18:35:05 -0600472 nid = this->TakeNextId();
473 callee2caller[rid] = nid;
474 }
Greg Fischer04fcc662016-11-10 10:11:50 -0700475 cp_inst->SetResultId(nid);
Steven Perroneb4653a2017-11-13 15:31:43 -0500476 get_decoration_mgr()->CloneDecorations(rid, nid, update_def_use_mgr_);
Greg Fischer04fcc662016-11-10 10:11:50 -0700477 }
478 new_blk_ptr->AddInstruction(std::move(cp_inst));
479 } break;
480 }
481 });
David Netoefff5fa2017-08-31 15:47:31 -0400482
David Neto25ddfec2017-09-02 19:01:03 -0400483 if (caller_is_loop_header && (new_blocks->size() > 1)) {
David Netoefff5fa2017-08-31 15:47:31 -0400484 // Move the OpLoopMerge from the last block back to the first, where
David Neto25ddfec2017-09-02 19:01:03 -0400485 // it belongs.
David Netoefff5fa2017-08-31 15:47:31 -0400486 auto& first = new_blocks->front();
487 auto& last = new_blocks->back();
488 assert(first != last);
489
490 // Insert a modified copy of the loop merge into the first block.
491 auto loop_merge_itr = last->tail();
492 --loop_merge_itr;
493 assert(loop_merge_itr->opcode() == SpvOpLoopMerge);
Alan Bakera7717132017-11-14 14:11:50 -0500494 std::unique_ptr<ir::Instruction> cp_inst(loop_merge_itr->Clone(context()));
David Neto25ddfec2017-09-02 19:01:03 -0400495 if (caller_is_single_block_loop) {
496 // Also, update its continue target to point to the last block.
497 cp_inst->SetInOperand(kSpvLoopMergeContinueTargetIdInIdx, {last->id()});
498 }
David Netoefff5fa2017-08-31 15:47:31 -0400499 first->tail().InsertBefore(std::move(cp_inst));
500
501 // Remove the loop merge from the last block.
Steven Perronbb7802b2017-10-13 14:25:21 -0400502 loop_merge_itr->RemoveFromList();
503 delete &*loop_merge_itr;
David Netoefff5fa2017-08-31 15:47:31 -0400504 }
505
Greg Fischer04fcc662016-11-10 10:11:50 -0700506 // Update block map given replacement blocks.
507 for (auto& blk : *new_blocks) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600508 id2block_[blk->id()] = &*blk;
Greg Fischer04fcc662016-11-10 10:11:50 -0700509 }
510}
511
David Netoceb1d4f2017-03-31 10:36:58 -0400512bool InlinePass::IsInlinableFunctionCall(const ir::Instruction* inst) {
513 if (inst->opcode() != SpvOp::SpvOpFunctionCall) return false;
GregFa107d342017-04-25 13:57:20 -0600514 const uint32_t calleeFnId =
515 inst->GetSingleWordOperand(kSpvFunctionCallFunctionId);
516 const auto ci = inlinable_.find(calleeFnId);
517 return ci != inlinable_.cend();
David Netoceb1d4f2017-03-31 10:36:58 -0400518}
519
GregFe28bd392017-08-01 17:20:13 -0600520void InlinePass::UpdateSucceedingPhis(
521 std::vector<std::unique_ptr<ir::BasicBlock>>& new_blocks) {
522 const auto firstBlk = new_blocks.begin();
523 const auto lastBlk = new_blocks.end() - 1;
524 const uint32_t firstId = (*firstBlk)->id();
525 const uint32_t lastId = (*lastBlk)->id();
Diego Novillod2938e42017-11-08 12:40:02 -0500526 (*lastBlk)->ForEachSuccessorLabel([&firstId, &lastId, this](uint32_t succ) {
527 ir::BasicBlock* sbp = this->id2block_[succ];
528 sbp->ForEachPhiInst([&firstId, &lastId](ir::Instruction* phi) {
529 phi->ForEachInId([&firstId, &lastId](uint32_t* id) {
530 if (*id == firstId) *id = lastId;
GregFe28bd392017-08-01 17:20:13 -0600531 });
Diego Novillod2938e42017-11-08 12:40:02 -0500532 });
533 });
Greg Fischer04fcc662016-11-10 10:11:50 -0700534}
535
Greg Fischerbba812f2017-05-04 20:55:53 -0600536bool InlinePass::HasMultipleReturns(ir::Function* func) {
537 bool seenReturn = false;
538 bool multipleReturns = false;
539 for (auto& blk : *func) {
540 auto terminal_ii = blk.cend();
541 --terminal_ii;
Diego Novillod2938e42017-11-08 12:40:02 -0500542 if (terminal_ii->opcode() == SpvOpReturn ||
Greg Fischerbba812f2017-05-04 20:55:53 -0600543 terminal_ii->opcode() == SpvOpReturnValue) {
544 if (seenReturn) {
545 multipleReturns = true;
546 break;
547 }
548 seenReturn = true;
549 }
550 }
551 return multipleReturns;
552}
553
Greg Fischerbba812f2017-05-04 20:55:53 -0600554void InlinePass::ComputeStructuredSuccessors(ir::Function* func) {
555 // If header, make merge block first successor.
556 for (auto& blk : *func) {
Diego Novillofef669f2017-10-30 17:42:26 -0400557 uint32_t mbid = blk.MergeBlockIdIfAny();
558 if (mbid != 0) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600559 block2structured_succs_[&blk].push_back(id2block_[mbid]);
Diego Novillofef669f2017-10-30 17:42:26 -0400560 }
561
562 // Add true successors.
Greg Fischerbba812f2017-05-04 20:55:53 -0600563 blk.ForEachSuccessorLabel([&blk, this](uint32_t sbid) {
564 block2structured_succs_[&blk].push_back(id2block_[sbid]);
565 });
566 }
567}
Diego Novillofef669f2017-10-30 17:42:26 -0400568
Greg Fischerbba812f2017-05-04 20:55:53 -0600569InlinePass::GetBlocksFunction InlinePass::StructuredSuccessorsFunction() {
570 return [this](const ir::BasicBlock* block) {
571 return &(block2structured_succs_[block]);
572 };
573}
574
575bool InlinePass::HasNoReturnInLoop(ir::Function* func) {
576 // If control not structured, do not do loop/return analysis
577 // TODO: Analyze returns in non-structured control flow
Steven Perron756b2772017-12-19 14:18:13 -0500578 if (!context()->get_feature_mgr()->HasCapability(SpvCapabilityShader))
579 return false;
Greg Fischerbba812f2017-05-04 20:55:53 -0600580 // Compute structured block order. This order has the property
581 // that dominators are before all blocks they dominate and merge blocks
582 // are after all blocks that are in the control constructs of their header.
583 ComputeStructuredSuccessors(func);
584 auto ignore_block = [](cbb_ptr) {};
585 auto ignore_edge = [](cbb_ptr, cbb_ptr) {};
586 std::list<const ir::BasicBlock*> structuredOrder;
587 spvtools::CFA<ir::BasicBlock>::DepthFirstTraversal(
Diego Novillod2938e42017-11-08 12:40:02 -0500588 &*func->begin(), StructuredSuccessorsFunction(), ignore_block,
589 [&](cbb_ptr b) { structuredOrder.push_front(b); }, ignore_edge);
Greg Fischerbba812f2017-05-04 20:55:53 -0600590 // Search for returns in loops. Only need to track outermost loop
591 bool return_in_loop = false;
592 uint32_t outerLoopMergeId = 0;
593 for (auto& blk : structuredOrder) {
594 // Exiting current outer loop
Diego Novillod2938e42017-11-08 12:40:02 -0500595 if (blk->id() == outerLoopMergeId) outerLoopMergeId = 0;
Greg Fischerbba812f2017-05-04 20:55:53 -0600596 // Return block
597 auto terminal_ii = blk->cend();
598 --terminal_ii;
Diego Novillod2938e42017-11-08 12:40:02 -0500599 if (terminal_ii->opcode() == SpvOpReturn ||
Greg Fischerbba812f2017-05-04 20:55:53 -0600600 terminal_ii->opcode() == SpvOpReturnValue) {
601 if (outerLoopMergeId != 0) {
602 return_in_loop = true;
603 break;
604 }
Diego Novillod2938e42017-11-08 12:40:02 -0500605 } else if (terminal_ii != blk->cbegin()) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600606 auto merge_ii = terminal_ii;
607 --merge_ii;
608 // Entering outermost loop
609 if (merge_ii->opcode() == SpvOpLoopMerge && outerLoopMergeId == 0)
Diego Novillod2938e42017-11-08 12:40:02 -0500610 outerLoopMergeId =
611 merge_ii->GetSingleWordOperand(kSpvLoopMergeMergeBlockId);
Greg Fischerbba812f2017-05-04 20:55:53 -0600612 }
613 }
614 return !return_in_loop;
615}
616
617void InlinePass::AnalyzeReturns(ir::Function* func) {
618 // Look for multiple returns
619 if (!HasMultipleReturns(func)) {
620 no_return_in_loop_.insert(func->result_id());
621 return;
622 }
David Neto2a1014b2017-08-09 14:59:04 -0400623 multi_return_funcs_.insert(func->result_id());
Greg Fischerbba812f2017-05-04 20:55:53 -0600624 // If multiple returns, see if any are in a loop
Diego Novillod2938e42017-11-08 12:40:02 -0500625 if (HasNoReturnInLoop(func)) no_return_in_loop_.insert(func->result_id());
Greg Fischerbba812f2017-05-04 20:55:53 -0600626}
627
628bool InlinePass::IsInlinableFunction(ir::Function* func) {
GregFa107d342017-04-25 13:57:20 -0600629 // We can only inline a function if it has blocks.
Diego Novillod2938e42017-11-08 12:40:02 -0500630 if (func->cbegin() == func->cend()) return false;
Greg Fischerbba812f2017-05-04 20:55:53 -0600631 // Do not inline functions with returns in loops. Currently early return
632 // functions are inlined by wrapping them in a one trip loop and implementing
633 // the returns as a branch to the loop's merge block. However, this can only
634 // done validly if the return was not in a loop in the original function.
635 // Also remember functions with multiple (early) returns.
636 AnalyzeReturns(func);
David Netoefff5fa2017-08-31 15:47:31 -0400637 return no_return_in_loop_.find(func->result_id()) !=
638 no_return_in_loop_.cend();
GregFa107d342017-04-25 13:57:20 -0600639}
640
Steven Perron476cae62017-10-30 11:13:24 -0400641void InlinePass::InitializeInline(ir::IRContext* c) {
642 InitializeProcessing(c);
Greg Fischer04fcc662016-11-10 10:11:50 -0700643
Alan Baker746bfd22017-11-14 14:11:50 -0500644 // Don't bother updating the DefUseManger
Pierre Moreau69043962017-11-30 22:32:44 +0100645 update_def_use_mgr_ = [](ir::Instruction&, bool) {};
Daniel Schürmanna76d0972017-10-24 18:28:18 +0200646
Greg Fischerbba812f2017-05-04 20:55:53 -0600647 false_id_ = 0;
648
GregFe28bd392017-08-01 17:20:13 -0600649 // clear collections
Greg Fischer04fcc662016-11-10 10:11:50 -0700650 id2function_.clear();
651 id2block_.clear();
Greg Fischerbba812f2017-05-04 20:55:53 -0600652 block2structured_succs_.clear();
GregFa107d342017-04-25 13:57:20 -0600653 inlinable_.clear();
GregFe28bd392017-08-01 17:20:13 -0600654 no_return_in_loop_.clear();
David Neto2a1014b2017-08-09 14:59:04 -0400655 multi_return_funcs_.clear();
GregFe28bd392017-08-01 17:20:13 -0600656
Diego Novillo1040a952017-10-25 13:26:25 -0400657 for (auto& fn : *get_module()) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600658 // Initialize function and block maps.
Greg Fischer04fcc662016-11-10 10:11:50 -0700659 id2function_[fn.result_id()] = &fn;
660 for (auto& blk : fn) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600661 id2block_[blk.id()] = &blk;
Greg Fischer04fcc662016-11-10 10:11:50 -0700662 }
Greg Fischerbba812f2017-05-04 20:55:53 -0600663 // Compute inlinability
Diego Novillod2938e42017-11-08 12:40:02 -0500664 if (IsInlinableFunction(&fn)) inlinable_.insert(fn.result_id());
Greg Fischer04fcc662016-11-10 10:11:50 -0700665 }
666};
667
Diego Novillo1040a952017-10-25 13:26:25 -0400668InlinePass::InlinePass() {}
Greg Fischer04fcc662016-11-10 10:11:50 -0700669
Greg Fischer04fcc662016-11-10 10:11:50 -0700670} // namespace opt
671} // namespace spvtools