blob: 706af448252e3627bb743da76dcbaf79bf32f8e5 [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 Fischer04fcc662016-11-10 10:11:50 -070030
31namespace spvtools {
32namespace opt {
33
34uint32_t InlinePass::FindPointerToType(uint32_t type_id,
35 SpvStorageClass storage_class) {
Diego Novillo1040a952017-10-25 13:26:25 -040036 ir::Module::inst_iterator type_itr = get_module()->types_values_begin();
37 for (; type_itr != get_module()->types_values_end(); ++type_itr) {
Greg Fischer04fcc662016-11-10 10:11:50 -070038 const ir::Instruction* type_inst = &*type_itr;
39 if (type_inst->opcode() == SpvOpTypePointer &&
40 type_inst->GetSingleWordOperand(kSpvTypePointerTypeId) == type_id &&
41 type_inst->GetSingleWordOperand(kSpvTypePointerStorageClass) ==
42 storage_class)
43 return type_inst->result_id();
44 }
45 return 0;
46}
47
48uint32_t InlinePass::AddPointerToType(uint32_t type_id,
49 SpvStorageClass storage_class) {
50 uint32_t resultId = TakeNextId();
51 std::unique_ptr<ir::Instruction> type_inst(new ir::Instruction(
52 SpvOpTypePointer, 0, resultId,
53 {{spv_operand_type_t::SPV_OPERAND_TYPE_STORAGE_CLASS,
54 {uint32_t(storage_class)}},
55 {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {type_id}}}));
Steven Perron476cae62017-10-30 11:13:24 -040056 context()->AddType(std::move(type_inst));
Greg Fischer04fcc662016-11-10 10:11:50 -070057 return resultId;
58}
59
60void InlinePass::AddBranch(uint32_t label_id,
Diego Novillod2938e42017-11-08 12:40:02 -050061 std::unique_ptr<ir::BasicBlock>* block_ptr) {
Greg Fischer04fcc662016-11-10 10:11:50 -070062 std::unique_ptr<ir::Instruction> newBranch(new ir::Instruction(
Diego Novillod2938e42017-11-08 12:40:02 -050063 SpvOpBranch, 0, 0,
64 {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {label_id}}}));
Greg Fischer04fcc662016-11-10 10:11:50 -070065 (*block_ptr)->AddInstruction(std::move(newBranch));
66}
67
Greg Fischerbba812f2017-05-04 20:55:53 -060068void InlinePass::AddBranchCond(uint32_t cond_id, uint32_t true_id,
Diego Novillod2938e42017-11-08 12:40:02 -050069 uint32_t false_id,
70 std::unique_ptr<ir::BasicBlock>* block_ptr) {
Greg Fischerbba812f2017-05-04 20:55:53 -060071 std::unique_ptr<ir::Instruction> newBranch(new ir::Instruction(
Diego Novillod2938e42017-11-08 12:40:02 -050072 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}}}));
Greg Fischerbba812f2017-05-04 20:55:53 -060076 (*block_ptr)->AddInstruction(std::move(newBranch));
77}
78
79void InlinePass::AddLoopMerge(uint32_t merge_id, uint32_t continue_id,
Diego Novillod2938e42017-11-08 12:40:02 -050080 std::unique_ptr<ir::BasicBlock>* block_ptr) {
Greg Fischerbba812f2017-05-04 20:55:53 -060081 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(
Diego Novillod2938e42017-11-08 12:40:02 -050092 SpvOpStore, 0, 0,
93 {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {ptr_id}},
94 {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {val_id}}}));
Greg Fischer04fcc662016-11-10 10:11:50 -070095 (*block_ptr)->AddInstruction(std::move(newStore));
96}
97
98void InlinePass::AddLoad(uint32_t type_id, uint32_t resultId, uint32_t ptr_id,
99 std::unique_ptr<ir::BasicBlock>* block_ptr) {
100 std::unique_ptr<ir::Instruction> newLoad(new ir::Instruction(
101 SpvOpLoad, type_id, resultId,
102 {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {ptr_id}}}));
103 (*block_ptr)->AddInstruction(std::move(newLoad));
104}
105
106std::unique_ptr<ir::Instruction> InlinePass::NewLabel(uint32_t label_id) {
107 std::unique_ptr<ir::Instruction> newLabel(
108 new ir::Instruction(SpvOpLabel, 0, label_id, {}));
109 return newLabel;
110}
111
Greg Fischerbba812f2017-05-04 20:55:53 -0600112uint32_t InlinePass::GetFalseId() {
Diego Novillod2938e42017-11-08 12:40:02 -0500113 if (false_id_ != 0) return false_id_;
Diego Novillo1040a952017-10-25 13:26:25 -0400114 false_id_ = get_module()->GetGlobalValue(SpvOpConstantFalse);
Diego Novillod2938e42017-11-08 12:40:02 -0500115 if (false_id_ != 0) return false_id_;
Diego Novillo1040a952017-10-25 13:26:25 -0400116 uint32_t boolId = get_module()->GetGlobalValue(SpvOpTypeBool);
Greg Fischerbba812f2017-05-04 20:55:53 -0600117 if (boolId == 0) {
118 boolId = TakeNextId();
Diego Novillo1040a952017-10-25 13:26:25 -0400119 get_module()->AddGlobalValue(SpvOpTypeBool, boolId, 0);
Greg Fischerbba812f2017-05-04 20:55:53 -0600120 }
121 false_id_ = TakeNextId();
Diego Novillo1040a952017-10-25 13:26:25 -0400122 get_module()->AddGlobalValue(SpvOpConstantFalse, false_id_, boolId);
Greg Fischerbba812f2017-05-04 20:55:53 -0600123 return false_id_;
124}
125
Greg Fischer04fcc662016-11-10 10:11:50 -0700126void InlinePass::MapParams(
Diego Novillod2938e42017-11-08 12:40:02 -0500127 ir::Function* calleeFn, ir::BasicBlock::iterator call_inst_itr,
Greg Fischer04fcc662016-11-10 10:11:50 -0700128 std::unordered_map<uint32_t, uint32_t>* callee2caller) {
129 int param_idx = 0;
130 calleeFn->ForEachParam(
131 [&call_inst_itr, &param_idx, &callee2caller](const ir::Instruction* cpi) {
132 const uint32_t pid = cpi->result_id();
133 (*callee2caller)[pid] = call_inst_itr->GetSingleWordOperand(
134 kSpvFunctionCallArgumentId + param_idx);
Greg Fischerbba812f2017-05-04 20:55:53 -0600135 ++param_idx;
Greg Fischer04fcc662016-11-10 10:11:50 -0700136 });
137}
138
139void InlinePass::CloneAndMapLocals(
140 ir::Function* calleeFn,
141 std::vector<std::unique_ptr<ir::Instruction>>* new_vars,
142 std::unordered_map<uint32_t, uint32_t>* callee2caller) {
143 auto callee_block_itr = calleeFn->begin();
144 auto callee_var_itr = callee_block_itr->begin();
145 while (callee_var_itr->opcode() == SpvOp::SpvOpVariable) {
Steven Perronbb7802b2017-10-13 14:25:21 -0400146 std::unique_ptr<ir::Instruction> var_inst(callee_var_itr->Clone());
Greg Fischer04fcc662016-11-10 10:11:50 -0700147 uint32_t newId = TakeNextId();
148 var_inst->SetResultId(newId);
149 (*callee2caller)[callee_var_itr->result_id()] = newId;
150 new_vars->push_back(std::move(var_inst));
Greg Fischerbba812f2017-05-04 20:55:53 -0600151 ++callee_var_itr;
Greg Fischer04fcc662016-11-10 10:11:50 -0700152 }
153}
154
155uint32_t InlinePass::CreateReturnVar(
156 ir::Function* calleeFn,
157 std::vector<std::unique_ptr<ir::Instruction>>* new_vars) {
158 uint32_t returnVarId = 0;
159 const uint32_t calleeTypeId = calleeFn->type_id();
160 const ir::Instruction* calleeType =
Diego Novillo1040a952017-10-25 13:26:25 -0400161 get_def_use_mgr()->id_to_defs().find(calleeTypeId)->second;
Greg Fischer04fcc662016-11-10 10:11:50 -0700162 if (calleeType->opcode() != SpvOpTypeVoid) {
163 // Find or create ptr to callee return type.
164 uint32_t returnVarTypeId =
165 FindPointerToType(calleeTypeId, SpvStorageClassFunction);
166 if (returnVarTypeId == 0)
167 returnVarTypeId = AddPointerToType(calleeTypeId, SpvStorageClassFunction);
168 // Add return var to new function scope variables.
169 returnVarId = TakeNextId();
170 std::unique_ptr<ir::Instruction> var_inst(new ir::Instruction(
171 SpvOpVariable, returnVarTypeId, returnVarId,
172 {{spv_operand_type_t::SPV_OPERAND_TYPE_STORAGE_CLASS,
173 {SpvStorageClassFunction}}}));
174 new_vars->push_back(std::move(var_inst));
175 }
176 return returnVarId;
177}
178
179bool InlinePass::IsSameBlockOp(const ir::Instruction* inst) const {
180 return inst->opcode() == SpvOpSampledImage || inst->opcode() == SpvOpImage;
181}
182
183void InlinePass::CloneSameBlockOps(
184 std::unique_ptr<ir::Instruction>* inst,
185 std::unordered_map<uint32_t, uint32_t>* postCallSB,
186 std::unordered_map<uint32_t, ir::Instruction*>* preCallSB,
187 std::unique_ptr<ir::BasicBlock>* block_ptr) {
Diego Novillod2938e42017-11-08 12:40:02 -0500188 (*inst)->ForEachInId(
189 [&postCallSB, &preCallSB, &block_ptr, this](uint32_t* iid) {
Greg Fischer04fcc662016-11-10 10:11:50 -0700190 const auto mapItr = (*postCallSB).find(*iid);
191 if (mapItr == (*postCallSB).end()) {
192 const auto mapItr2 = (*preCallSB).find(*iid);
193 if (mapItr2 != (*preCallSB).end()) {
194 // Clone pre-call same-block ops, map result id.
195 const ir::Instruction* inInst = mapItr2->second;
Steven Perronbb7802b2017-10-13 14:25:21 -0400196 std::unique_ptr<ir::Instruction> sb_inst(inInst->Clone());
Greg Fischer04fcc662016-11-10 10:11:50 -0700197 CloneSameBlockOps(&sb_inst, postCallSB, preCallSB, block_ptr);
198 const uint32_t rid = sb_inst->result_id();
199 const uint32_t nid = this->TakeNextId();
200 sb_inst->SetResultId(nid);
201 (*postCallSB)[rid] = nid;
202 *iid = nid;
203 (*block_ptr)->AddInstruction(std::move(sb_inst));
204 }
205 } else {
206 // Reset same-block op operand.
207 *iid = mapItr->second;
208 }
209 });
210}
211
212void InlinePass::GenInlineCode(
213 std::vector<std::unique_ptr<ir::BasicBlock>>* new_blocks,
214 std::vector<std::unique_ptr<ir::Instruction>>* new_vars,
Steven Perronbb7802b2017-10-13 14:25:21 -0400215 ir::BasicBlock::iterator call_inst_itr,
Greg Fischer04fcc662016-11-10 10:11:50 -0700216 ir::UptrVectorIterator<ir::BasicBlock> call_block_itr) {
217 // Map from all ids in the callee to their equivalent id in the caller
218 // as callee instructions are copied into caller.
219 std::unordered_map<uint32_t, uint32_t> callee2caller;
220 // Pre-call same-block insts
221 std::unordered_map<uint32_t, ir::Instruction*> preCallSB;
222 // Post-call same-block op ids
223 std::unordered_map<uint32_t, uint32_t> postCallSB;
224
225 ir::Function* calleeFn = id2function_[call_inst_itr->GetSingleWordOperand(
226 kSpvFunctionCallFunctionId)];
227
David Neto2a1014b2017-08-09 14:59:04 -0400228 // Check for multiple returns in the callee.
229 auto fi = multi_return_funcs_.find(calleeFn->result_id());
230 const bool multiReturn = fi != multi_return_funcs_.end();
Greg Fischerbba812f2017-05-04 20:55:53 -0600231
Greg Fischer04fcc662016-11-10 10:11:50 -0700232 // Map parameters to actual arguments.
233 MapParams(calleeFn, call_inst_itr, &callee2caller);
234
235 // Define caller local variables for all callee variables and create map to
236 // them.
237 CloneAndMapLocals(calleeFn, new_vars, &callee2caller);
238
239 // Create return var if needed.
240 uint32_t returnVarId = CreateReturnVar(calleeFn, new_vars);
241
GregFa699d1a2017-08-29 18:35:05 -0600242 // Create set of callee result ids. Used to detect forward references
243 std::unordered_set<uint32_t> callee_result_ids;
Diego Novillod2938e42017-11-08 12:40:02 -0500244 calleeFn->ForEachInst([&callee_result_ids](const ir::Instruction* cpi) {
GregFa699d1a2017-08-29 18:35:05 -0600245 const uint32_t rid = cpi->result_id();
Diego Novillod2938e42017-11-08 12:40:02 -0500246 if (rid != 0) callee_result_ids.insert(rid);
GregFa699d1a2017-08-29 18:35:05 -0600247 });
248
David Netoefff5fa2017-08-31 15:47:31 -0400249 // If the caller is in a single-block loop, and the callee has multiple
250 // blocks, then the normal inlining logic will place the OpLoopMerge in
251 // the last of several blocks in the loop. Instead, it should be placed
252 // at the end of the first block. First determine if the caller is in a
253 // single block loop. We'll wait to move the OpLoopMerge until the end
254 // of the regular inlining logic, and only if necessary.
255 bool caller_is_single_block_loop = false;
David Neto25ddfec2017-09-02 19:01:03 -0400256 bool caller_is_loop_header = false;
David Netoefff5fa2017-08-31 15:47:31 -0400257 if (auto* loop_merge = call_block_itr->GetLoopMergeInst()) {
David Neto25ddfec2017-09-02 19:01:03 -0400258 caller_is_loop_header = true;
David Netoefff5fa2017-08-31 15:47:31 -0400259 caller_is_single_block_loop =
260 call_block_itr->id() ==
261 loop_merge->GetSingleWordInOperand(kSpvLoopMergeContinueTargetIdInIdx);
262 }
263
264 bool callee_begins_with_structured_header =
265 (*(calleeFn->begin())).GetMergeInst() != nullptr;
266
Greg Fischer04fcc662016-11-10 10:11:50 -0700267 // Clone and map callee code. Copy caller block code to beginning of
268 // first block and end of last block.
269 bool prevInstWasReturn = false;
Greg Fischerbba812f2017-05-04 20:55:53 -0600270 uint32_t singleTripLoopHeaderId = 0;
271 uint32_t singleTripLoopContinueId = 0;
Greg Fischer04fcc662016-11-10 10:11:50 -0700272 uint32_t returnLabelId = 0;
273 bool multiBlocks = false;
274 const uint32_t calleeTypeId = calleeFn->type_id();
David Neto2a1014b2017-08-09 14:59:04 -0400275 // new_blk_ptr is a new basic block in the caller. New instructions are
276 // written to it. It is created when we encounter the OpLabel
David Netoefff5fa2017-08-31 15:47:31 -0400277 // of the first callee block. It is appended to new_blocks only when
278 // it is complete.
Greg Fischer04fcc662016-11-10 10:11:50 -0700279 std::unique_ptr<ir::BasicBlock> new_blk_ptr;
280 calleeFn->ForEachInst([&new_blocks, &callee2caller, &call_block_itr,
281 &call_inst_itr, &new_blk_ptr, &prevInstWasReturn,
David Neto25ddfec2017-09-02 19:01:03 -0400282 &returnLabelId, &returnVarId, caller_is_loop_header,
David Netoefff5fa2017-08-31 15:47:31 -0400283 callee_begins_with_structured_header, &calleeTypeId,
David Neto2a1014b2017-08-09 14:59:04 -0400284 &multiBlocks, &postCallSB, &preCallSB, multiReturn,
Greg Fischerbba812f2017-05-04 20:55:53 -0600285 &singleTripLoopHeaderId, &singleTripLoopContinueId,
David Netoefff5fa2017-08-31 15:47:31 -0400286 &callee_result_ids, this](const ir::Instruction* cpi) {
Greg Fischer04fcc662016-11-10 10:11:50 -0700287 switch (cpi->opcode()) {
288 case SpvOpFunction:
289 case SpvOpFunctionParameter:
290 case SpvOpVariable:
291 // Already processed
292 break;
293 case SpvOpLabel: {
294 // If previous instruction was early return, insert branch
295 // instruction to return block.
296 if (prevInstWasReturn) {
297 if (returnLabelId == 0) returnLabelId = this->TakeNextId();
298 AddBranch(returnLabelId, &new_blk_ptr);
299 prevInstWasReturn = false;
300 }
301 // Finish current block (if it exists) and get label for next block.
302 uint32_t labelId;
303 bool firstBlock = false;
304 if (new_blk_ptr != nullptr) {
305 new_blocks->push_back(std::move(new_blk_ptr));
306 // If result id is already mapped, use it, otherwise get a new
307 // one.
308 const uint32_t rid = cpi->result_id();
309 const auto mapItr = callee2caller.find(rid);
310 labelId = (mapItr != callee2caller.end()) ? mapItr->second
311 : this->TakeNextId();
312 } else {
313 // First block needs to use label of original block
314 // but map callee label in case of phi reference.
Greg Fischerbba812f2017-05-04 20:55:53 -0600315 labelId = call_block_itr->id();
Greg Fischer04fcc662016-11-10 10:11:50 -0700316 callee2caller[cpi->result_id()] = labelId;
317 firstBlock = true;
318 }
319 // Create first/next block.
320 new_blk_ptr.reset(new ir::BasicBlock(NewLabel(labelId)));
321 if (firstBlock) {
322 // Copy contents of original caller block up to call instruction.
323 for (auto cii = call_block_itr->begin(); cii != call_inst_itr;
Greg Fischerbba812f2017-05-04 20:55:53 -0600324 ++cii) {
Steven Perronbb7802b2017-10-13 14:25:21 -0400325 std::unique_ptr<ir::Instruction> cp_inst(cii->Clone());
Greg Fischer04fcc662016-11-10 10:11:50 -0700326 // Remember same-block ops for possible regeneration.
327 if (IsSameBlockOp(&*cp_inst)) {
328 auto* sb_inst_ptr = cp_inst.get();
329 preCallSB[cp_inst->result_id()] = sb_inst_ptr;
330 }
331 new_blk_ptr->AddInstruction(std::move(cp_inst));
332 }
Diego Novillod2938e42017-11-08 12:40:02 -0500333 if (caller_is_loop_header && callee_begins_with_structured_header) {
David Netoefff5fa2017-08-31 15:47:31 -0400334 // We can't place both the caller's merge instruction and another
335 // merge instruction in the same block. So split the calling block.
336 // Insert an unconditional branch to a new guard block. Later,
337 // once we know the ID of the last block, we will move the caller's
338 // OpLoopMerge from the last generated block into the first block.
339 // We also wait to avoid invalidating various iterators.
340 const auto guard_block_id = this->TakeNextId();
341 AddBranch(guard_block_id, &new_blk_ptr);
342 new_blocks->push_back(std::move(new_blk_ptr));
343 // Start the next block.
344 new_blk_ptr.reset(new ir::BasicBlock(NewLabel(guard_block_id)));
345 // Reset the mapping of the callee's entry block to point to
346 // the guard block. Do this so we can fix up phis later on to
347 // satisfy dominance.
348 callee2caller[cpi->result_id()] = guard_block_id;
349 }
350 // If callee has multiple returns, insert a header block for
David Neto2a1014b2017-08-09 14:59:04 -0400351 // single-trip loop that will encompass callee code. Start postheader
Greg Fischerbba812f2017-05-04 20:55:53 -0600352 // block.
David Netoefff5fa2017-08-31 15:47:31 -0400353 //
354 // Note: Consider the following combination:
355 // - the caller is a single block loop
356 // - the callee does not begin with a structure header
357 // - the callee has multiple returns.
358 // We still need to split the caller block and insert a guard block.
359 // But we only need to do it once. We haven't done it yet, but the
360 // single-trip loop header will serve the same purpose.
David Neto2a1014b2017-08-09 14:59:04 -0400361 if (multiReturn) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600362 singleTripLoopHeaderId = this->TakeNextId();
363 AddBranch(singleTripLoopHeaderId, &new_blk_ptr);
364 new_blocks->push_back(std::move(new_blk_ptr));
Diego Novillod2938e42017-11-08 12:40:02 -0500365 new_blk_ptr.reset(
366 new ir::BasicBlock(NewLabel(singleTripLoopHeaderId)));
Greg Fischerbba812f2017-05-04 20:55:53 -0600367 returnLabelId = this->TakeNextId();
368 singleTripLoopContinueId = this->TakeNextId();
369 AddLoopMerge(returnLabelId, singleTripLoopContinueId, &new_blk_ptr);
370 uint32_t postHeaderId = this->TakeNextId();
371 AddBranch(postHeaderId, &new_blk_ptr);
372 new_blocks->push_back(std::move(new_blk_ptr));
373 new_blk_ptr.reset(new ir::BasicBlock(NewLabel(postHeaderId)));
374 multiBlocks = true;
David Neto860c4192017-08-31 17:33:44 -0400375 // Reset the mapping of the callee's entry block to point to
376 // the post-header block. Do this so we can fix up phis later
377 // on to satisfy dominance.
378 callee2caller[cpi->result_id()] = postHeaderId;
Greg Fischerbba812f2017-05-04 20:55:53 -0600379 }
Greg Fischer04fcc662016-11-10 10:11:50 -0700380 } else {
381 multiBlocks = true;
382 }
383 } break;
384 case SpvOpReturnValue: {
385 // Store return value to return variable.
386 assert(returnVarId != 0);
387 uint32_t valId = cpi->GetInOperand(kSpvReturnValueId).words[0];
388 const auto mapItr = callee2caller.find(valId);
389 if (mapItr != callee2caller.end()) {
390 valId = mapItr->second;
391 }
392 AddStore(returnVarId, valId, &new_blk_ptr);
393
394 // Remember we saw a return; if followed by a label, will need to
395 // insert branch.
396 prevInstWasReturn = true;
397 } break;
398 case SpvOpReturn: {
399 // Remember we saw a return; if followed by a label, will need to
400 // insert branch.
401 prevInstWasReturn = true;
402 } break;
403 case SpvOpFunctionEnd: {
David Neto2a1014b2017-08-09 14:59:04 -0400404 // If there was an early return, we generated a return label id
405 // for it. Now we have to generate the return block with that Id.
Greg Fischer04fcc662016-11-10 10:11:50 -0700406 if (returnLabelId != 0) {
David Neto2a1014b2017-08-09 14:59:04 -0400407 // If previous instruction was return, insert branch instruction
408 // to return block.
Greg Fischer04fcc662016-11-10 10:11:50 -0700409 if (prevInstWasReturn) AddBranch(returnLabelId, &new_blk_ptr);
David Neto2a1014b2017-08-09 14:59:04 -0400410 if (multiReturn) {
411 // If we generated a loop header to for the single-trip loop
412 // to accommodate multiple returns, insert the continue
413 // target block now, with a false branch back to the loop header.
414 new_blocks->push_back(std::move(new_blk_ptr));
415 new_blk_ptr.reset(
416 new ir::BasicBlock(NewLabel(singleTripLoopContinueId)));
417 AddBranchCond(GetFalseId(), singleTripLoopHeaderId, returnLabelId,
418 &new_blk_ptr);
419 }
420 // Generate the return block.
Greg Fischerbba812f2017-05-04 20:55:53 -0600421 new_blocks->push_back(std::move(new_blk_ptr));
Greg Fischer04fcc662016-11-10 10:11:50 -0700422 new_blk_ptr.reset(new ir::BasicBlock(NewLabel(returnLabelId)));
423 multiBlocks = true;
424 }
425 // Load return value into result id of call, if it exists.
426 if (returnVarId != 0) {
427 const uint32_t resId = call_inst_itr->result_id();
428 assert(resId != 0);
429 AddLoad(calleeTypeId, resId, returnVarId, &new_blk_ptr);
430 }
431 // Copy remaining instructions from caller block.
432 auto cii = call_inst_itr;
Greg Fischerbba812f2017-05-04 20:55:53 -0600433 for (++cii; cii != call_block_itr->end(); ++cii) {
Steven Perronbb7802b2017-10-13 14:25:21 -0400434 std::unique_ptr<ir::Instruction> cp_inst(cii->Clone());
Greg Fischer04fcc662016-11-10 10:11:50 -0700435 // If multiple blocks generated, regenerate any same-block
436 // instruction that has not been seen in this last block.
437 if (multiBlocks) {
438 CloneSameBlockOps(&cp_inst, &postCallSB, &preCallSB, &new_blk_ptr);
439 // Remember same-block ops in this block.
440 if (IsSameBlockOp(&*cp_inst)) {
441 const uint32_t rid = cp_inst->result_id();
442 postCallSB[rid] = rid;
443 }
444 }
445 new_blk_ptr->AddInstruction(std::move(cp_inst));
446 }
447 // Finalize inline code.
448 new_blocks->push_back(std::move(new_blk_ptr));
449 } break;
450 default: {
451 // Copy callee instruction and remap all input Ids.
Steven Perronbb7802b2017-10-13 14:25:21 -0400452 std::unique_ptr<ir::Instruction> cp_inst(cpi->Clone());
David Netoefff5fa2017-08-31 15:47:31 -0400453 cp_inst->ForEachInId([&callee2caller, &callee_result_ids,
454 this](uint32_t* iid) {
Greg Fischer04fcc662016-11-10 10:11:50 -0700455 const auto mapItr = callee2caller.find(*iid);
456 if (mapItr != callee2caller.end()) {
457 *iid = mapItr->second;
GregFa699d1a2017-08-29 18:35:05 -0600458 } else if (callee_result_ids.find(*iid) != callee_result_ids.end()) {
459 // Forward reference. Allocate a new id, map it,
460 // use it and check for it when remapping result ids
461 const uint32_t nid = this->TakeNextId();
462 callee2caller[*iid] = nid;
463 *iid = nid;
Greg Fischer04fcc662016-11-10 10:11:50 -0700464 }
465 });
GregFa699d1a2017-08-29 18:35:05 -0600466 // If result id is non-zero, remap it. If already mapped, use mapped
467 // value, else use next id.
Greg Fischer04fcc662016-11-10 10:11:50 -0700468 const uint32_t rid = cp_inst->result_id();
469 if (rid != 0) {
GregFa699d1a2017-08-29 18:35:05 -0600470 const auto mapItr = callee2caller.find(rid);
471 uint32_t nid;
472 if (mapItr != callee2caller.end()) {
473 nid = mapItr->second;
Diego Novillod2938e42017-11-08 12:40:02 -0500474 } else {
GregFa699d1a2017-08-29 18:35:05 -0600475 nid = this->TakeNextId();
476 callee2caller[rid] = nid;
477 }
Greg Fischer04fcc662016-11-10 10:11:50 -0700478 cp_inst->SetResultId(nid);
479 }
480 new_blk_ptr->AddInstruction(std::move(cp_inst));
481 } break;
482 }
483 });
David Netoefff5fa2017-08-31 15:47:31 -0400484
David Neto25ddfec2017-09-02 19:01:03 -0400485 if (caller_is_loop_header && (new_blocks->size() > 1)) {
David Netoefff5fa2017-08-31 15:47:31 -0400486 // Move the OpLoopMerge from the last block back to the first, where
David Neto25ddfec2017-09-02 19:01:03 -0400487 // it belongs.
David Netoefff5fa2017-08-31 15:47:31 -0400488 auto& first = new_blocks->front();
489 auto& last = new_blocks->back();
490 assert(first != last);
491
492 // Insert a modified copy of the loop merge into the first block.
493 auto loop_merge_itr = last->tail();
494 --loop_merge_itr;
495 assert(loop_merge_itr->opcode() == SpvOpLoopMerge);
Steven Perronbb7802b2017-10-13 14:25:21 -0400496 std::unique_ptr<ir::Instruction> cp_inst(loop_merge_itr->Clone());
David Neto25ddfec2017-09-02 19:01:03 -0400497 if (caller_is_single_block_loop) {
498 // Also, update its continue target to point to the last block.
499 cp_inst->SetInOperand(kSpvLoopMergeContinueTargetIdInIdx, {last->id()});
500 }
David Netoefff5fa2017-08-31 15:47:31 -0400501 first->tail().InsertBefore(std::move(cp_inst));
502
503 // Remove the loop merge from the last block.
Steven Perronbb7802b2017-10-13 14:25:21 -0400504 loop_merge_itr->RemoveFromList();
505 delete &*loop_merge_itr;
David Netoefff5fa2017-08-31 15:47:31 -0400506 }
507
Greg Fischer04fcc662016-11-10 10:11:50 -0700508 // Update block map given replacement blocks.
509 for (auto& blk : *new_blocks) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600510 id2block_[blk->id()] = &*blk;
Greg Fischer04fcc662016-11-10 10:11:50 -0700511 }
512}
513
David Netoceb1d4f2017-03-31 10:36:58 -0400514bool InlinePass::IsInlinableFunctionCall(const ir::Instruction* inst) {
515 if (inst->opcode() != SpvOp::SpvOpFunctionCall) return false;
GregFa107d342017-04-25 13:57:20 -0600516 const uint32_t calleeFnId =
517 inst->GetSingleWordOperand(kSpvFunctionCallFunctionId);
518 const auto ci = inlinable_.find(calleeFnId);
519 return ci != inlinable_.cend();
David Netoceb1d4f2017-03-31 10:36:58 -0400520}
521
GregFe28bd392017-08-01 17:20:13 -0600522void InlinePass::UpdateSucceedingPhis(
523 std::vector<std::unique_ptr<ir::BasicBlock>>& new_blocks) {
524 const auto firstBlk = new_blocks.begin();
525 const auto lastBlk = new_blocks.end() - 1;
526 const uint32_t firstId = (*firstBlk)->id();
527 const uint32_t lastId = (*lastBlk)->id();
Diego Novillod2938e42017-11-08 12:40:02 -0500528 (*lastBlk)->ForEachSuccessorLabel([&firstId, &lastId, this](uint32_t succ) {
529 ir::BasicBlock* sbp = this->id2block_[succ];
530 sbp->ForEachPhiInst([&firstId, &lastId](ir::Instruction* phi) {
531 phi->ForEachInId([&firstId, &lastId](uint32_t* id) {
532 if (*id == firstId) *id = lastId;
GregFe28bd392017-08-01 17:20:13 -0600533 });
Diego Novillod2938e42017-11-08 12:40:02 -0500534 });
535 });
Greg Fischer04fcc662016-11-10 10:11:50 -0700536}
537
Greg Fischerbba812f2017-05-04 20:55:53 -0600538bool InlinePass::HasMultipleReturns(ir::Function* func) {
539 bool seenReturn = false;
540 bool multipleReturns = false;
541 for (auto& blk : *func) {
542 auto terminal_ii = blk.cend();
543 --terminal_ii;
Diego Novillod2938e42017-11-08 12:40:02 -0500544 if (terminal_ii->opcode() == SpvOpReturn ||
Greg Fischerbba812f2017-05-04 20:55:53 -0600545 terminal_ii->opcode() == SpvOpReturnValue) {
546 if (seenReturn) {
547 multipleReturns = true;
548 break;
549 }
550 seenReturn = true;
551 }
552 }
553 return multipleReturns;
554}
555
Greg Fischerbba812f2017-05-04 20:55:53 -0600556void InlinePass::ComputeStructuredSuccessors(ir::Function* func) {
557 // If header, make merge block first successor.
558 for (auto& blk : *func) {
Diego Novillofef669f2017-10-30 17:42:26 -0400559 uint32_t mbid = blk.MergeBlockIdIfAny();
560 if (mbid != 0) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600561 block2structured_succs_[&blk].push_back(id2block_[mbid]);
Diego Novillofef669f2017-10-30 17:42:26 -0400562 }
563
564 // Add true successors.
Greg Fischerbba812f2017-05-04 20:55:53 -0600565 blk.ForEachSuccessorLabel([&blk, this](uint32_t sbid) {
566 block2structured_succs_[&blk].push_back(id2block_[sbid]);
567 });
568 }
569}
Diego Novillofef669f2017-10-30 17:42:26 -0400570
Greg Fischerbba812f2017-05-04 20:55:53 -0600571InlinePass::GetBlocksFunction InlinePass::StructuredSuccessorsFunction() {
572 return [this](const ir::BasicBlock* block) {
573 return &(block2structured_succs_[block]);
574 };
575}
576
577bool InlinePass::HasNoReturnInLoop(ir::Function* func) {
578 // If control not structured, do not do loop/return analysis
579 // TODO: Analyze returns in non-structured control flow
Diego Novillod2938e42017-11-08 12:40:02 -0500580 if (!get_module()->HasCapability(SpvCapabilityShader)) return false;
Greg Fischerbba812f2017-05-04 20:55:53 -0600581 // Compute structured block order. This order has the property
582 // that dominators are before all blocks they dominate and merge blocks
583 // are after all blocks that are in the control constructs of their header.
584 ComputeStructuredSuccessors(func);
585 auto ignore_block = [](cbb_ptr) {};
586 auto ignore_edge = [](cbb_ptr, cbb_ptr) {};
587 std::list<const ir::BasicBlock*> structuredOrder;
588 spvtools::CFA<ir::BasicBlock>::DepthFirstTraversal(
Diego Novillod2938e42017-11-08 12:40:02 -0500589 &*func->begin(), StructuredSuccessorsFunction(), ignore_block,
590 [&](cbb_ptr b) { structuredOrder.push_front(b); }, ignore_edge);
Greg Fischerbba812f2017-05-04 20:55:53 -0600591 // Search for returns in loops. Only need to track outermost loop
592 bool return_in_loop = false;
593 uint32_t outerLoopMergeId = 0;
594 for (auto& blk : structuredOrder) {
595 // Exiting current outer loop
Diego Novillod2938e42017-11-08 12:40:02 -0500596 if (blk->id() == outerLoopMergeId) outerLoopMergeId = 0;
Greg Fischerbba812f2017-05-04 20:55:53 -0600597 // Return block
598 auto terminal_ii = blk->cend();
599 --terminal_ii;
Diego Novillod2938e42017-11-08 12:40:02 -0500600 if (terminal_ii->opcode() == SpvOpReturn ||
Greg Fischerbba812f2017-05-04 20:55:53 -0600601 terminal_ii->opcode() == SpvOpReturnValue) {
602 if (outerLoopMergeId != 0) {
603 return_in_loop = true;
604 break;
605 }
Diego Novillod2938e42017-11-08 12:40:02 -0500606 } else if (terminal_ii != blk->cbegin()) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600607 auto merge_ii = terminal_ii;
608 --merge_ii;
609 // Entering outermost loop
610 if (merge_ii->opcode() == SpvOpLoopMerge && outerLoopMergeId == 0)
Diego Novillod2938e42017-11-08 12:40:02 -0500611 outerLoopMergeId =
612 merge_ii->GetSingleWordOperand(kSpvLoopMergeMergeBlockId);
Greg Fischerbba812f2017-05-04 20:55:53 -0600613 }
614 }
615 return !return_in_loop;
616}
617
618void InlinePass::AnalyzeReturns(ir::Function* func) {
619 // Look for multiple returns
620 if (!HasMultipleReturns(func)) {
621 no_return_in_loop_.insert(func->result_id());
622 return;
623 }
David Neto2a1014b2017-08-09 14:59:04 -0400624 multi_return_funcs_.insert(func->result_id());
Greg Fischerbba812f2017-05-04 20:55:53 -0600625 // If multiple returns, see if any are in a loop
Diego Novillod2938e42017-11-08 12:40:02 -0500626 if (HasNoReturnInLoop(func)) no_return_in_loop_.insert(func->result_id());
Greg Fischerbba812f2017-05-04 20:55:53 -0600627}
628
629bool InlinePass::IsInlinableFunction(ir::Function* func) {
GregFa107d342017-04-25 13:57:20 -0600630 // We can only inline a function if it has blocks.
Diego Novillod2938e42017-11-08 12:40:02 -0500631 if (func->cbegin() == func->cend()) return false;
Greg Fischerbba812f2017-05-04 20:55:53 -0600632 // Do not inline functions with returns in loops. Currently early return
633 // functions are inlined by wrapping them in a one trip loop and implementing
634 // the returns as a branch to the loop's merge block. However, this can only
635 // done validly if the return was not in a loop in the original function.
636 // Also remember functions with multiple (early) returns.
637 AnalyzeReturns(func);
David Netoefff5fa2017-08-31 15:47:31 -0400638 return no_return_in_loop_.find(func->result_id()) !=
639 no_return_in_loop_.cend();
GregFa107d342017-04-25 13:57:20 -0600640}
641
Steven Perron476cae62017-10-30 11:13:24 -0400642void InlinePass::InitializeInline(ir::IRContext* c) {
643 InitializeProcessing(c);
Greg Fischer04fcc662016-11-10 10:11:50 -0700644
Greg Fischerbba812f2017-05-04 20:55:53 -0600645 false_id_ = 0;
646
GregFe28bd392017-08-01 17:20:13 -0600647 // clear collections
Greg Fischer04fcc662016-11-10 10:11:50 -0700648 id2function_.clear();
649 id2block_.clear();
Greg Fischerbba812f2017-05-04 20:55:53 -0600650 block2structured_succs_.clear();
GregFa107d342017-04-25 13:57:20 -0600651 inlinable_.clear();
GregFe28bd392017-08-01 17:20:13 -0600652 no_return_in_loop_.clear();
David Neto2a1014b2017-08-09 14:59:04 -0400653 multi_return_funcs_.clear();
GregFe28bd392017-08-01 17:20:13 -0600654
Diego Novillo1040a952017-10-25 13:26:25 -0400655 for (auto& fn : *get_module()) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600656 // Initialize function and block maps.
Greg Fischer04fcc662016-11-10 10:11:50 -0700657 id2function_[fn.result_id()] = &fn;
658 for (auto& blk : fn) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600659 id2block_[blk.id()] = &blk;
Greg Fischer04fcc662016-11-10 10:11:50 -0700660 }
Greg Fischerbba812f2017-05-04 20:55:53 -0600661 // Compute inlinability
Diego Novillod2938e42017-11-08 12:40:02 -0500662 if (IsInlinableFunction(&fn)) inlinable_.insert(fn.result_id());
Greg Fischer04fcc662016-11-10 10:11:50 -0700663 }
664};
665
Diego Novillo1040a952017-10-25 13:26:25 -0400666InlinePass::InlinePass() {}
Greg Fischer04fcc662016-11-10 10:11:50 -0700667
Greg Fischer04fcc662016-11-10 10:11:50 -0700668} // namespace opt
669} // namespace spvtools