inline_pass.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849
  1. // 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. #include "source/opt/inline_pass.h"
  17. #include <unordered_set>
  18. #include <utility>
  19. #include "source/cfa.h"
  20. #include "source/opt/reflect.h"
  21. #include "source/util/make_unique.h"
  22. namespace spvtools {
  23. namespace opt {
  24. namespace {
  25. // Indices of operands in SPIR-V instructions
  26. constexpr int kSpvFunctionCallFunctionId = 2;
  27. constexpr int kSpvFunctionCallArgumentId = 3;
  28. constexpr int kSpvReturnValueId = 0;
  29. } // namespace
  30. uint32_t InlinePass::AddPointerToType(uint32_t type_id,
  31. spv::StorageClass storage_class) {
  32. uint32_t resultId = context()->TakeNextId();
  33. if (resultId == 0) {
  34. return resultId;
  35. }
  36. std::unique_ptr<Instruction> type_inst(
  37. new Instruction(context(), spv::Op::OpTypePointer, 0, resultId,
  38. {{spv_operand_type_t::SPV_OPERAND_TYPE_STORAGE_CLASS,
  39. {uint32_t(storage_class)}},
  40. {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {type_id}}}));
  41. context()->AddType(std::move(type_inst));
  42. analysis::Type* pointeeTy;
  43. std::unique_ptr<analysis::Pointer> pointerTy;
  44. std::tie(pointeeTy, pointerTy) =
  45. context()->get_type_mgr()->GetTypeAndPointerType(
  46. type_id, spv::StorageClass::Function);
  47. context()->get_type_mgr()->RegisterType(resultId, *pointerTy);
  48. return resultId;
  49. }
  50. void InlinePass::AddBranch(uint32_t label_id,
  51. std::unique_ptr<BasicBlock>* block_ptr) {
  52. std::unique_ptr<Instruction> newBranch(
  53. new Instruction(context(), spv::Op::OpBranch, 0, 0,
  54. {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {label_id}}}));
  55. (*block_ptr)->AddInstruction(std::move(newBranch));
  56. }
  57. void InlinePass::AddBranchCond(uint32_t cond_id, uint32_t true_id,
  58. uint32_t false_id,
  59. std::unique_ptr<BasicBlock>* block_ptr) {
  60. std::unique_ptr<Instruction> newBranch(
  61. new Instruction(context(), spv::Op::OpBranchConditional, 0, 0,
  62. {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {cond_id}},
  63. {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {true_id}},
  64. {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {false_id}}}));
  65. (*block_ptr)->AddInstruction(std::move(newBranch));
  66. }
  67. void InlinePass::AddLoopMerge(uint32_t merge_id, uint32_t continue_id,
  68. std::unique_ptr<BasicBlock>* block_ptr) {
  69. std::unique_ptr<Instruction> newLoopMerge(new Instruction(
  70. context(), spv::Op::OpLoopMerge, 0, 0,
  71. {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {merge_id}},
  72. {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {continue_id}},
  73. {spv_operand_type_t::SPV_OPERAND_TYPE_LOOP_CONTROL, {0}}}));
  74. (*block_ptr)->AddInstruction(std::move(newLoopMerge));
  75. }
  76. void InlinePass::AddStore(uint32_t ptr_id, uint32_t val_id,
  77. std::unique_ptr<BasicBlock>* block_ptr,
  78. const Instruction* line_inst,
  79. const DebugScope& dbg_scope) {
  80. std::unique_ptr<Instruction> newStore(
  81. new Instruction(context(), spv::Op::OpStore, 0, 0,
  82. {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {ptr_id}},
  83. {spv_operand_type_t::SPV_OPERAND_TYPE_ID, {val_id}}}));
  84. if (line_inst != nullptr) {
  85. newStore->AddDebugLine(line_inst);
  86. }
  87. newStore->SetDebugScope(dbg_scope);
  88. (*block_ptr)->AddInstruction(std::move(newStore));
  89. }
  90. void InlinePass::AddLoad(uint32_t type_id, uint32_t resultId, uint32_t ptr_id,
  91. std::unique_ptr<BasicBlock>* block_ptr,
  92. const Instruction* line_inst,
  93. const DebugScope& dbg_scope) {
  94. std::unique_ptr<Instruction> newLoad(
  95. new Instruction(context(), spv::Op::OpLoad, type_id, resultId,
  96. {{spv_operand_type_t::SPV_OPERAND_TYPE_ID, {ptr_id}}}));
  97. if (line_inst != nullptr) {
  98. newLoad->AddDebugLine(line_inst);
  99. }
  100. newLoad->SetDebugScope(dbg_scope);
  101. (*block_ptr)->AddInstruction(std::move(newLoad));
  102. }
  103. std::unique_ptr<Instruction> InlinePass::NewLabel(uint32_t label_id) {
  104. std::unique_ptr<Instruction> newLabel(
  105. new Instruction(context(), spv::Op::OpLabel, 0, label_id, {}));
  106. return newLabel;
  107. }
  108. uint32_t InlinePass::GetFalseId() {
  109. if (false_id_ != 0) return false_id_;
  110. false_id_ = get_module()->GetGlobalValue(spv::Op::OpConstantFalse);
  111. if (false_id_ != 0) return false_id_;
  112. uint32_t boolId = get_module()->GetGlobalValue(spv::Op::OpTypeBool);
  113. if (boolId == 0) {
  114. boolId = context()->TakeNextId();
  115. if (boolId == 0) {
  116. return 0;
  117. }
  118. get_module()->AddGlobalValue(spv::Op::OpTypeBool, boolId, 0);
  119. }
  120. false_id_ = context()->TakeNextId();
  121. if (false_id_ == 0) {
  122. return 0;
  123. }
  124. get_module()->AddGlobalValue(spv::Op::OpConstantFalse, false_id_, boolId);
  125. return false_id_;
  126. }
  127. void InlinePass::MapParams(
  128. Function* calleeFn, BasicBlock::iterator call_inst_itr,
  129. std::unordered_map<uint32_t, uint32_t>* callee2caller) {
  130. int param_idx = 0;
  131. calleeFn->ForEachParam(
  132. [&call_inst_itr, &param_idx, &callee2caller](const Instruction* cpi) {
  133. const uint32_t pid = cpi->result_id();
  134. (*callee2caller)[pid] = call_inst_itr->GetSingleWordOperand(
  135. kSpvFunctionCallArgumentId + param_idx);
  136. ++param_idx;
  137. });
  138. }
  139. bool InlinePass::CloneAndMapLocals(
  140. Function* calleeFn, std::vector<std::unique_ptr<Instruction>>* new_vars,
  141. std::unordered_map<uint32_t, uint32_t>* callee2caller,
  142. analysis::DebugInlinedAtContext* inlined_at_ctx) {
  143. auto callee_block_itr = calleeFn->begin();
  144. auto callee_var_itr = callee_block_itr->begin();
  145. while (callee_var_itr->opcode() == spv::Op::OpVariable ||
  146. callee_var_itr->GetCommonDebugOpcode() ==
  147. CommonDebugInfoDebugDeclare) {
  148. if (callee_var_itr->opcode() != spv::Op::OpVariable) {
  149. ++callee_var_itr;
  150. continue;
  151. }
  152. std::unique_ptr<Instruction> var_inst(callee_var_itr->Clone(context()));
  153. uint32_t newId = context()->TakeNextId();
  154. if (newId == 0) {
  155. return false;
  156. }
  157. get_decoration_mgr()->CloneDecorations(callee_var_itr->result_id(), newId);
  158. var_inst->SetResultId(newId);
  159. var_inst->UpdateDebugInlinedAt(
  160. context()->get_debug_info_mgr()->BuildDebugInlinedAtChain(
  161. callee_var_itr->GetDebugInlinedAt(), inlined_at_ctx));
  162. (*callee2caller)[callee_var_itr->result_id()] = newId;
  163. new_vars->push_back(std::move(var_inst));
  164. ++callee_var_itr;
  165. }
  166. return true;
  167. }
  168. uint32_t InlinePass::CreateReturnVar(
  169. Function* calleeFn, std::vector<std::unique_ptr<Instruction>>* new_vars) {
  170. uint32_t returnVarId = 0;
  171. const uint32_t calleeTypeId = calleeFn->type_id();
  172. analysis::TypeManager* type_mgr = context()->get_type_mgr();
  173. assert(type_mgr->GetType(calleeTypeId)->AsVoid() == nullptr &&
  174. "Cannot create a return variable of type void.");
  175. // Find or create ptr to callee return type.
  176. uint32_t returnVarTypeId =
  177. type_mgr->FindPointerToType(calleeTypeId, spv::StorageClass::Function);
  178. if (returnVarTypeId == 0) {
  179. returnVarTypeId =
  180. AddPointerToType(calleeTypeId, spv::StorageClass::Function);
  181. if (returnVarTypeId == 0) {
  182. return 0;
  183. }
  184. }
  185. // Add return var to new function scope variables.
  186. returnVarId = context()->TakeNextId();
  187. if (returnVarId == 0) {
  188. return 0;
  189. }
  190. std::unique_ptr<Instruction> var_inst(new Instruction(
  191. context(), spv::Op::OpVariable, returnVarTypeId, returnVarId,
  192. {{spv_operand_type_t::SPV_OPERAND_TYPE_STORAGE_CLASS,
  193. {(uint32_t)spv::StorageClass::Function}}}));
  194. new_vars->push_back(std::move(var_inst));
  195. get_decoration_mgr()->CloneDecorations(calleeFn->result_id(), returnVarId);
  196. return returnVarId;
  197. }
  198. bool InlinePass::IsSameBlockOp(const Instruction* inst) const {
  199. return inst->opcode() == spv::Op::OpSampledImage ||
  200. inst->opcode() == spv::Op::OpImage;
  201. }
  202. bool InlinePass::CloneSameBlockOps(
  203. std::unique_ptr<Instruction>* inst,
  204. std::unordered_map<uint32_t, uint32_t>* postCallSB,
  205. std::unordered_map<uint32_t, Instruction*>* preCallSB,
  206. std::unique_ptr<BasicBlock>* block_ptr) {
  207. return (*inst)->WhileEachInId([&postCallSB, &preCallSB, &block_ptr,
  208. this](uint32_t* iid) {
  209. const auto mapItr = (*postCallSB).find(*iid);
  210. if (mapItr == (*postCallSB).end()) {
  211. const auto mapItr2 = (*preCallSB).find(*iid);
  212. if (mapItr2 != (*preCallSB).end()) {
  213. // Clone pre-call same-block ops, map result id.
  214. const Instruction* inInst = mapItr2->second;
  215. std::unique_ptr<Instruction> sb_inst(inInst->Clone(context()));
  216. if (!CloneSameBlockOps(&sb_inst, postCallSB, preCallSB, block_ptr)) {
  217. return false;
  218. }
  219. const uint32_t rid = sb_inst->result_id();
  220. const uint32_t nid = context()->TakeNextId();
  221. if (nid == 0) {
  222. return false;
  223. }
  224. get_decoration_mgr()->CloneDecorations(rid, nid);
  225. sb_inst->SetResultId(nid);
  226. (*postCallSB)[rid] = nid;
  227. *iid = nid;
  228. (*block_ptr)->AddInstruction(std::move(sb_inst));
  229. }
  230. } else {
  231. // Reset same-block op operand.
  232. *iid = mapItr->second;
  233. }
  234. return true;
  235. });
  236. }
  237. void InlinePass::MoveInstsBeforeEntryBlock(
  238. std::unordered_map<uint32_t, Instruction*>* preCallSB,
  239. BasicBlock* new_blk_ptr, BasicBlock::iterator call_inst_itr,
  240. UptrVectorIterator<BasicBlock> call_block_itr) {
  241. for (auto cii = call_block_itr->begin(); cii != call_inst_itr;
  242. cii = call_block_itr->begin()) {
  243. Instruction* inst = &*cii;
  244. inst->RemoveFromList();
  245. std::unique_ptr<Instruction> cp_inst(inst);
  246. // Remember same-block ops for possible regeneration.
  247. if (IsSameBlockOp(&*cp_inst)) {
  248. auto* sb_inst_ptr = cp_inst.get();
  249. (*preCallSB)[cp_inst->result_id()] = sb_inst_ptr;
  250. }
  251. new_blk_ptr->AddInstruction(std::move(cp_inst));
  252. }
  253. }
  254. std::unique_ptr<BasicBlock> InlinePass::AddGuardBlock(
  255. std::vector<std::unique_ptr<BasicBlock>>* new_blocks,
  256. std::unordered_map<uint32_t, uint32_t>* callee2caller,
  257. std::unique_ptr<BasicBlock> new_blk_ptr, uint32_t entry_blk_label_id) {
  258. const auto guard_block_id = context()->TakeNextId();
  259. if (guard_block_id == 0) {
  260. return nullptr;
  261. }
  262. AddBranch(guard_block_id, &new_blk_ptr);
  263. new_blocks->push_back(std::move(new_blk_ptr));
  264. // Start the next block.
  265. new_blk_ptr = MakeUnique<BasicBlock>(NewLabel(guard_block_id));
  266. // Reset the mapping of the callee's entry block to point to
  267. // the guard block. Do this so we can fix up phis later on to
  268. // satisfy dominance.
  269. (*callee2caller)[entry_blk_label_id] = guard_block_id;
  270. return new_blk_ptr;
  271. }
  272. InstructionList::iterator InlinePass::AddStoresForVariableInitializers(
  273. const std::unordered_map<uint32_t, uint32_t>& callee2caller,
  274. analysis::DebugInlinedAtContext* inlined_at_ctx,
  275. std::unique_ptr<BasicBlock>* new_blk_ptr,
  276. UptrVectorIterator<BasicBlock> callee_first_block_itr) {
  277. auto callee_itr = callee_first_block_itr->begin();
  278. while (callee_itr->opcode() == spv::Op::OpVariable ||
  279. callee_itr->GetCommonDebugOpcode() == CommonDebugInfoDebugDeclare) {
  280. if (callee_itr->opcode() == spv::Op::OpVariable &&
  281. callee_itr->NumInOperands() == 2) {
  282. assert(callee2caller.count(callee_itr->result_id()) &&
  283. "Expected the variable to have already been mapped.");
  284. uint32_t new_var_id = callee2caller.at(callee_itr->result_id());
  285. // The initializer must be a constant or global value. No mapped
  286. // should be used.
  287. uint32_t val_id = callee_itr->GetSingleWordInOperand(1);
  288. AddStore(new_var_id, val_id, new_blk_ptr, callee_itr->dbg_line_inst(),
  289. context()->get_debug_info_mgr()->BuildDebugScope(
  290. callee_itr->GetDebugScope(), inlined_at_ctx));
  291. }
  292. if (callee_itr->GetCommonDebugOpcode() == CommonDebugInfoDebugDeclare) {
  293. InlineSingleInstruction(
  294. callee2caller, new_blk_ptr->get(), &*callee_itr,
  295. context()->get_debug_info_mgr()->BuildDebugInlinedAtChain(
  296. callee_itr->GetDebugScope().GetInlinedAt(), inlined_at_ctx));
  297. }
  298. ++callee_itr;
  299. }
  300. return callee_itr;
  301. }
  302. bool InlinePass::InlineSingleInstruction(
  303. const std::unordered_map<uint32_t, uint32_t>& callee2caller,
  304. BasicBlock* new_blk_ptr, const Instruction* inst, uint32_t dbg_inlined_at) {
  305. // If we have return, it must be at the end of the callee. We will handle
  306. // it at the end.
  307. if (inst->opcode() == spv::Op::OpReturnValue ||
  308. inst->opcode() == spv::Op::OpReturn)
  309. return true;
  310. // Copy callee instruction and remap all input Ids.
  311. std::unique_ptr<Instruction> cp_inst(inst->Clone(context()));
  312. cp_inst->ForEachInId([&callee2caller](uint32_t* iid) {
  313. const auto mapItr = callee2caller.find(*iid);
  314. if (mapItr != callee2caller.end()) {
  315. *iid = mapItr->second;
  316. }
  317. });
  318. // If result id is non-zero, remap it.
  319. const uint32_t rid = cp_inst->result_id();
  320. if (rid != 0) {
  321. const auto mapItr = callee2caller.find(rid);
  322. if (mapItr == callee2caller.end()) {
  323. return false;
  324. }
  325. uint32_t nid = mapItr->second;
  326. cp_inst->SetResultId(nid);
  327. get_decoration_mgr()->CloneDecorations(rid, nid);
  328. }
  329. cp_inst->UpdateDebugInlinedAt(dbg_inlined_at);
  330. new_blk_ptr->AddInstruction(std::move(cp_inst));
  331. return true;
  332. }
  333. std::unique_ptr<BasicBlock> InlinePass::InlineReturn(
  334. const std::unordered_map<uint32_t, uint32_t>& callee2caller,
  335. std::vector<std::unique_ptr<BasicBlock>>* new_blocks,
  336. std::unique_ptr<BasicBlock> new_blk_ptr,
  337. analysis::DebugInlinedAtContext* inlined_at_ctx, Function* calleeFn,
  338. const Instruction* inst, uint32_t returnVarId) {
  339. // Store return value to return variable.
  340. if (inst->opcode() == spv::Op::OpReturnValue) {
  341. assert(returnVarId != 0);
  342. uint32_t valId = inst->GetInOperand(kSpvReturnValueId).words[0];
  343. const auto mapItr = callee2caller.find(valId);
  344. if (mapItr != callee2caller.end()) {
  345. valId = mapItr->second;
  346. }
  347. AddStore(returnVarId, valId, &new_blk_ptr, inst->dbg_line_inst(),
  348. context()->get_debug_info_mgr()->BuildDebugScope(
  349. inst->GetDebugScope(), inlined_at_ctx));
  350. }
  351. uint32_t returnLabelId = 0;
  352. for (auto callee_block_itr = calleeFn->begin();
  353. callee_block_itr != calleeFn->end(); ++callee_block_itr) {
  354. if (spvOpcodeIsAbort(callee_block_itr->tail()->opcode())) {
  355. returnLabelId = context()->TakeNextId();
  356. break;
  357. }
  358. }
  359. if (returnLabelId == 0) return new_blk_ptr;
  360. if (inst->opcode() == spv::Op::OpReturn ||
  361. inst->opcode() == spv::Op::OpReturnValue)
  362. AddBranch(returnLabelId, &new_blk_ptr);
  363. new_blocks->push_back(std::move(new_blk_ptr));
  364. return MakeUnique<BasicBlock>(NewLabel(returnLabelId));
  365. }
  366. bool InlinePass::InlineEntryBlock(
  367. const std::unordered_map<uint32_t, uint32_t>& callee2caller,
  368. std::unique_ptr<BasicBlock>* new_blk_ptr,
  369. UptrVectorIterator<BasicBlock> callee_first_block,
  370. analysis::DebugInlinedAtContext* inlined_at_ctx) {
  371. auto callee_inst_itr = AddStoresForVariableInitializers(
  372. callee2caller, inlined_at_ctx, new_blk_ptr, callee_first_block);
  373. while (callee_inst_itr != callee_first_block->end()) {
  374. // Don't inline function definition links, the calling function is not a
  375. // definition.
  376. if (callee_inst_itr->GetShader100DebugOpcode() ==
  377. NonSemanticShaderDebugInfo100DebugFunctionDefinition) {
  378. ++callee_inst_itr;
  379. continue;
  380. }
  381. if (!InlineSingleInstruction(
  382. callee2caller, new_blk_ptr->get(), &*callee_inst_itr,
  383. context()->get_debug_info_mgr()->BuildDebugInlinedAtChain(
  384. callee_inst_itr->GetDebugScope().GetInlinedAt(),
  385. inlined_at_ctx))) {
  386. return false;
  387. }
  388. ++callee_inst_itr;
  389. }
  390. return true;
  391. }
  392. std::unique_ptr<BasicBlock> InlinePass::InlineBasicBlocks(
  393. std::vector<std::unique_ptr<BasicBlock>>* new_blocks,
  394. const std::unordered_map<uint32_t, uint32_t>& callee2caller,
  395. std::unique_ptr<BasicBlock> new_blk_ptr,
  396. analysis::DebugInlinedAtContext* inlined_at_ctx, Function* calleeFn) {
  397. auto callee_block_itr = calleeFn->begin();
  398. ++callee_block_itr;
  399. while (callee_block_itr != calleeFn->end()) {
  400. new_blocks->push_back(std::move(new_blk_ptr));
  401. const auto mapItr =
  402. callee2caller.find(callee_block_itr->GetLabelInst()->result_id());
  403. if (mapItr == callee2caller.end()) return nullptr;
  404. new_blk_ptr = MakeUnique<BasicBlock>(NewLabel(mapItr->second));
  405. auto tail_inst_itr = callee_block_itr->end();
  406. for (auto inst_itr = callee_block_itr->begin(); inst_itr != tail_inst_itr;
  407. ++inst_itr) {
  408. // Don't inline function definition links, the calling function is not a
  409. // definition
  410. if (inst_itr->GetShader100DebugOpcode() ==
  411. NonSemanticShaderDebugInfo100DebugFunctionDefinition)
  412. continue;
  413. if (!InlineSingleInstruction(
  414. callee2caller, new_blk_ptr.get(), &*inst_itr,
  415. context()->get_debug_info_mgr()->BuildDebugInlinedAtChain(
  416. inst_itr->GetDebugScope().GetInlinedAt(), inlined_at_ctx))) {
  417. return nullptr;
  418. }
  419. }
  420. ++callee_block_itr;
  421. }
  422. return new_blk_ptr;
  423. }
  424. bool InlinePass::MoveCallerInstsAfterFunctionCall(
  425. std::unordered_map<uint32_t, Instruction*>* preCallSB,
  426. std::unordered_map<uint32_t, uint32_t>* postCallSB,
  427. std::unique_ptr<BasicBlock>* new_blk_ptr,
  428. BasicBlock::iterator call_inst_itr, bool multiBlocks) {
  429. // Copy remaining instructions from caller block.
  430. for (Instruction* inst = call_inst_itr->NextNode(); inst;
  431. inst = call_inst_itr->NextNode()) {
  432. inst->RemoveFromList();
  433. std::unique_ptr<Instruction> cp_inst(inst);
  434. // If multiple blocks generated, regenerate any same-block
  435. // instruction that has not been seen in this last block.
  436. if (multiBlocks) {
  437. if (!CloneSameBlockOps(&cp_inst, postCallSB, preCallSB, new_blk_ptr)) {
  438. return false;
  439. }
  440. // Remember same-block ops in this block.
  441. if (IsSameBlockOp(&*cp_inst)) {
  442. const uint32_t rid = cp_inst->result_id();
  443. (*postCallSB)[rid] = rid;
  444. }
  445. }
  446. new_blk_ptr->get()->AddInstruction(std::move(cp_inst));
  447. }
  448. return true;
  449. }
  450. void InlinePass::MoveLoopMergeInstToFirstBlock(
  451. std::vector<std::unique_ptr<BasicBlock>>* new_blocks) {
  452. // Move the OpLoopMerge from the last block back to the first, where
  453. // it belongs.
  454. auto& first = new_blocks->front();
  455. auto& last = new_blocks->back();
  456. assert(first != last);
  457. // Insert a modified copy of the loop merge into the first block.
  458. auto loop_merge_itr = last->tail();
  459. --loop_merge_itr;
  460. assert(loop_merge_itr->opcode() == spv::Op::OpLoopMerge);
  461. std::unique_ptr<Instruction> cp_inst(loop_merge_itr->Clone(context()));
  462. first->tail().InsertBefore(std::move(cp_inst));
  463. // Remove the loop merge from the last block.
  464. loop_merge_itr->RemoveFromList();
  465. delete &*loop_merge_itr;
  466. }
  467. void InlinePass::UpdateSingleBlockLoopContinueTarget(
  468. uint32_t new_id, std::vector<std::unique_ptr<BasicBlock>>* new_blocks) {
  469. auto& header = new_blocks->front();
  470. auto* merge_inst = header->GetLoopMergeInst();
  471. // The back-edge block is split at the branch to create a new back-edge
  472. // block. The old block is modified to branch to the new block. The loop
  473. // merge instruction is updated to declare the new block as the continue
  474. // target. This has the effect of changing the loop from being a large
  475. // continue construct and an empty loop construct to being a loop with a loop
  476. // construct and a trivial continue construct. This change is made to satisfy
  477. // structural dominance.
  478. // Add the new basic block.
  479. std::unique_ptr<BasicBlock> new_block =
  480. MakeUnique<BasicBlock>(NewLabel(new_id));
  481. auto& old_backedge = new_blocks->back();
  482. auto old_branch = old_backedge->tail();
  483. // Move the old back edge into the new block.
  484. std::unique_ptr<Instruction> br(&*old_branch);
  485. new_block->AddInstruction(std::move(br));
  486. // Add a branch to the new block from the old back-edge block.
  487. AddBranch(new_id, &old_backedge);
  488. new_blocks->push_back(std::move(new_block));
  489. // Update the loop's continue target to the new block.
  490. merge_inst->SetInOperand(1u, {new_id});
  491. }
  492. bool InlinePass::GenInlineCode(
  493. std::vector<std::unique_ptr<BasicBlock>>* new_blocks,
  494. std::vector<std::unique_ptr<Instruction>>* new_vars,
  495. BasicBlock::iterator call_inst_itr,
  496. UptrVectorIterator<BasicBlock> call_block_itr) {
  497. // Map from all ids in the callee to their equivalent id in the caller
  498. // as callee instructions are copied into caller.
  499. std::unordered_map<uint32_t, uint32_t> callee2caller;
  500. // Pre-call same-block insts
  501. std::unordered_map<uint32_t, Instruction*> preCallSB;
  502. // Post-call same-block op ids
  503. std::unordered_map<uint32_t, uint32_t> postCallSB;
  504. analysis::DebugInlinedAtContext inlined_at_ctx(&*call_inst_itr);
  505. // Invalidate the def-use chains. They are not kept up to date while
  506. // inlining. However, certain calls try to keep them up-to-date if they are
  507. // valid. These operations can fail.
  508. context()->InvalidateAnalyses(IRContext::kAnalysisDefUse);
  509. // If the caller is a loop header and the callee has multiple blocks, then the
  510. // normal inlining logic will place the OpLoopMerge in the last of several
  511. // blocks in the loop. Instead, it should be placed at the end of the first
  512. // block. We'll wait to move the OpLoopMerge until the end of the regular
  513. // inlining logic, and only if necessary.
  514. bool caller_is_loop_header = call_block_itr->GetLoopMergeInst() != nullptr;
  515. // Single-trip loop continue block
  516. std::unique_ptr<BasicBlock> single_trip_loop_cont_blk;
  517. Function* calleeFn = id2function_[call_inst_itr->GetSingleWordOperand(
  518. kSpvFunctionCallFunctionId)];
  519. // Map parameters to actual arguments.
  520. MapParams(calleeFn, call_inst_itr, &callee2caller);
  521. // Define caller local variables for all callee variables and create map to
  522. // them.
  523. if (!CloneAndMapLocals(calleeFn, new_vars, &callee2caller, &inlined_at_ctx)) {
  524. return false;
  525. }
  526. // First block needs to use label of original block
  527. // but map callee label in case of phi reference.
  528. uint32_t entry_blk_label_id = calleeFn->begin()->GetLabelInst()->result_id();
  529. callee2caller[entry_blk_label_id] = call_block_itr->id();
  530. std::unique_ptr<BasicBlock> new_blk_ptr =
  531. MakeUnique<BasicBlock>(NewLabel(call_block_itr->id()));
  532. // Move instructions of original caller block up to call instruction.
  533. MoveInstsBeforeEntryBlock(&preCallSB, new_blk_ptr.get(), call_inst_itr,
  534. call_block_itr);
  535. if (caller_is_loop_header &&
  536. (*(calleeFn->begin())).GetMergeInst() != nullptr) {
  537. // We can't place both the caller's merge instruction and
  538. // another merge instruction in the same block. So split the
  539. // calling block. Insert an unconditional branch to a new guard
  540. // block. Later, once we know the ID of the last block, we
  541. // will move the caller's OpLoopMerge from the last generated
  542. // block into the first block. We also wait to avoid
  543. // invalidating various iterators.
  544. new_blk_ptr = AddGuardBlock(new_blocks, &callee2caller,
  545. std::move(new_blk_ptr), entry_blk_label_id);
  546. if (new_blk_ptr == nullptr) return false;
  547. }
  548. // Create return var if needed.
  549. const uint32_t calleeTypeId = calleeFn->type_id();
  550. uint32_t returnVarId = 0;
  551. analysis::Type* calleeType = context()->get_type_mgr()->GetType(calleeTypeId);
  552. if (calleeType->AsVoid() == nullptr) {
  553. returnVarId = CreateReturnVar(calleeFn, new_vars);
  554. if (returnVarId == 0) {
  555. return false;
  556. }
  557. }
  558. calleeFn->WhileEachInst([&callee2caller, this](const Instruction* cpi) {
  559. // Create set of callee result ids. Used to detect forward references
  560. const uint32_t rid = cpi->result_id();
  561. if (rid != 0 && callee2caller.find(rid) == callee2caller.end()) {
  562. const uint32_t nid = context()->TakeNextId();
  563. if (nid == 0) return false;
  564. callee2caller[rid] = nid;
  565. }
  566. return true;
  567. });
  568. // Inline DebugClare instructions in the callee's header.
  569. calleeFn->ForEachDebugInstructionsInHeader(
  570. [&new_blk_ptr, &callee2caller, &inlined_at_ctx, this](Instruction* inst) {
  571. InlineSingleInstruction(
  572. callee2caller, new_blk_ptr.get(), inst,
  573. context()->get_debug_info_mgr()->BuildDebugInlinedAtChain(
  574. inst->GetDebugScope().GetInlinedAt(), &inlined_at_ctx));
  575. });
  576. // Inline the entry block of the callee function.
  577. if (!InlineEntryBlock(callee2caller, &new_blk_ptr, calleeFn->begin(),
  578. &inlined_at_ctx)) {
  579. return false;
  580. }
  581. // Inline blocks of the callee function other than the entry block.
  582. new_blk_ptr =
  583. InlineBasicBlocks(new_blocks, callee2caller, std::move(new_blk_ptr),
  584. &inlined_at_ctx, calleeFn);
  585. if (new_blk_ptr == nullptr) return false;
  586. new_blk_ptr = InlineReturn(callee2caller, new_blocks, std::move(new_blk_ptr),
  587. &inlined_at_ctx, calleeFn,
  588. &*(calleeFn->tail()->tail()), returnVarId);
  589. // Load return value into result id of call, if it exists.
  590. if (returnVarId != 0) {
  591. const uint32_t resId = call_inst_itr->result_id();
  592. assert(resId != 0);
  593. AddLoad(calleeTypeId, resId, returnVarId, &new_blk_ptr,
  594. call_inst_itr->dbg_line_inst(), call_inst_itr->GetDebugScope());
  595. }
  596. // Move instructions of original caller block after call instruction.
  597. if (!MoveCallerInstsAfterFunctionCall(&preCallSB, &postCallSB, &new_blk_ptr,
  598. call_inst_itr,
  599. calleeFn->begin() != calleeFn->end()))
  600. return false;
  601. // Finalize inline code.
  602. new_blocks->push_back(std::move(new_blk_ptr));
  603. if (caller_is_loop_header && (new_blocks->size() > 1)) {
  604. MoveLoopMergeInstToFirstBlock(new_blocks);
  605. // If the loop was a single basic block previously, update it's structure.
  606. auto& header = new_blocks->front();
  607. auto* merge_inst = header->GetLoopMergeInst();
  608. if (merge_inst->GetSingleWordInOperand(1u) == header->id()) {
  609. auto new_id = context()->TakeNextId();
  610. if (new_id == 0) return false;
  611. UpdateSingleBlockLoopContinueTarget(new_id, new_blocks);
  612. }
  613. }
  614. // Update block map given replacement blocks.
  615. for (auto& blk : *new_blocks) {
  616. id2block_[blk->id()] = &*blk;
  617. }
  618. // We need to kill the name and decorations for the call, which will be
  619. // deleted.
  620. context()->KillNamesAndDecorates(&*call_inst_itr);
  621. return true;
  622. }
  623. bool InlinePass::IsInlinableFunctionCall(const Instruction* inst) {
  624. if (inst->opcode() != spv::Op::OpFunctionCall) return false;
  625. const uint32_t calleeFnId =
  626. inst->GetSingleWordOperand(kSpvFunctionCallFunctionId);
  627. const auto ci = inlinable_.find(calleeFnId);
  628. if (ci == inlinable_.cend()) return false;
  629. if (early_return_funcs_.find(calleeFnId) != early_return_funcs_.end()) {
  630. // We rely on the merge-return pass to handle the early return case
  631. // in advance.
  632. std::string message =
  633. "The function '" + id2function_[calleeFnId]->DefInst().PrettyPrint() +
  634. "' could not be inlined because the return instruction "
  635. "is not at the end of the function. This could be fixed by "
  636. "running merge-return before inlining.";
  637. consumer()(SPV_MSG_WARNING, "", {0, 0, 0}, message.c_str());
  638. return false;
  639. }
  640. return true;
  641. }
  642. void InlinePass::UpdateSucceedingPhis(
  643. std::vector<std::unique_ptr<BasicBlock>>& new_blocks) {
  644. const auto firstBlk = new_blocks.begin();
  645. const auto lastBlk = new_blocks.end() - 1;
  646. const uint32_t firstId = (*firstBlk)->id();
  647. const uint32_t lastId = (*lastBlk)->id();
  648. const BasicBlock& const_last_block = *lastBlk->get();
  649. const_last_block.ForEachSuccessorLabel(
  650. [&firstId, &lastId, this](const uint32_t succ) {
  651. BasicBlock* sbp = this->id2block_[succ];
  652. sbp->ForEachPhiInst([&firstId, &lastId](Instruction* phi) {
  653. phi->ForEachInId([&firstId, &lastId](uint32_t* id) {
  654. if (*id == firstId) *id = lastId;
  655. });
  656. });
  657. });
  658. }
  659. bool InlinePass::HasNoReturnInLoop(Function* func) {
  660. // If control not structured, do not do loop/return analysis
  661. // TODO: Analyze returns in non-structured control flow
  662. if (!context()->get_feature_mgr()->HasCapability(spv::Capability::Shader))
  663. return false;
  664. const auto structured_analysis = context()->GetStructuredCFGAnalysis();
  665. // Search for returns in structured construct.
  666. bool return_in_loop = false;
  667. for (auto& blk : *func) {
  668. auto terminal_ii = blk.cend();
  669. --terminal_ii;
  670. if (spvOpcodeIsReturn(terminal_ii->opcode()) &&
  671. structured_analysis->ContainingLoop(blk.id()) != 0) {
  672. return_in_loop = true;
  673. break;
  674. }
  675. }
  676. return !return_in_loop;
  677. }
  678. void InlinePass::AnalyzeReturns(Function* func) {
  679. // Analyze functions without a return in loop.
  680. if (HasNoReturnInLoop(func)) {
  681. no_return_in_loop_.insert(func->result_id());
  682. }
  683. // Analyze functions with a return before its tail basic block.
  684. for (auto& blk : *func) {
  685. auto terminal_ii = blk.cend();
  686. --terminal_ii;
  687. if (spvOpcodeIsReturn(terminal_ii->opcode()) && &blk != func->tail()) {
  688. early_return_funcs_.insert(func->result_id());
  689. break;
  690. }
  691. }
  692. }
  693. bool InlinePass::IsInlinableFunction(Function* func) {
  694. // We can only inline a function if it has blocks.
  695. if (func->cbegin() == func->cend()) return false;
  696. // Do not inline functions with DontInline flag.
  697. if (func->control_mask() & uint32_t(spv::FunctionControlMask::DontInline)) {
  698. return false;
  699. }
  700. // Do not inline functions with returns in loops. Currently early return
  701. // functions are inlined by wrapping them in a one trip loop and implementing
  702. // the returns as a branch to the loop's merge block. However, this can only
  703. // done validly if the return was not in a loop in the original function.
  704. // Also remember functions with multiple (early) returns.
  705. AnalyzeReturns(func);
  706. if (no_return_in_loop_.find(func->result_id()) == no_return_in_loop_.cend()) {
  707. return false;
  708. }
  709. if (func->IsRecursive()) {
  710. return false;
  711. }
  712. // Do not inline functions with an abort instruction if they are called from a
  713. // continue construct. If it is inlined into a continue construct the backedge
  714. // will no longer post-dominate the continue target, which is invalid. An
  715. // `OpUnreachable` is acceptable because it will not change post-dominance if
  716. // it is statically unreachable.
  717. bool func_is_called_from_continue =
  718. funcs_called_from_continue_.count(func->result_id()) != 0;
  719. if (func_is_called_from_continue && ContainsAbortOtherThanUnreachable(func)) {
  720. return false;
  721. }
  722. return true;
  723. }
  724. bool InlinePass::ContainsAbortOtherThanUnreachable(Function* func) const {
  725. return !func->WhileEachInst([](Instruction* inst) {
  726. return inst->opcode() == spv::Op::OpUnreachable ||
  727. !spvOpcodeIsAbort(inst->opcode());
  728. });
  729. }
  730. void InlinePass::InitializeInline() {
  731. false_id_ = 0;
  732. // clear collections
  733. id2function_.clear();
  734. id2block_.clear();
  735. inlinable_.clear();
  736. no_return_in_loop_.clear();
  737. early_return_funcs_.clear();
  738. funcs_called_from_continue_ =
  739. context()->GetStructuredCFGAnalysis()->FindFuncsCalledFromContinue();
  740. for (auto& fn : *get_module()) {
  741. // Initialize function and block maps.
  742. id2function_[fn.result_id()] = &fn;
  743. for (auto& blk : fn) {
  744. id2block_[blk.id()] = &blk;
  745. }
  746. // Compute inlinability
  747. if (IsInlinableFunction(&fn)) inlinable_.insert(fn.result_id());
  748. }
  749. }
  750. InlinePass::InlinePass() {}
  751. } // namespace opt
  752. } // namespace spvtools