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
21 namespace spvtools {
22 namespace opt {
23
InlineExhaustive(Function * func)24 Pass::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 bi = bi.Erase();
42
43 for (auto& bb : newBlocks) {
44 bb->SetParent(func);
45 }
46 bi = bi.InsertBefore(&newBlocks);
47 // Insert new function variables.
48 if (newVars.size() > 0)
49 func->begin()->begin().InsertBefore(std::move(newVars));
50 // Restart inlining at beginning of calling block.
51 ii = bi->begin();
52 modified = true;
53 } else {
54 ++ii;
55 }
56 }
57 }
58 return (modified ? Status::SuccessWithChange : Status::SuccessWithoutChange);
59 }
60
ProcessImpl()61 Pass::Status InlineExhaustivePass::ProcessImpl() {
62 Status status = Status::SuccessWithoutChange;
63 // Attempt exhaustive inlining on each entry point function in module
64 ProcessFunction pfn = [&status, this](Function* fp) {
65 status = CombineStatus(status, InlineExhaustive(fp));
66 return false;
67 };
68 context()->ProcessReachableCallTree(pfn);
69 return status;
70 }
71
72 InlineExhaustivePass::InlineExhaustivePass() = default;
73
Process()74 Pass::Status InlineExhaustivePass::Process() {
75 InitializeInline();
76 return ProcessImpl();
77 }
78
79 } // namespace opt
80 } // namespace spvtools
81