comparison lib/Transforms/IPO/BlockExtractor.cpp @ 147:c2174574ed3a

LLVM 10
author Shinji KONO <kono@ie.u-ryukyu.ac.jp>
date Wed, 14 Aug 2019 16:55:33 +0900
parents 3a76565eade5
children
comparison
equal deleted inserted replaced
134:3a76565eade5 147:c2174574ed3a
1 //===- BlockExtractor.cpp - Extracts blocks into their own functions ------===// 1 //===- BlockExtractor.cpp - Extracts blocks into their own functions ------===//
2 // 2 //
3 // The LLVM Compiler Infrastructure 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // 4 // See https://llvm.org/LICENSE.txt for license information.
5 // This file is distributed under the University of Illinois Open Source 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 // License. See LICENSE.TXT for details.
7 // 6 //
8 //===----------------------------------------------------------------------===// 7 //===----------------------------------------------------------------------===//
9 // 8 //
10 // This pass extracts the specified basic blocks from the module into their 9 // This pass extracts the specified basic blocks from the module into their
11 // own functions. 10 // own functions.
21 #include "llvm/Support/Debug.h" 20 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/MemoryBuffer.h" 21 #include "llvm/Support/MemoryBuffer.h"
23 #include "llvm/Transforms/IPO.h" 22 #include "llvm/Transforms/IPO.h"
24 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 23 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
25 #include "llvm/Transforms/Utils/CodeExtractor.h" 24 #include "llvm/Transforms/Utils/CodeExtractor.h"
25
26 using namespace llvm; 26 using namespace llvm;
27 27
28 #define DEBUG_TYPE "block-extractor" 28 #define DEBUG_TYPE "block-extractor"
29 29
30 STATISTIC(NumExtracted, "Number of basic blocks extracted"); 30 STATISTIC(NumExtracted, "Number of basic blocks extracted");
34 cl::desc("A file containing list of basic blocks to extract"), cl::Hidden); 34 cl::desc("A file containing list of basic blocks to extract"), cl::Hidden);
35 35
36 cl::opt<bool> BlockExtractorEraseFuncs("extract-blocks-erase-funcs", 36 cl::opt<bool> BlockExtractorEraseFuncs("extract-blocks-erase-funcs",
37 cl::desc("Erase the existing functions"), 37 cl::desc("Erase the existing functions"),
38 cl::Hidden); 38 cl::Hidden);
39
40 namespace { 39 namespace {
41 class BlockExtractor : public ModulePass { 40 class BlockExtractor : public ModulePass {
42 SmallVector<BasicBlock *, 16> Blocks; 41 SmallVector<SmallVector<BasicBlock *, 16>, 4> GroupsOfBlocks;
43 bool EraseFunctions; 42 bool EraseFunctions;
44 SmallVector<std::pair<std::string, std::string>, 32> BlocksByName; 43 /// Map a function name to groups of blocks.
44 SmallVector<std::pair<std::string, SmallVector<std::string, 4>>, 4>
45 BlocksByName;
46
47 void init(const SmallVectorImpl<SmallVector<BasicBlock *, 16>>
48 &GroupsOfBlocksToExtract) {
49 for (const SmallVectorImpl<BasicBlock *> &GroupOfBlocks :
50 GroupsOfBlocksToExtract) {
51 SmallVector<BasicBlock *, 16> NewGroup;
52 NewGroup.append(GroupOfBlocks.begin(), GroupOfBlocks.end());
53 GroupsOfBlocks.emplace_back(NewGroup);
54 }
55 if (!BlockExtractorFile.empty())
56 loadFile();
57 }
45 58
46 public: 59 public:
47 static char ID; 60 static char ID;
48 BlockExtractor(const SmallVectorImpl<BasicBlock *> &BlocksToExtract, 61 BlockExtractor(const SmallVectorImpl<BasicBlock *> &BlocksToExtract,
49 bool EraseFunctions) 62 bool EraseFunctions)
50 : ModulePass(ID), Blocks(BlocksToExtract.begin(), BlocksToExtract.end()), 63 : ModulePass(ID), EraseFunctions(EraseFunctions) {
51 EraseFunctions(EraseFunctions) { 64 // We want one group per element of the input list.
52 if (!BlockExtractorFile.empty()) 65 SmallVector<SmallVector<BasicBlock *, 16>, 4> MassagedGroupsOfBlocks;
53 loadFile(); 66 for (BasicBlock *BB : BlocksToExtract) {
54 } 67 SmallVector<BasicBlock *, 16> NewGroup;
68 NewGroup.push_back(BB);
69 MassagedGroupsOfBlocks.push_back(NewGroup);
70 }
71 init(MassagedGroupsOfBlocks);
72 }
73
74 BlockExtractor(const SmallVectorImpl<SmallVector<BasicBlock *, 16>>
75 &GroupsOfBlocksToExtract,
76 bool EraseFunctions)
77 : ModulePass(ID), EraseFunctions(EraseFunctions) {
78 init(GroupsOfBlocksToExtract);
79 }
80
55 BlockExtractor() : BlockExtractor(SmallVector<BasicBlock *, 0>(), false) {} 81 BlockExtractor() : BlockExtractor(SmallVector<BasicBlock *, 0>(), false) {}
56 bool runOnModule(Module &M) override; 82 bool runOnModule(Module &M) override;
57 83
58 private: 84 private:
59 void loadFile(); 85 void loadFile();
67 93
68 ModulePass *llvm::createBlockExtractorPass() { return new BlockExtractor(); } 94 ModulePass *llvm::createBlockExtractorPass() { return new BlockExtractor(); }
69 ModulePass *llvm::createBlockExtractorPass( 95 ModulePass *llvm::createBlockExtractorPass(
70 const SmallVectorImpl<BasicBlock *> &BlocksToExtract, bool EraseFunctions) { 96 const SmallVectorImpl<BasicBlock *> &BlocksToExtract, bool EraseFunctions) {
71 return new BlockExtractor(BlocksToExtract, EraseFunctions); 97 return new BlockExtractor(BlocksToExtract, EraseFunctions);
98 }
99 ModulePass *llvm::createBlockExtractorPass(
100 const SmallVectorImpl<SmallVector<BasicBlock *, 16>>
101 &GroupsOfBlocksToExtract,
102 bool EraseFunctions) {
103 return new BlockExtractor(GroupsOfBlocksToExtract, EraseFunctions);
72 } 104 }
73 105
74 /// Gets all of the blocks specified in the input file. 106 /// Gets all of the blocks specified in the input file.
75 void BlockExtractor::loadFile() { 107 void BlockExtractor::loadFile() {
76 auto ErrOrBuf = MemoryBuffer::getFile(BlockExtractorFile); 108 auto ErrOrBuf = MemoryBuffer::getFile(BlockExtractorFile);
80 auto &Buf = *ErrOrBuf; 112 auto &Buf = *ErrOrBuf;
81 SmallVector<StringRef, 16> Lines; 113 SmallVector<StringRef, 16> Lines;
82 Buf->getBuffer().split(Lines, '\n', /*MaxSplit=*/-1, 114 Buf->getBuffer().split(Lines, '\n', /*MaxSplit=*/-1,
83 /*KeepEmpty=*/false); 115 /*KeepEmpty=*/false);
84 for (const auto &Line : Lines) { 116 for (const auto &Line : Lines) {
85 auto FBPair = Line.split(' '); 117 SmallVector<StringRef, 4> LineSplit;
86 BlocksByName.push_back({FBPair.first, FBPair.second}); 118 Line.split(LineSplit, ' ', /*MaxSplit=*/-1,
119 /*KeepEmpty=*/false);
120 if (LineSplit.empty())
121 continue;
122 SmallVector<StringRef, 4> BBNames;
123 LineSplit[1].split(BBNames, ';', /*MaxSplit=*/-1,
124 /*KeepEmpty=*/false);
125 if (BBNames.empty())
126 report_fatal_error("Missing bbs name");
127 BlocksByName.push_back({LineSplit[0], {BBNames.begin(), BBNames.end()}});
87 } 128 }
88 } 129 }
89 130
90 /// Extracts the landing pads to make sure all of them have only one 131 /// Extracts the landing pads to make sure all of them have only one
91 /// predecessor. 132 /// predecessor.
128 splitLandingPadPreds(F); 169 splitLandingPadPreds(F);
129 Functions.push_back(&F); 170 Functions.push_back(&F);
130 } 171 }
131 172
132 // Get all the blocks specified in the input file. 173 // Get all the blocks specified in the input file.
174 unsigned NextGroupIdx = GroupsOfBlocks.size();
175 GroupsOfBlocks.resize(NextGroupIdx + BlocksByName.size());
133 for (const auto &BInfo : BlocksByName) { 176 for (const auto &BInfo : BlocksByName) {
134 Function *F = M.getFunction(BInfo.first); 177 Function *F = M.getFunction(BInfo.first);
135 if (!F) 178 if (!F)
136 report_fatal_error("Invalid function name specified in the input file"); 179 report_fatal_error("Invalid function name specified in the input file");
137 auto Res = llvm::find_if(*F, [&](const BasicBlock &BB) { 180 for (const auto &BBInfo : BInfo.second) {
138 return BB.getName().equals(BInfo.second); 181 auto Res = llvm::find_if(*F, [&](const BasicBlock &BB) {
139 }); 182 return BB.getName().equals(BBInfo);
140 if (Res == F->end()) 183 });
141 report_fatal_error("Invalid block name specified in the input file"); 184 if (Res == F->end())
142 Blocks.push_back(&*Res); 185 report_fatal_error("Invalid block name specified in the input file");
143 } 186 GroupsOfBlocks[NextGroupIdx].push_back(&*Res);
144 187 }
145 // Extract basic blocks. 188 ++NextGroupIdx;
146 for (BasicBlock *BB : Blocks) { 189 }
147 // Check if the module contains BB. 190
148 if (BB->getParent()->getParent() != &M) 191 // Extract each group of basic blocks.
149 report_fatal_error("Invalid basic block"); 192 for (auto &BBs : GroupsOfBlocks) {
150 DEBUG(dbgs() << "BlockExtractor: Extracting " << BB->getParent()->getName() 193 SmallVector<BasicBlock *, 32> BlocksToExtractVec;
151 << ":" << BB->getName() << "\n"); 194 for (BasicBlock *BB : BBs) {
152 SmallVector<BasicBlock *, 2> BlocksToExtractVec; 195 // Check if the module contains BB.
153 BlocksToExtractVec.push_back(BB); 196 if (BB->getParent()->getParent() != &M)
154 if (const InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) 197 report_fatal_error("Invalid basic block");
155 BlocksToExtractVec.push_back(II->getUnwindDest()); 198 LLVM_DEBUG(dbgs() << "BlockExtractor: Extracting "
156 CodeExtractor(BlocksToExtractVec).extractCodeRegion(); 199 << BB->getParent()->getName() << ":" << BB->getName()
157 ++NumExtracted; 200 << "\n");
158 Changed = true; 201 BlocksToExtractVec.push_back(BB);
202 if (const InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator()))
203 BlocksToExtractVec.push_back(II->getUnwindDest());
204 ++NumExtracted;
205 Changed = true;
206 }
207 Function *F = CodeExtractor(BlocksToExtractVec).extractCodeRegion();
208 if (F)
209 LLVM_DEBUG(dbgs() << "Extracted group '" << (*BBs.begin())->getName()
210 << "' in: " << F->getName() << '\n');
211 else
212 LLVM_DEBUG(dbgs() << "Failed to extract for group '"
213 << (*BBs.begin())->getName() << "'\n");
159 } 214 }
160 215
161 // Erase the functions. 216 // Erase the functions.
162 if (EraseFunctions || BlockExtractorEraseFuncs) { 217 if (EraseFunctions || BlockExtractorEraseFuncs) {
163 for (Function *F : Functions) { 218 for (Function *F : Functions) {
164 DEBUG(dbgs() << "BlockExtractor: Deleting " << F->getName() << "\n"); 219 LLVM_DEBUG(dbgs() << "BlockExtractor: Trying to delete " << F->getName()
165 F->eraseFromParent(); 220 << "\n");
221 F->deleteBody();
166 } 222 }
167 // Set linkage as ExternalLinkage to avoid erasing unreachable functions. 223 // Set linkage as ExternalLinkage to avoid erasing unreachable functions.
168 for (Function &F : M) 224 for (Function &F : M)
169 F.setLinkage(GlobalValue::ExternalLinkage); 225 F.setLinkage(GlobalValue::ExternalLinkage);
170 Changed = true; 226 Changed = true;