blob: 94aaa2f52eb58738591d51ac6ce40f694ccbf3fc [file] [log] [blame]
Misha Brukmande03bc02005-04-24 17:36:05 +00001//===- llvm-extract.cpp - LLVM function extraction utility ----------------===//
Misha Brukman3da94ae2005-04-22 00:00:37 +00002//
John Criswell7c0e0222003-10-20 17:47:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner21c62da2007-12-29 20:44:31 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman3da94ae2005-04-22 00:00:37 +00007//
John Criswell7c0e0222003-10-20 17:47:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner579d9142002-05-22 20:27:00 +00009//
10// This utility changes the input module to only contain a single function,
11// which is primarily used for debugging transformations.
12//
13//===----------------------------------------------------------------------===//
14
Chandler Carruthf010c462012-12-04 10:44:52 +000015#include "llvm/ADT/SetVector.h"
16#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruthe2dc71d2014-01-13 07:38:24 +000017#include "llvm/Bitcode/BitcodeWriterPass.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000018#include "llvm/IR/DataLayout.h"
Chandler Carruth8a5351f2014-01-12 11:10:32 +000019#include "llvm/IR/IRPrintingPasses.h"
Keno Fischer1f6fa0f2017-04-06 20:51:40 +000020#include "llvm/IR/Instructions.h"
Chandler Carruth8a5351f2014-01-12 11:10:32 +000021#include "llvm/IR/LLVMContext.h"
Keno Fischer1f6fa0f2017-04-06 20:51:40 +000022#include "llvm/IR/LegacyPassManager.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000023#include "llvm/IR/Module.h"
Chandler Carruth7fc162f2013-03-26 02:25:37 +000024#include "llvm/IRReader/IRReader.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000025#include "llvm/Support/CommandLine.h"
Peter Collingbourne76c218e2016-11-09 17:49:19 +000026#include "llvm/Support/Error.h"
Benjamin Kramer7259f142014-04-29 23:26:49 +000027#include "llvm/Support/FileSystem.h"
Rui Ueyama0b9d56a2018-04-13 18:26:06 +000028#include "llvm/Support/InitLLVM.h"
Chad Rosier4e0a55d2011-09-16 21:09:17 +000029#include "llvm/Support/Regex.h"
Chandler Carruth7fc162f2013-03-26 02:25:37 +000030#include "llvm/Support/SourceMgr.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000031#include "llvm/Support/SystemUtils.h"
32#include "llvm/Support/ToolOutputFile.h"
33#include "llvm/Transforms/IPO.h"
Chris Lattner579d9142002-05-22 20:27:00 +000034#include <memory>
Brian Gaeked0fde302003-11-11 22:41:34 +000035using namespace llvm;
36
Chris Lattner5ff62e92002-07-22 02:10:13 +000037// InputFilename - The filename to read from.
Chris Lattnerc7a09852002-07-25 16:31:09 +000038static cl::opt<std::string>
Gabor Greifa99be512007-07-05 17:07:56 +000039InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
Chris Lattner5ff62e92002-07-22 02:10:13 +000040 cl::init("-"), cl::value_desc("filename"));
Misha Brukman3da94ae2005-04-22 00:00:37 +000041
Chris Lattnerba9cc1f2004-02-18 16:53:59 +000042static cl::opt<std::string>
Misha Brukman3da94ae2005-04-22 00:00:37 +000043OutputFilename("o", cl::desc("Specify output filename"),
Chris Lattnerba9cc1f2004-02-18 16:53:59 +000044 cl::value_desc("filename"), cl::init("-"));
45
46static cl::opt<bool>
Dan Gohmanbaa26392009-08-25 15:34:52 +000047Force("f", cl::desc("Enable binary output on terminals"));
Chris Lattner5ff62e92002-07-22 02:10:13 +000048
Misha Brukmanca718e42004-04-22 23:07:39 +000049static cl::opt<bool>
Andrew Lenharthd245a8a2008-03-07 19:51:57 +000050DeleteFn("delete", cl::desc("Delete specified Globals from Module"));
Misha Brukmanca718e42004-04-22 23:07:39 +000051
Keno Fischer1f6fa0f2017-04-06 20:51:40 +000052static cl::opt<bool>
53 Recursive("recursive",
54 cl::desc("Recursively extract all called functions"));
55
Chad Rosier4e0a55d2011-09-16 21:09:17 +000056// ExtractFuncs - The functions to extract from the module.
Dan Gohmana499d202010-02-10 23:58:53 +000057static cl::list<std::string>
58ExtractFuncs("func", cl::desc("Specify function to extract"),
59 cl::ZeroOrMore, cl::value_desc("function"));
Chris Lattner5ff62e92002-07-22 02:10:13 +000060
Andrew Trick2cccc622013-09-18 23:31:10 +000061// ExtractRegExpFuncs - The functions, matched via regular expression, to
Chad Rosier4e0a55d2011-09-16 21:09:17 +000062// extract from the module.
63static cl::list<std::string>
64ExtractRegExpFuncs("rfunc", cl::desc("Specify function(s) to extract using a "
65 "regular expression"),
66 cl::ZeroOrMore, cl::value_desc("rfunction"));
67
Volkan Keles22b25642018-01-23 21:51:34 +000068// ExtractBlocks - The blocks to extract from the module.
69static cl::list<std::string>
70 ExtractBlocks("bb",
71 cl::desc("Specify <function, basic block> pairs to extract"),
72 cl::ZeroOrMore, cl::value_desc("function:bb"));
73
Rafael Espindolaca88cee2012-10-29 02:23:07 +000074// ExtractAlias - The alias to extract from the module.
75static cl::list<std::string>
76ExtractAliases("alias", cl::desc("Specify alias to extract"),
77 cl::ZeroOrMore, cl::value_desc("alias"));
78
79
80// ExtractRegExpAliases - The aliases, matched via regular expression, to
81// extract from the module.
82static cl::list<std::string>
83ExtractRegExpAliases("ralias", cl::desc("Specify alias(es) to extract using a "
84 "regular expression"),
85 cl::ZeroOrMore, cl::value_desc("ralias"));
86
Chad Rosier4e0a55d2011-09-16 21:09:17 +000087// ExtractGlobals - The globals to extract from the module.
Dan Gohmana499d202010-02-10 23:58:53 +000088static cl::list<std::string>
89ExtractGlobals("glob", cl::desc("Specify global to extract"),
90 cl::ZeroOrMore, cl::value_desc("global"));
Andrew Lenharthd245a8a2008-03-07 19:51:57 +000091
Chad Rosier4e0a55d2011-09-16 21:09:17 +000092// ExtractRegExpGlobals - The globals, matched via regular expression, to
93// extract from the module...
94static cl::list<std::string>
95ExtractRegExpGlobals("rglob", cl::desc("Specify global(s) to extract using a "
96 "regular expression"),
97 cl::ZeroOrMore, cl::value_desc("rglobal"));
98
Dan Gohmanec080462009-09-11 20:46:33 +000099static cl::opt<bool>
100OutputAssembly("S",
101 cl::desc("Write output as LLVM assembly"), cl::Hidden);
102
Duncan P. N. Exon Smith8d61ee92015-04-15 03:14:06 +0000103static cl::opt<bool> PreserveBitcodeUseListOrder(
104 "preserve-bc-uselistorder",
105 cl::desc("Preserve use-list order when writing LLVM bitcode."),
106 cl::init(true), cl::Hidden);
107
108static cl::opt<bool> PreserveAssemblyUseListOrder(
109 "preserve-ll-uselistorder",
110 cl::desc("Preserve use-list order when writing LLVM assembly."),
111 cl::init(false), cl::Hidden);
112
Chris Lattner579d9142002-05-22 20:27:00 +0000113int main(int argc, char **argv) {
Rui Ueyama0b9d56a2018-04-13 18:26:06 +0000114 InitLLVM X(argc, argv);
Owen Anderson8b477ed2009-07-01 16:58:40 +0000115
Mehdi Amini8be77072016-04-14 21:59:01 +0000116 LLVMContext Context;
Chris Lattnercc14d252009-03-06 05:34:10 +0000117 cl::ParseCommandLineOptions(argc, argv, "llvm extractor\n");
Chris Lattner579d9142002-05-22 20:27:00 +0000118
Dan Gohman44f95332010-08-25 23:33:07 +0000119 // Use lazy loading, since we only care about selected global values.
Dan Gohmanec080462009-09-11 20:46:33 +0000120 SMDiagnostic Err;
Rafael Espindola81e49922014-08-26 17:29:46 +0000121 std::unique_ptr<Module> M = getLazyIRFileModule(InputFilename, Err, Context);
Dan Gohmanec080462009-09-11 20:46:33 +0000122
Craig Topper573faec2014-04-25 04:24:47 +0000123 if (!M.get()) {
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000124 Err.print(argv[0], errs());
Chris Lattnerc48e1db2007-05-06 05:13:17 +0000125 return 1;
126 }
127
Chad Rosier4e0a55d2011-09-16 21:09:17 +0000128 // Use SetVector to avoid duplicates.
129 SetVector<GlobalValue *> GVs;
Andrew Lenharthd245a8a2008-03-07 19:51:57 +0000130
Rafael Espindolaca88cee2012-10-29 02:23:07 +0000131 // Figure out which aliases we should extract.
132 for (size_t i = 0, e = ExtractAliases.size(); i != e; ++i) {
133 GlobalAlias *GA = M->getNamedAlias(ExtractAliases[i]);
134 if (!GA) {
135 errs() << argv[0] << ": program doesn't contain alias named '"
136 << ExtractAliases[i] << "'!\n";
137 return 1;
138 }
139 GVs.insert(GA);
140 }
141
142 // Extract aliases via regular expression matching.
143 for (size_t i = 0, e = ExtractRegExpAliases.size(); i != e; ++i) {
144 std::string Error;
145 Regex RegEx(ExtractRegExpAliases[i]);
146 if (!RegEx.isValid(Error)) {
147 errs() << argv[0] << ": '" << ExtractRegExpAliases[i] << "' "
148 "invalid regex: " << Error;
149 }
150 bool match = false;
151 for (Module::alias_iterator GA = M->alias_begin(), E = M->alias_end();
152 GA != E; GA++) {
153 if (RegEx.match(GA->getName())) {
154 GVs.insert(&*GA);
155 match = true;
156 }
157 }
158 if (!match) {
159 errs() << argv[0] << ": program doesn't contain global named '"
160 << ExtractRegExpAliases[i] << "'!\n";
161 return 1;
162 }
163 }
164
Dan Gohmana499d202010-02-10 23:58:53 +0000165 // Figure out which globals we should extract.
166 for (size_t i = 0, e = ExtractGlobals.size(); i != e; ++i) {
Nick Lewyckydb186c42011-12-30 19:17:23 +0000167 GlobalValue *GV = M->getNamedGlobal(ExtractGlobals[i]);
Dan Gohmana499d202010-02-10 23:58:53 +0000168 if (!GV) {
169 errs() << argv[0] << ": program doesn't contain global named '"
170 << ExtractGlobals[i] << "'!\n";
171 return 1;
172 }
Chad Rosier4e0a55d2011-09-16 21:09:17 +0000173 GVs.insert(GV);
174 }
175
176 // Extract globals via regular expression matching.
177 for (size_t i = 0, e = ExtractRegExpGlobals.size(); i != e; ++i) {
178 std::string Error;
179 Regex RegEx(ExtractRegExpGlobals[i]);
180 if (!RegEx.isValid(Error)) {
181 errs() << argv[0] << ": '" << ExtractRegExpGlobals[i] << "' "
182 "invalid regex: " << Error;
183 }
184 bool match = false;
Rafael Espindola82cb28e2014-05-08 19:30:17 +0000185 for (auto &GV : M->globals()) {
186 if (RegEx.match(GV.getName())) {
187 GVs.insert(&GV);
Chad Rosier4e0a55d2011-09-16 21:09:17 +0000188 match = true;
189 }
190 }
191 if (!match) {
192 errs() << argv[0] << ": program doesn't contain global named '"
193 << ExtractRegExpGlobals[i] << "'!\n";
194 return 1;
195 }
Dan Gohmana499d202010-02-10 23:58:53 +0000196 }
Andrew Lenharthd245a8a2008-03-07 19:51:57 +0000197
Dan Gohmana499d202010-02-10 23:58:53 +0000198 // Figure out which functions we should extract.
199 for (size_t i = 0, e = ExtractFuncs.size(); i != e; ++i) {
Nick Lewyckydb186c42011-12-30 19:17:23 +0000200 GlobalValue *GV = M->getFunction(ExtractFuncs[i]);
Dan Gohmana499d202010-02-10 23:58:53 +0000201 if (!GV) {
202 errs() << argv[0] << ": program doesn't contain function named '"
203 << ExtractFuncs[i] << "'!\n";
204 return 1;
205 }
Chad Rosier4e0a55d2011-09-16 21:09:17 +0000206 GVs.insert(GV);
207 }
208 // Extract functions via regular expression matching.
209 for (size_t i = 0, e = ExtractRegExpFuncs.size(); i != e; ++i) {
210 std::string Error;
211 StringRef RegExStr = ExtractRegExpFuncs[i];
212 Regex RegEx(RegExStr);
213 if (!RegEx.isValid(Error)) {
214 errs() << argv[0] << ": '" << ExtractRegExpFuncs[i] << "' "
215 "invalid regex: " << Error;
216 }
217 bool match = false;
Nick Lewyckydb186c42011-12-30 19:17:23 +0000218 for (Module::iterator F = M->begin(), E = M->end(); F != E;
Chad Rosier4e0a55d2011-09-16 21:09:17 +0000219 F++) {
220 if (RegEx.match(F->getName())) {
221 GVs.insert(&*F);
222 match = true;
223 }
224 }
225 if (!match) {
226 errs() << argv[0] << ": program doesn't contain global named '"
227 << ExtractRegExpFuncs[i] << "'!\n";
228 return 1;
229 }
Chris Lattnerc48e1db2007-05-06 05:13:17 +0000230 }
231
Volkan Keles22b25642018-01-23 21:51:34 +0000232 // Figure out which BasicBlocks we should extract.
233 SmallVector<BasicBlock *, 4> BBs;
234 for (StringRef StrPair : ExtractBlocks) {
235 auto BBInfo = StrPair.split(':');
236 // Get the function.
237 Function *F = M->getFunction(BBInfo.first);
238 if (!F) {
239 errs() << argv[0] << ": program doesn't contain a function named '"
240 << BBInfo.first << "'!\n";
241 return 1;
242 }
243 // Do not materialize this function.
244 GVs.insert(F);
245 // Get the basic block.
246 auto Res = llvm::find_if(*F, [&](const BasicBlock &BB) {
247 return BB.getName().equals(BBInfo.second);
248 });
249 if (Res == F->end()) {
250 errs() << argv[0] << ": function " << F->getName()
251 << " doesn't contain a basic block named '" << BBInfo.second
252 << "'!\n";
253 return 1;
254 }
255 BBs.push_back(&*Res);
256 }
257
Davide Italiano00347282016-11-09 21:30:33 +0000258 // Use *argv instead of argv[0] to work around a wrong GCC warning.
259 ExitOnError ExitOnErr(std::string(*argv) + ": error reading input: ");
Peter Collingbourne76c218e2016-11-09 17:49:19 +0000260
Keno Fischer1f6fa0f2017-04-06 20:51:40 +0000261 if (Recursive) {
262 std::vector<llvm::Function *> Workqueue;
263 for (GlobalValue *GV : GVs) {
264 if (auto *F = dyn_cast<Function>(GV)) {
265 Workqueue.push_back(F);
266 }
267 }
268 while (!Workqueue.empty()) {
269 Function *F = &*Workqueue.back();
270 Workqueue.pop_back();
271 ExitOnErr(F->materialize());
272 for (auto &BB : *F) {
273 for (auto &I : BB) {
274 auto *CI = dyn_cast<CallInst>(&I);
275 if (!CI)
276 continue;
277 Function *CF = CI->getCalledFunction();
278 if (!CF)
279 continue;
280 if (CF->isDeclaration() || GVs.count(CF))
281 continue;
282 GVs.insert(CF);
283 Workqueue.push_back(CF);
284 }
285 }
286 }
287 }
288
Peter Collingbourne76c218e2016-11-09 17:49:19 +0000289 auto Materialize = [&](GlobalValue &GV) { ExitOnErr(GV.materialize()); };
Rafael Espindola3bca2f22015-12-18 22:40:27 +0000290
291 // Materialize requisite global values.
292 if (!DeleteFn) {
293 for (size_t i = 0, e = GVs.size(); i != e; ++i)
294 Materialize(*GVs[i]);
295 } else {
Dan Gohmanbe2d4e72010-09-23 00:33:13 +0000296 // Deleting. Materialize every GV that's *not* in GVs.
297 SmallPtrSet<GlobalValue *, 8> GVSet(GVs.begin(), GVs.end());
Rafael Espindola82cb28e2014-05-08 19:30:17 +0000298 for (auto &F : *M) {
Rafael Espindola3bca2f22015-12-18 22:40:27 +0000299 if (!GVSet.count(&F))
300 Materialize(F);
Dan Gohman44f95332010-08-25 23:33:07 +0000301 }
302 }
303
Rafael Espindola17920c22016-01-15 19:00:20 +0000304 {
305 std::vector<GlobalValue *> Gvs(GVs.begin(), GVs.end());
306 legacy::PassManager Extract;
307 Extract.add(createGVExtractionPass(Gvs, DeleteFn));
308 Extract.run(*M);
309
310 // Now that we have all the GVs we want, mark the module as fully
311 // materialized.
312 // FIXME: should the GVExtractionPass handle this?
Peter Collingbourne76c218e2016-11-09 17:49:19 +0000313 ExitOnErr(M->materializeAll());
Rafael Espindola17920c22016-01-15 19:00:20 +0000314 }
315
Volkan Keles22b25642018-01-23 21:51:34 +0000316 // Extract the specified basic blocks from the module and erase the existing
317 // functions.
318 if (!ExtractBlocks.empty()) {
319 legacy::PassManager PM;
320 PM.add(createBlockExtractorPass(BBs, true));
321 PM.run(*M);
322 }
323
Chris Lattnerc48e1db2007-05-06 05:13:17 +0000324 // In addition to deleting all other functions, we also want to spiff it
325 // up a little bit. Do this now.
Chandler Carruth417c5c12015-02-13 10:01:29 +0000326 legacy::PassManager Passes;
Andrew Lenharthd245a8a2008-03-07 19:51:57 +0000327
Chris Lattnerc48e1db2007-05-06 05:13:17 +0000328 if (!DeleteFn)
329 Passes.add(createGlobalDCEPass()); // Delete unreachable globals
Devang Patelc1874b72010-07-01 19:58:05 +0000330 Passes.add(createStripDeadDebugInfoPass()); // Remove dead debug info
Chris Lattnerc48e1db2007-05-06 05:13:17 +0000331 Passes.add(createStripDeadPrototypesPass()); // Remove dead func decls
332
Rafael Espindola8c968622014-08-25 18:16:47 +0000333 std::error_code EC;
Reid Kleckner97ca9642017-09-23 01:03:17 +0000334 ToolOutputFile Out(OutputFilename, EC, sys::fs::F_None);
Rafael Espindola8c968622014-08-25 18:16:47 +0000335 if (EC) {
336 errs() << EC.message() << '\n';
Chris Lattner51a11322009-08-23 02:56:05 +0000337 return 1;
Chris Lattnerc48e1db2007-05-06 05:13:17 +0000338 }
339
Dan Gohmanec080462009-09-11 20:46:33 +0000340 if (OutputAssembly)
Duncan P. N. Exon Smithe005d712015-04-15 00:34:24 +0000341 Passes.add(
Duncan P. N. Exon Smith8d61ee92015-04-15 03:14:06 +0000342 createPrintModulePass(Out.os(), "", PreserveAssemblyUseListOrder));
343 else if (Force || !CheckBitcodeOutputToConsole(Out.os(), true))
344 Passes.add(createBitcodeWriterPass(Out.os(), PreserveBitcodeUseListOrder));
Dan Gohmanbaa26392009-08-25 15:34:52 +0000345
Chris Lattnerc48e1db2007-05-06 05:13:17 +0000346 Passes.run(*M.get());
347
Dan Gohman2df95042010-08-20 01:12:13 +0000348 // Declare success.
349 Out.keep();
350
Chris Lattnerc48e1db2007-05-06 05:13:17 +0000351 return 0;
Chris Lattner579d9142002-05-22 20:27:00 +0000352}