blob: 8bd67f12ece3b183aca00898c532ba23f5f17ca6 [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) {
Alan Baker61690852017-12-08 15:33:19 -050036 analysis::Type* pointeeTy;
37 std::unique_ptr<analysis::Pointer> pointerTy;
38 std::tie(pointeeTy, pointerTy) =
39 context()->get_type_mgr()->GetTypeAndPointerType(type_id,
40 SpvStorageClassFunction);
41 if (type_id == context()->get_type_mgr()->GetId(pointeeTy)) {
42 // Non-ambiguous type. Get the pointer type through the type manager.
43 return context()->get_type_mgr()->GetTypeInstruction(pointerTy.get());
44 }
45
46 // Ambiguous type, do a linear search.
Diego Novillo1040a952017-10-25 13:26:25 -040047 ir::Module::inst_iterator type_itr = get_module()->types_values_begin();
48 for (; type_itr != get_module()->types_values_end(); ++type_itr) {
Greg Fischer04fcc662016-11-10 10:11:50 -070049 const ir::Instruction* type_inst = &*type_itr;
50 if (type_inst->opcode() == SpvOpTypePointer &&
51 type_inst->GetSingleWordOperand(kSpvTypePointerTypeId) == type_id &&
52 type_inst->GetSingleWordOperand(kSpvTypePointerStorageClass) ==
53 storage_class)
54 return type_inst->result_id();
55 }
56 return 0;
57}
58
59uint32_t InlinePass::AddPointerToType(uint32_t type_id,
60 SpvStorageClass storage_class) {
61 uint32_t resultId = TakeNextId();
62 std::unique_ptr<ir::Instruction> type_inst(new ir::Instruction(
Alan Bakera7717132017-11-14 14:11:50 -050063 context(), SpvOpTypePointer, 0, resultId,
Greg Fischer04fcc662016-11-10 10:11:50 -070064 {{spv_operand_type_t::SPV_OPERAND_TYPE_STORAGE_CLASS,
65 {uint32_t(storage_class)}},
66 {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {type_id}}}));
Steven Perron476cae62017-10-30 11:13:24 -040067 context()->AddType(std::move(type_inst));
Alan Baker61690852017-12-08 15:33:19 -050068 analysis::Type* pointeeTy;
69 std::unique_ptr<analysis::Pointer> pointerTy;
70 std::tie(pointeeTy, pointerTy) =
71 context()->get_type_mgr()->GetTypeAndPointerType(type_id,
72 SpvStorageClassFunction);
73 context()->get_type_mgr()->RegisterType(resultId, *pointerTy);
Greg Fischer04fcc662016-11-10 10:11:50 -070074 return resultId;
75}
76
77void InlinePass::AddBranch(uint32_t label_id,
Diego Novillod2938e42017-11-08 12:40:02 -050078 std::unique_ptr<ir::BasicBlock>* block_ptr) {
Greg Fischer04fcc662016-11-10 10:11:50 -070079 std::unique_ptr<ir::Instruction> newBranch(new ir::Instruction(
Alan Bakera7717132017-11-14 14:11:50 -050080 context(), SpvOpBranch, 0, 0,
Diego Novillod2938e42017-11-08 12:40:02 -050081 {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {label_id}}}));
Greg Fischer04fcc662016-11-10 10:11:50 -070082 (*block_ptr)->AddInstruction(std::move(newBranch));
83}
84
Greg Fischerbba812f2017-05-04 20:55:53 -060085void InlinePass::AddBranchCond(uint32_t cond_id, uint32_t true_id,
Diego Novillod2938e42017-11-08 12:40:02 -050086 uint32_t false_id,
87 std::unique_ptr<ir::BasicBlock>* block_ptr) {
Greg Fischerbba812f2017-05-04 20:55:53 -060088 std::unique_ptr<ir::Instruction> newBranch(new ir::Instruction(
Alan Bakera7717132017-11-14 14:11:50 -050089 context(), SpvOpBranchConditional, 0, 0,
Diego Novillod2938e42017-11-08 12:40:02 -050090 {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {cond_id}},
91 {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {true_id}},
92 {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {false_id}}}));
Greg Fischerbba812f2017-05-04 20:55:53 -060093 (*block_ptr)->AddInstruction(std::move(newBranch));
94}
95
96void InlinePass::AddLoopMerge(uint32_t merge_id, uint32_t continue_id,
Diego Novillod2938e42017-11-08 12:40:02 -050097 std::unique_ptr<ir::BasicBlock>* block_ptr) {
Greg Fischerbba812f2017-05-04 20:55:53 -060098 std::unique_ptr<ir::Instruction> newLoopMerge(new ir::Instruction(
Alan Bakera7717132017-11-14 14:11:50 -050099 context(), SpvOpLoopMerge, 0, 0,
Greg Fischerbba812f2017-05-04 20:55:53 -0600100 {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {merge_id}},
101 {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {continue_id}},
102 {spv_operand_type_t::SPV_OPERAND_TYPE_LOOP_CONTROL, {0}}}));
103 (*block_ptr)->AddInstruction(std::move(newLoopMerge));
104}
105
Greg Fischer04fcc662016-11-10 10:11:50 -0700106void InlinePass::AddStore(uint32_t ptr_id, uint32_t val_id,
107 std::unique_ptr<ir::BasicBlock>* block_ptr) {
108 std::unique_ptr<ir::Instruction> newStore(new ir::Instruction(
Alan Bakera7717132017-11-14 14:11:50 -0500109 context(), SpvOpStore, 0, 0,
Diego Novillod2938e42017-11-08 12:40:02 -0500110 {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {ptr_id}},
111 {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {val_id}}}));
Greg Fischer04fcc662016-11-10 10:11:50 -0700112 (*block_ptr)->AddInstruction(std::move(newStore));
113}
114
115void InlinePass::AddLoad(uint32_t type_id, uint32_t resultId, uint32_t ptr_id,
116 std::unique_ptr<ir::BasicBlock>* block_ptr) {
117 std::unique_ptr<ir::Instruction> newLoad(new ir::Instruction(
Alan Bakera7717132017-11-14 14:11:50 -0500118 context(), SpvOpLoad, type_id, resultId,
Greg Fischer04fcc662016-11-10 10:11:50 -0700119 {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {ptr_id}}}));
120 (*block_ptr)->AddInstruction(std::move(newLoad));
121}
122
123std::unique_ptr<ir::Instruction> InlinePass::NewLabel(uint32_t label_id) {
124 std::unique_ptr<ir::Instruction> newLabel(
Alan Bakera7717132017-11-14 14:11:50 -0500125 new ir::Instruction(context(), SpvOpLabel, 0, label_id, {}));
Greg Fischer04fcc662016-11-10 10:11:50 -0700126 return newLabel;
127}
128
Greg Fischerbba812f2017-05-04 20:55:53 -0600129uint32_t InlinePass::GetFalseId() {
Diego Novillod2938e42017-11-08 12:40:02 -0500130 if (false_id_ != 0) return false_id_;
Diego Novillo1040a952017-10-25 13:26:25 -0400131 false_id_ = get_module()->GetGlobalValue(SpvOpConstantFalse);
Diego Novillod2938e42017-11-08 12:40:02 -0500132 if (false_id_ != 0) return false_id_;
Diego Novillo1040a952017-10-25 13:26:25 -0400133 uint32_t boolId = get_module()->GetGlobalValue(SpvOpTypeBool);
Greg Fischerbba812f2017-05-04 20:55:53 -0600134 if (boolId == 0) {
135 boolId = TakeNextId();
Diego Novillo1040a952017-10-25 13:26:25 -0400136 get_module()->AddGlobalValue(SpvOpTypeBool, boolId, 0);
Greg Fischerbba812f2017-05-04 20:55:53 -0600137 }
138 false_id_ = TakeNextId();
Diego Novillo1040a952017-10-25 13:26:25 -0400139 get_module()->AddGlobalValue(SpvOpConstantFalse, false_id_, boolId);
Greg Fischerbba812f2017-05-04 20:55:53 -0600140 return false_id_;
141}
142
Greg Fischer04fcc662016-11-10 10:11:50 -0700143void InlinePass::MapParams(
Diego Novillod2938e42017-11-08 12:40:02 -0500144 ir::Function* calleeFn, ir::BasicBlock::iterator call_inst_itr,
Greg Fischer04fcc662016-11-10 10:11:50 -0700145 std::unordered_map<uint32_t, uint32_t>* callee2caller) {
146 int param_idx = 0;
147 calleeFn->ForEachParam(
148 [&call_inst_itr, &param_idx, &callee2caller](const ir::Instruction* cpi) {
149 const uint32_t pid = cpi->result_id();
150 (*callee2caller)[pid] = call_inst_itr->GetSingleWordOperand(
151 kSpvFunctionCallArgumentId + param_idx);
Greg Fischerbba812f2017-05-04 20:55:53 -0600152 ++param_idx;
Greg Fischer04fcc662016-11-10 10:11:50 -0700153 });
154}
155
156void InlinePass::CloneAndMapLocals(
157 ir::Function* calleeFn,
158 std::vector<std::unique_ptr<ir::Instruction>>* new_vars,
159 std::unordered_map<uint32_t, uint32_t>* callee2caller) {
160 auto callee_block_itr = calleeFn->begin();
161 auto callee_var_itr = callee_block_itr->begin();
162 while (callee_var_itr->opcode() == SpvOp::SpvOpVariable) {
Alan Bakera7717132017-11-14 14:11:50 -0500163 std::unique_ptr<ir::Instruction> var_inst(
164 callee_var_itr->Clone(callee_var_itr->context()));
Greg Fischer04fcc662016-11-10 10:11:50 -0700165 uint32_t newId = TakeNextId();
Diego Novillo83228132017-11-27 10:16:41 -0500166 get_decoration_mgr()->CloneDecorations(callee_var_itr->result_id(), newId,
167 update_def_use_mgr_);
Greg Fischer04fcc662016-11-10 10:11:50 -0700168 var_inst->SetResultId(newId);
169 (*callee2caller)[callee_var_itr->result_id()] = newId;
170 new_vars->push_back(std::move(var_inst));
Greg Fischerbba812f2017-05-04 20:55:53 -0600171 ++callee_var_itr;
Greg Fischer04fcc662016-11-10 10:11:50 -0700172 }
173}
174
175uint32_t InlinePass::CreateReturnVar(
176 ir::Function* calleeFn,
177 std::vector<std::unique_ptr<ir::Instruction>>* new_vars) {
178 uint32_t returnVarId = 0;
179 const uint32_t calleeTypeId = calleeFn->type_id();
180 const ir::Instruction* calleeType =
Diego Novillo1040a952017-10-25 13:26:25 -0400181 get_def_use_mgr()->id_to_defs().find(calleeTypeId)->second;
Greg Fischer04fcc662016-11-10 10:11:50 -0700182 if (calleeType->opcode() != SpvOpTypeVoid) {
183 // Find or create ptr to callee return type.
184 uint32_t returnVarTypeId =
185 FindPointerToType(calleeTypeId, SpvStorageClassFunction);
186 if (returnVarTypeId == 0)
187 returnVarTypeId = AddPointerToType(calleeTypeId, SpvStorageClassFunction);
188 // Add return var to new function scope variables.
189 returnVarId = TakeNextId();
190 std::unique_ptr<ir::Instruction> var_inst(new ir::Instruction(
Alan Bakera7717132017-11-14 14:11:50 -0500191 context(), SpvOpVariable, returnVarTypeId, returnVarId,
Greg Fischer04fcc662016-11-10 10:11:50 -0700192 {{spv_operand_type_t::SPV_OPERAND_TYPE_STORAGE_CLASS,
193 {SpvStorageClassFunction}}}));
194 new_vars->push_back(std::move(var_inst));
195 }
Diego Novillo83228132017-11-27 10:16:41 -0500196 get_decoration_mgr()->CloneDecorations(calleeFn->result_id(), returnVarId,
197 update_def_use_mgr_);
Greg Fischer04fcc662016-11-10 10:11:50 -0700198 return returnVarId;
199}
200
201bool InlinePass::IsSameBlockOp(const ir::Instruction* inst) const {
202 return inst->opcode() == SpvOpSampledImage || inst->opcode() == SpvOpImage;
203}
204
205void InlinePass::CloneSameBlockOps(
206 std::unique_ptr<ir::Instruction>* inst,
207 std::unordered_map<uint32_t, uint32_t>* postCallSB,
208 std::unordered_map<uint32_t, ir::Instruction*>* preCallSB,
209 std::unique_ptr<ir::BasicBlock>* block_ptr) {
Diego Novillo83228132017-11-27 10:16:41 -0500210 (*inst)->ForEachInId([&postCallSB, &preCallSB, &block_ptr,
211 this](uint32_t* iid) {
212 const auto mapItr = (*postCallSB).find(*iid);
213 if (mapItr == (*postCallSB).end()) {
214 const auto mapItr2 = (*preCallSB).find(*iid);
215 if (mapItr2 != (*preCallSB).end()) {
216 // Clone pre-call same-block ops, map result id.
217 const ir::Instruction* inInst = mapItr2->second;
218 std::unique_ptr<ir::Instruction> sb_inst(
219 inInst->Clone(inInst->context()));
220 CloneSameBlockOps(&sb_inst, postCallSB, preCallSB, block_ptr);
221 const uint32_t rid = sb_inst->result_id();
222 const uint32_t nid = this->TakeNextId();
223 get_decoration_mgr()->CloneDecorations(rid, nid, update_def_use_mgr_);
224 sb_inst->SetResultId(nid);
225 (*postCallSB)[rid] = nid;
226 *iid = nid;
227 (*block_ptr)->AddInstruction(std::move(sb_inst));
228 }
229 } else {
230 // Reset same-block op operand.
231 *iid = mapItr->second;
232 }
233 });
Greg Fischer04fcc662016-11-10 10:11:50 -0700234}
235
236void InlinePass::GenInlineCode(
237 std::vector<std::unique_ptr<ir::BasicBlock>>* new_blocks,
238 std::vector<std::unique_ptr<ir::Instruction>>* new_vars,
Steven Perronbb7802b2017-10-13 14:25:21 -0400239 ir::BasicBlock::iterator call_inst_itr,
Greg Fischer04fcc662016-11-10 10:11:50 -0700240 ir::UptrVectorIterator<ir::BasicBlock> call_block_itr) {
241 // Map from all ids in the callee to their equivalent id in the caller
242 // as callee instructions are copied into caller.
243 std::unordered_map<uint32_t, uint32_t> callee2caller;
244 // Pre-call same-block insts
245 std::unordered_map<uint32_t, ir::Instruction*> preCallSB;
246 // Post-call same-block op ids
247 std::unordered_map<uint32_t, uint32_t> postCallSB;
248
249 ir::Function* calleeFn = id2function_[call_inst_itr->GetSingleWordOperand(
250 kSpvFunctionCallFunctionId)];
251
David Neto2a1014b2017-08-09 14:59:04 -0400252 // Check for multiple returns in the callee.
253 auto fi = multi_return_funcs_.find(calleeFn->result_id());
254 const bool multiReturn = fi != multi_return_funcs_.end();
Greg Fischerbba812f2017-05-04 20:55:53 -0600255
Greg Fischer04fcc662016-11-10 10:11:50 -0700256 // Map parameters to actual arguments.
257 MapParams(calleeFn, call_inst_itr, &callee2caller);
258
259 // Define caller local variables for all callee variables and create map to
260 // them.
261 CloneAndMapLocals(calleeFn, new_vars, &callee2caller);
262
263 // Create return var if needed.
264 uint32_t returnVarId = CreateReturnVar(calleeFn, new_vars);
265
GregFa699d1a2017-08-29 18:35:05 -0600266 // Create set of callee result ids. Used to detect forward references
267 std::unordered_set<uint32_t> callee_result_ids;
Diego Novillod2938e42017-11-08 12:40:02 -0500268 calleeFn->ForEachInst([&callee_result_ids](const ir::Instruction* cpi) {
GregFa699d1a2017-08-29 18:35:05 -0600269 const uint32_t rid = cpi->result_id();
Diego Novillod2938e42017-11-08 12:40:02 -0500270 if (rid != 0) callee_result_ids.insert(rid);
GregFa699d1a2017-08-29 18:35:05 -0600271 });
272
David Netoefff5fa2017-08-31 15:47:31 -0400273 // If the caller is in a single-block loop, and the callee has multiple
274 // blocks, then the normal inlining logic will place the OpLoopMerge in
275 // the last of several blocks in the loop. Instead, it should be placed
276 // at the end of the first block. First determine if the caller is in a
277 // single block loop. We'll wait to move the OpLoopMerge until the end
278 // of the regular inlining logic, and only if necessary.
279 bool caller_is_single_block_loop = false;
David Neto25ddfec2017-09-02 19:01:03 -0400280 bool caller_is_loop_header = false;
David Netoefff5fa2017-08-31 15:47:31 -0400281 if (auto* loop_merge = call_block_itr->GetLoopMergeInst()) {
David Neto25ddfec2017-09-02 19:01:03 -0400282 caller_is_loop_header = true;
David Netoefff5fa2017-08-31 15:47:31 -0400283 caller_is_single_block_loop =
284 call_block_itr->id() ==
285 loop_merge->GetSingleWordInOperand(kSpvLoopMergeContinueTargetIdInIdx);
286 }
287
288 bool callee_begins_with_structured_header =
289 (*(calleeFn->begin())).GetMergeInst() != nullptr;
290
Greg Fischer04fcc662016-11-10 10:11:50 -0700291 // Clone and map callee code. Copy caller block code to beginning of
292 // first block and end of last block.
293 bool prevInstWasReturn = false;
Greg Fischerbba812f2017-05-04 20:55:53 -0600294 uint32_t singleTripLoopHeaderId = 0;
295 uint32_t singleTripLoopContinueId = 0;
Greg Fischer04fcc662016-11-10 10:11:50 -0700296 uint32_t returnLabelId = 0;
297 bool multiBlocks = false;
298 const uint32_t calleeTypeId = calleeFn->type_id();
David Neto2a1014b2017-08-09 14:59:04 -0400299 // new_blk_ptr is a new basic block in the caller. New instructions are
300 // written to it. It is created when we encounter the OpLabel
David Netoefff5fa2017-08-31 15:47:31 -0400301 // of the first callee block. It is appended to new_blocks only when
302 // it is complete.
Greg Fischer04fcc662016-11-10 10:11:50 -0700303 std::unique_ptr<ir::BasicBlock> new_blk_ptr;
304 calleeFn->ForEachInst([&new_blocks, &callee2caller, &call_block_itr,
305 &call_inst_itr, &new_blk_ptr, &prevInstWasReturn,
David Neto25ddfec2017-09-02 19:01:03 -0400306 &returnLabelId, &returnVarId, caller_is_loop_header,
David Netoefff5fa2017-08-31 15:47:31 -0400307 callee_begins_with_structured_header, &calleeTypeId,
David Neto2a1014b2017-08-09 14:59:04 -0400308 &multiBlocks, &postCallSB, &preCallSB, multiReturn,
Greg Fischerbba812f2017-05-04 20:55:53 -0600309 &singleTripLoopHeaderId, &singleTripLoopContinueId,
David Netoefff5fa2017-08-31 15:47:31 -0400310 &callee_result_ids, this](const ir::Instruction* cpi) {
Greg Fischer04fcc662016-11-10 10:11:50 -0700311 switch (cpi->opcode()) {
312 case SpvOpFunction:
313 case SpvOpFunctionParameter:
314 case SpvOpVariable:
315 // Already processed
316 break;
317 case SpvOpLabel: {
318 // If previous instruction was early return, insert branch
319 // instruction to return block.
320 if (prevInstWasReturn) {
321 if (returnLabelId == 0) returnLabelId = this->TakeNextId();
322 AddBranch(returnLabelId, &new_blk_ptr);
323 prevInstWasReturn = false;
324 }
325 // Finish current block (if it exists) and get label for next block.
326 uint32_t labelId;
327 bool firstBlock = false;
328 if (new_blk_ptr != nullptr) {
329 new_blocks->push_back(std::move(new_blk_ptr));
330 // If result id is already mapped, use it, otherwise get a new
331 // one.
332 const uint32_t rid = cpi->result_id();
333 const auto mapItr = callee2caller.find(rid);
334 labelId = (mapItr != callee2caller.end()) ? mapItr->second
335 : this->TakeNextId();
336 } else {
337 // First block needs to use label of original block
338 // but map callee label in case of phi reference.
Greg Fischerbba812f2017-05-04 20:55:53 -0600339 labelId = call_block_itr->id();
Greg Fischer04fcc662016-11-10 10:11:50 -0700340 callee2caller[cpi->result_id()] = labelId;
341 firstBlock = true;
342 }
343 // Create first/next block.
344 new_blk_ptr.reset(new ir::BasicBlock(NewLabel(labelId)));
345 if (firstBlock) {
346 // Copy contents of original caller block up to call instruction.
347 for (auto cii = call_block_itr->begin(); cii != call_inst_itr;
Greg Fischerbba812f2017-05-04 20:55:53 -0600348 ++cii) {
Alan Bakera7717132017-11-14 14:11:50 -0500349 std::unique_ptr<ir::Instruction> cp_inst(cii->Clone(context()));
Greg Fischer04fcc662016-11-10 10:11:50 -0700350 // Remember same-block ops for possible regeneration.
351 if (IsSameBlockOp(&*cp_inst)) {
352 auto* sb_inst_ptr = cp_inst.get();
353 preCallSB[cp_inst->result_id()] = sb_inst_ptr;
354 }
355 new_blk_ptr->AddInstruction(std::move(cp_inst));
356 }
Diego Novillod2938e42017-11-08 12:40:02 -0500357 if (caller_is_loop_header && callee_begins_with_structured_header) {
David Netoefff5fa2017-08-31 15:47:31 -0400358 // We can't place both the caller's merge instruction and another
359 // merge instruction in the same block. So split the calling block.
360 // Insert an unconditional branch to a new guard block. Later,
361 // once we know the ID of the last block, we will move the caller's
362 // OpLoopMerge from the last generated block into the first block.
363 // We also wait to avoid invalidating various iterators.
364 const auto guard_block_id = this->TakeNextId();
365 AddBranch(guard_block_id, &new_blk_ptr);
366 new_blocks->push_back(std::move(new_blk_ptr));
367 // Start the next block.
368 new_blk_ptr.reset(new ir::BasicBlock(NewLabel(guard_block_id)));
369 // Reset the mapping of the callee's entry block to point to
370 // the guard block. Do this so we can fix up phis later on to
371 // satisfy dominance.
372 callee2caller[cpi->result_id()] = guard_block_id;
373 }
374 // If callee has multiple returns, insert a header block for
David Neto2a1014b2017-08-09 14:59:04 -0400375 // single-trip loop that will encompass callee code. Start postheader
Greg Fischerbba812f2017-05-04 20:55:53 -0600376 // block.
David Netoefff5fa2017-08-31 15:47:31 -0400377 //
378 // Note: Consider the following combination:
379 // - the caller is a single block loop
380 // - the callee does not begin with a structure header
381 // - the callee has multiple returns.
382 // We still need to split the caller block and insert a guard block.
383 // But we only need to do it once. We haven't done it yet, but the
384 // single-trip loop header will serve the same purpose.
David Neto2a1014b2017-08-09 14:59:04 -0400385 if (multiReturn) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600386 singleTripLoopHeaderId = this->TakeNextId();
387 AddBranch(singleTripLoopHeaderId, &new_blk_ptr);
388 new_blocks->push_back(std::move(new_blk_ptr));
Diego Novillod2938e42017-11-08 12:40:02 -0500389 new_blk_ptr.reset(
390 new ir::BasicBlock(NewLabel(singleTripLoopHeaderId)));
Greg Fischerbba812f2017-05-04 20:55:53 -0600391 returnLabelId = this->TakeNextId();
392 singleTripLoopContinueId = this->TakeNextId();
393 AddLoopMerge(returnLabelId, singleTripLoopContinueId, &new_blk_ptr);
394 uint32_t postHeaderId = this->TakeNextId();
395 AddBranch(postHeaderId, &new_blk_ptr);
396 new_blocks->push_back(std::move(new_blk_ptr));
397 new_blk_ptr.reset(new ir::BasicBlock(NewLabel(postHeaderId)));
398 multiBlocks = true;
David Neto860c4192017-08-31 17:33:44 -0400399 // Reset the mapping of the callee's entry block to point to
400 // the post-header block. Do this so we can fix up phis later
401 // on to satisfy dominance.
402 callee2caller[cpi->result_id()] = postHeaderId;
Greg Fischerbba812f2017-05-04 20:55:53 -0600403 }
Greg Fischer04fcc662016-11-10 10:11:50 -0700404 } else {
405 multiBlocks = true;
406 }
407 } break;
408 case SpvOpReturnValue: {
409 // Store return value to return variable.
410 assert(returnVarId != 0);
411 uint32_t valId = cpi->GetInOperand(kSpvReturnValueId).words[0];
412 const auto mapItr = callee2caller.find(valId);
413 if (mapItr != callee2caller.end()) {
414 valId = mapItr->second;
415 }
416 AddStore(returnVarId, valId, &new_blk_ptr);
417
418 // Remember we saw a return; if followed by a label, will need to
419 // insert branch.
420 prevInstWasReturn = true;
421 } break;
422 case SpvOpReturn: {
423 // Remember we saw a return; if followed by a label, will need to
424 // insert branch.
425 prevInstWasReturn = true;
426 } break;
427 case SpvOpFunctionEnd: {
David Neto2a1014b2017-08-09 14:59:04 -0400428 // If there was an early return, we generated a return label id
429 // for it. Now we have to generate the return block with that Id.
Greg Fischer04fcc662016-11-10 10:11:50 -0700430 if (returnLabelId != 0) {
David Neto2a1014b2017-08-09 14:59:04 -0400431 // If previous instruction was return, insert branch instruction
432 // to return block.
Greg Fischer04fcc662016-11-10 10:11:50 -0700433 if (prevInstWasReturn) AddBranch(returnLabelId, &new_blk_ptr);
David Neto2a1014b2017-08-09 14:59:04 -0400434 if (multiReturn) {
435 // If we generated a loop header to for the single-trip loop
436 // to accommodate multiple returns, insert the continue
437 // target block now, with a false branch back to the loop header.
438 new_blocks->push_back(std::move(new_blk_ptr));
439 new_blk_ptr.reset(
440 new ir::BasicBlock(NewLabel(singleTripLoopContinueId)));
441 AddBranchCond(GetFalseId(), singleTripLoopHeaderId, returnLabelId,
442 &new_blk_ptr);
443 }
444 // Generate the return block.
Greg Fischerbba812f2017-05-04 20:55:53 -0600445 new_blocks->push_back(std::move(new_blk_ptr));
Greg Fischer04fcc662016-11-10 10:11:50 -0700446 new_blk_ptr.reset(new ir::BasicBlock(NewLabel(returnLabelId)));
447 multiBlocks = true;
448 }
449 // Load return value into result id of call, if it exists.
450 if (returnVarId != 0) {
451 const uint32_t resId = call_inst_itr->result_id();
452 assert(resId != 0);
453 AddLoad(calleeTypeId, resId, returnVarId, &new_blk_ptr);
454 }
455 // Copy remaining instructions from caller block.
456 auto cii = call_inst_itr;
Greg Fischerbba812f2017-05-04 20:55:53 -0600457 for (++cii; cii != call_block_itr->end(); ++cii) {
Alan Bakera7717132017-11-14 14:11:50 -0500458 std::unique_ptr<ir::Instruction> cp_inst(cii->Clone(context()));
Greg Fischer04fcc662016-11-10 10:11:50 -0700459 // If multiple blocks generated, regenerate any same-block
460 // instruction that has not been seen in this last block.
461 if (multiBlocks) {
462 CloneSameBlockOps(&cp_inst, &postCallSB, &preCallSB, &new_blk_ptr);
463 // Remember same-block ops in this block.
464 if (IsSameBlockOp(&*cp_inst)) {
465 const uint32_t rid = cp_inst->result_id();
466 postCallSB[rid] = rid;
467 }
468 }
469 new_blk_ptr->AddInstruction(std::move(cp_inst));
470 }
471 // Finalize inline code.
472 new_blocks->push_back(std::move(new_blk_ptr));
473 } break;
474 default: {
475 // Copy callee instruction and remap all input Ids.
Alan Bakera7717132017-11-14 14:11:50 -0500476 std::unique_ptr<ir::Instruction> cp_inst(cpi->Clone(context()));
David Netoefff5fa2017-08-31 15:47:31 -0400477 cp_inst->ForEachInId([&callee2caller, &callee_result_ids,
478 this](uint32_t* iid) {
Greg Fischer04fcc662016-11-10 10:11:50 -0700479 const auto mapItr = callee2caller.find(*iid);
480 if (mapItr != callee2caller.end()) {
481 *iid = mapItr->second;
GregFa699d1a2017-08-29 18:35:05 -0600482 } else if (callee_result_ids.find(*iid) != callee_result_ids.end()) {
483 // Forward reference. Allocate a new id, map it,
484 // use it and check for it when remapping result ids
485 const uint32_t nid = this->TakeNextId();
486 callee2caller[*iid] = nid;
487 *iid = nid;
Greg Fischer04fcc662016-11-10 10:11:50 -0700488 }
489 });
GregFa699d1a2017-08-29 18:35:05 -0600490 // If result id is non-zero, remap it. If already mapped, use mapped
491 // value, else use next id.
Greg Fischer04fcc662016-11-10 10:11:50 -0700492 const uint32_t rid = cp_inst->result_id();
493 if (rid != 0) {
GregFa699d1a2017-08-29 18:35:05 -0600494 const auto mapItr = callee2caller.find(rid);
495 uint32_t nid;
496 if (mapItr != callee2caller.end()) {
497 nid = mapItr->second;
Diego Novillod2938e42017-11-08 12:40:02 -0500498 } else {
GregFa699d1a2017-08-29 18:35:05 -0600499 nid = this->TakeNextId();
500 callee2caller[rid] = nid;
501 }
Greg Fischer04fcc662016-11-10 10:11:50 -0700502 cp_inst->SetResultId(nid);
Steven Perroneb4653a2017-11-13 15:31:43 -0500503 get_decoration_mgr()->CloneDecorations(rid, nid, update_def_use_mgr_);
Greg Fischer04fcc662016-11-10 10:11:50 -0700504 }
505 new_blk_ptr->AddInstruction(std::move(cp_inst));
506 } break;
507 }
508 });
David Netoefff5fa2017-08-31 15:47:31 -0400509
David Neto25ddfec2017-09-02 19:01:03 -0400510 if (caller_is_loop_header && (new_blocks->size() > 1)) {
David Netoefff5fa2017-08-31 15:47:31 -0400511 // Move the OpLoopMerge from the last block back to the first, where
David Neto25ddfec2017-09-02 19:01:03 -0400512 // it belongs.
David Netoefff5fa2017-08-31 15:47:31 -0400513 auto& first = new_blocks->front();
514 auto& last = new_blocks->back();
515 assert(first != last);
516
517 // Insert a modified copy of the loop merge into the first block.
518 auto loop_merge_itr = last->tail();
519 --loop_merge_itr;
520 assert(loop_merge_itr->opcode() == SpvOpLoopMerge);
Alan Bakera7717132017-11-14 14:11:50 -0500521 std::unique_ptr<ir::Instruction> cp_inst(loop_merge_itr->Clone(context()));
David Neto25ddfec2017-09-02 19:01:03 -0400522 if (caller_is_single_block_loop) {
523 // Also, update its continue target to point to the last block.
524 cp_inst->SetInOperand(kSpvLoopMergeContinueTargetIdInIdx, {last->id()});
525 }
David Netoefff5fa2017-08-31 15:47:31 -0400526 first->tail().InsertBefore(std::move(cp_inst));
527
528 // Remove the loop merge from the last block.
Steven Perronbb7802b2017-10-13 14:25:21 -0400529 loop_merge_itr->RemoveFromList();
530 delete &*loop_merge_itr;
David Netoefff5fa2017-08-31 15:47:31 -0400531 }
532
Greg Fischer04fcc662016-11-10 10:11:50 -0700533 // Update block map given replacement blocks.
534 for (auto& blk : *new_blocks) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600535 id2block_[blk->id()] = &*blk;
Greg Fischer04fcc662016-11-10 10:11:50 -0700536 }
537}
538
David Netoceb1d4f2017-03-31 10:36:58 -0400539bool InlinePass::IsInlinableFunctionCall(const ir::Instruction* inst) {
540 if (inst->opcode() != SpvOp::SpvOpFunctionCall) return false;
GregFa107d342017-04-25 13:57:20 -0600541 const uint32_t calleeFnId =
542 inst->GetSingleWordOperand(kSpvFunctionCallFunctionId);
543 const auto ci = inlinable_.find(calleeFnId);
544 return ci != inlinable_.cend();
David Netoceb1d4f2017-03-31 10:36:58 -0400545}
546
GregFe28bd392017-08-01 17:20:13 -0600547void InlinePass::UpdateSucceedingPhis(
548 std::vector<std::unique_ptr<ir::BasicBlock>>& new_blocks) {
549 const auto firstBlk = new_blocks.begin();
550 const auto lastBlk = new_blocks.end() - 1;
551 const uint32_t firstId = (*firstBlk)->id();
552 const uint32_t lastId = (*lastBlk)->id();
Diego Novillod2938e42017-11-08 12:40:02 -0500553 (*lastBlk)->ForEachSuccessorLabel([&firstId, &lastId, this](uint32_t succ) {
554 ir::BasicBlock* sbp = this->id2block_[succ];
555 sbp->ForEachPhiInst([&firstId, &lastId](ir::Instruction* phi) {
556 phi->ForEachInId([&firstId, &lastId](uint32_t* id) {
557 if (*id == firstId) *id = lastId;
GregFe28bd392017-08-01 17:20:13 -0600558 });
Diego Novillod2938e42017-11-08 12:40:02 -0500559 });
560 });
Greg Fischer04fcc662016-11-10 10:11:50 -0700561}
562
Greg Fischerbba812f2017-05-04 20:55:53 -0600563bool InlinePass::HasMultipleReturns(ir::Function* func) {
564 bool seenReturn = false;
565 bool multipleReturns = false;
566 for (auto& blk : *func) {
567 auto terminal_ii = blk.cend();
568 --terminal_ii;
Diego Novillod2938e42017-11-08 12:40:02 -0500569 if (terminal_ii->opcode() == SpvOpReturn ||
Greg Fischerbba812f2017-05-04 20:55:53 -0600570 terminal_ii->opcode() == SpvOpReturnValue) {
571 if (seenReturn) {
572 multipleReturns = true;
573 break;
574 }
575 seenReturn = true;
576 }
577 }
578 return multipleReturns;
579}
580
Greg Fischerbba812f2017-05-04 20:55:53 -0600581void InlinePass::ComputeStructuredSuccessors(ir::Function* func) {
582 // If header, make merge block first successor.
583 for (auto& blk : *func) {
Diego Novillofef669f2017-10-30 17:42:26 -0400584 uint32_t mbid = blk.MergeBlockIdIfAny();
585 if (mbid != 0) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600586 block2structured_succs_[&blk].push_back(id2block_[mbid]);
Diego Novillofef669f2017-10-30 17:42:26 -0400587 }
588
589 // Add true successors.
Greg Fischerbba812f2017-05-04 20:55:53 -0600590 blk.ForEachSuccessorLabel([&blk, this](uint32_t sbid) {
591 block2structured_succs_[&blk].push_back(id2block_[sbid]);
592 });
593 }
594}
Diego Novillofef669f2017-10-30 17:42:26 -0400595
Greg Fischerbba812f2017-05-04 20:55:53 -0600596InlinePass::GetBlocksFunction InlinePass::StructuredSuccessorsFunction() {
597 return [this](const ir::BasicBlock* block) {
598 return &(block2structured_succs_[block]);
599 };
600}
601
602bool InlinePass::HasNoReturnInLoop(ir::Function* func) {
603 // If control not structured, do not do loop/return analysis
604 // TODO: Analyze returns in non-structured control flow
Diego Novillod2938e42017-11-08 12:40:02 -0500605 if (!get_module()->HasCapability(SpvCapabilityShader)) return false;
Greg Fischerbba812f2017-05-04 20:55:53 -0600606 // Compute structured block order. This order has the property
607 // that dominators are before all blocks they dominate and merge blocks
608 // are after all blocks that are in the control constructs of their header.
609 ComputeStructuredSuccessors(func);
610 auto ignore_block = [](cbb_ptr) {};
611 auto ignore_edge = [](cbb_ptr, cbb_ptr) {};
612 std::list<const ir::BasicBlock*> structuredOrder;
613 spvtools::CFA<ir::BasicBlock>::DepthFirstTraversal(
Diego Novillod2938e42017-11-08 12:40:02 -0500614 &*func->begin(), StructuredSuccessorsFunction(), ignore_block,
615 [&](cbb_ptr b) { structuredOrder.push_front(b); }, ignore_edge);
Greg Fischerbba812f2017-05-04 20:55:53 -0600616 // Search for returns in loops. Only need to track outermost loop
617 bool return_in_loop = false;
618 uint32_t outerLoopMergeId = 0;
619 for (auto& blk : structuredOrder) {
620 // Exiting current outer loop
Diego Novillod2938e42017-11-08 12:40:02 -0500621 if (blk->id() == outerLoopMergeId) outerLoopMergeId = 0;
Greg Fischerbba812f2017-05-04 20:55:53 -0600622 // Return block
623 auto terminal_ii = blk->cend();
624 --terminal_ii;
Diego Novillod2938e42017-11-08 12:40:02 -0500625 if (terminal_ii->opcode() == SpvOpReturn ||
Greg Fischerbba812f2017-05-04 20:55:53 -0600626 terminal_ii->opcode() == SpvOpReturnValue) {
627 if (outerLoopMergeId != 0) {
628 return_in_loop = true;
629 break;
630 }
Diego Novillod2938e42017-11-08 12:40:02 -0500631 } else if (terminal_ii != blk->cbegin()) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600632 auto merge_ii = terminal_ii;
633 --merge_ii;
634 // Entering outermost loop
635 if (merge_ii->opcode() == SpvOpLoopMerge && outerLoopMergeId == 0)
Diego Novillod2938e42017-11-08 12:40:02 -0500636 outerLoopMergeId =
637 merge_ii->GetSingleWordOperand(kSpvLoopMergeMergeBlockId);
Greg Fischerbba812f2017-05-04 20:55:53 -0600638 }
639 }
640 return !return_in_loop;
641}
642
643void InlinePass::AnalyzeReturns(ir::Function* func) {
644 // Look for multiple returns
645 if (!HasMultipleReturns(func)) {
646 no_return_in_loop_.insert(func->result_id());
647 return;
648 }
David Neto2a1014b2017-08-09 14:59:04 -0400649 multi_return_funcs_.insert(func->result_id());
Greg Fischerbba812f2017-05-04 20:55:53 -0600650 // If multiple returns, see if any are in a loop
Diego Novillod2938e42017-11-08 12:40:02 -0500651 if (HasNoReturnInLoop(func)) no_return_in_loop_.insert(func->result_id());
Greg Fischerbba812f2017-05-04 20:55:53 -0600652}
653
654bool InlinePass::IsInlinableFunction(ir::Function* func) {
GregFa107d342017-04-25 13:57:20 -0600655 // We can only inline a function if it has blocks.
Diego Novillod2938e42017-11-08 12:40:02 -0500656 if (func->cbegin() == func->cend()) return false;
Greg Fischerbba812f2017-05-04 20:55:53 -0600657 // Do not inline functions with returns in loops. Currently early return
658 // functions are inlined by wrapping them in a one trip loop and implementing
659 // the returns as a branch to the loop's merge block. However, this can only
660 // done validly if the return was not in a loop in the original function.
661 // Also remember functions with multiple (early) returns.
662 AnalyzeReturns(func);
David Netoefff5fa2017-08-31 15:47:31 -0400663 return no_return_in_loop_.find(func->result_id()) !=
664 no_return_in_loop_.cend();
GregFa107d342017-04-25 13:57:20 -0600665}
666
Steven Perron476cae62017-10-30 11:13:24 -0400667void InlinePass::InitializeInline(ir::IRContext* c) {
668 InitializeProcessing(c);
Greg Fischer04fcc662016-11-10 10:11:50 -0700669
Alan Baker746bfd22017-11-14 14:11:50 -0500670 // Don't bother updating the DefUseManger
Pierre Moreau69043962017-11-30 22:32:44 +0100671 update_def_use_mgr_ = [](ir::Instruction&, bool) {};
Daniel Schürmanna76d0972017-10-24 18:28:18 +0200672
Greg Fischerbba812f2017-05-04 20:55:53 -0600673 false_id_ = 0;
674
GregFe28bd392017-08-01 17:20:13 -0600675 // clear collections
Greg Fischer04fcc662016-11-10 10:11:50 -0700676 id2function_.clear();
677 id2block_.clear();
Greg Fischerbba812f2017-05-04 20:55:53 -0600678 block2structured_succs_.clear();
GregFa107d342017-04-25 13:57:20 -0600679 inlinable_.clear();
GregFe28bd392017-08-01 17:20:13 -0600680 no_return_in_loop_.clear();
David Neto2a1014b2017-08-09 14:59:04 -0400681 multi_return_funcs_.clear();
GregFe28bd392017-08-01 17:20:13 -0600682
Diego Novillo1040a952017-10-25 13:26:25 -0400683 for (auto& fn : *get_module()) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600684 // Initialize function and block maps.
Greg Fischer04fcc662016-11-10 10:11:50 -0700685 id2function_[fn.result_id()] = &fn;
686 for (auto& blk : fn) {
Greg Fischerbba812f2017-05-04 20:55:53 -0600687 id2block_[blk.id()] = &blk;
Greg Fischer04fcc662016-11-10 10:11:50 -0700688 }
Greg Fischerbba812f2017-05-04 20:55:53 -0600689 // Compute inlinability
Diego Novillod2938e42017-11-08 12:40:02 -0500690 if (IsInlinableFunction(&fn)) inlinable_.insert(fn.result_id());
Greg Fischer04fcc662016-11-10 10:11:50 -0700691 }
692};
693
Diego Novillo1040a952017-10-25 13:26:25 -0400694InlinePass::InlinePass() {}
Greg Fischer04fcc662016-11-10 10:11:50 -0700695
Greg Fischer04fcc662016-11-10 10:11:50 -0700696} // namespace opt
697} // namespace spvtools