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
17#include "source/opt/inline_exhaustive_pass.h"
18
19#include <utility>
20
21namespace spvtools {
22namespace opt {
23
24Pass::Status InlineExhaustivePass::InlineExhaustive(Function* func) {
25 bool modified = false;
26 // Using block iterators here because of block erasures and insertions.
27 for (auto bi = func->begin(); bi != func->end(); ++bi) {
28 for (auto ii = bi->begin(); ii != bi->end();) {
29 if (IsInlinableFunctionCall(&*ii)) {
30 // Inline call.
31 std::vector<std::unique_ptr<BasicBlock>> newBlocks;
32 std::vector<std::unique_ptr<Instruction>> newVars;
33 if (!GenInlineCode(&newBlocks, &newVars, ii, bi)) {
34 return Status::Failure;
35 }
36 // If call block is replaced with more than one block, point
37 // succeeding phis at new last block.
38 if (newBlocks.size() > 1) UpdateSucceedingPhis(newBlocks);
39 // Replace old calling block with new block(s).
40
41 // We need to kill the name and decorations for the call, which
42 // will be deleted. Other instructions in the block will be moved to
43 // newBlocks. We don't need to do anything with those.
44 context()->KillNamesAndDecorates(&*ii);
45
46 bi = bi.Erase();
47
48 for (auto& bb : newBlocks) {
49 bb->SetParent(func);
50 }
51 bi = bi.InsertBefore(&newBlocks);
52 // Insert new function variables.
53 if (newVars.size() > 0)
54 func->begin()->begin().InsertBefore(std::move(newVars));
55 // Restart inlining at beginning of calling block.
56 ii = bi->begin();
57 modified = true;
58 } else {
59 ++ii;
60 }
61 }
62 }
63 return (modified ? Status::SuccessWithChange : Status::SuccessWithoutChange);
64}
65
66Pass::Status InlineExhaustivePass::ProcessImpl() {
67 Status status = Status::SuccessWithoutChange;
68 // Attempt exhaustive inlining on each entry point function in module
69 ProcessFunction pfn = [&status, this](Function* fp) {
70 status = CombineStatus(status, InlineExhaustive(fp));
71 return false;
72 };
73 context()->ProcessEntryPointCallTree(pfn);
74 return status;
75}
76
77InlineExhaustivePass::InlineExhaustivePass() = default;
78
79Pass::Status InlineExhaustivePass::Process() {
80 InitializeInline();
81 return ProcessImpl();
82}
83
84} // namespace opt
85} // namespace spvtools
86