1 //===- llvm-extract.cpp - LLVM function extraction utility ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This utility changes the input module to only contain a single function,
11 // which is primarily used for debugging transformations.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/SetVector.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/Bitcode/BitcodeWriterPass.h"
18 #include "llvm/IR/DataLayout.h"
19 #include "llvm/IR/IRPrintingPasses.h"
20 #include "llvm/IR/LLVMContext.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/IR/UseListOrder.h"
23 #include "llvm/IRReader/IRReader.h"
24 #include "llvm/IR/LegacyPassManager.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/FileSystem.h"
27 #include "llvm/Support/ManagedStatic.h"
28 #include "llvm/Support/PrettyStackTrace.h"
29 #include "llvm/Support/Regex.h"
30 #include "llvm/Support/Signals.h"
31 #include "llvm/Support/SourceMgr.h"
32 #include "llvm/Support/SystemUtils.h"
33 #include "llvm/Support/ToolOutputFile.h"
34 #include "llvm/Transforms/IPO.h"
38 // InputFilename - The filename to read from.
39 static cl::opt<std::string>
40 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
41 cl::init("-"), cl::value_desc("filename"));
43 static cl::opt<std::string>
44 OutputFilename("o", cl::desc("Specify output filename"),
45 cl::value_desc("filename"), cl::init("-"));
48 Force("f", cl::desc("Enable binary output on terminals"));
51 DeleteFn("delete", cl::desc("Delete specified Globals from Module"));
53 // ExtractFuncs - The functions to extract from the module.
54 static cl::list<std::string>
55 ExtractFuncs("func", cl::desc("Specify function to extract"),
56 cl::ZeroOrMore, cl::value_desc("function"));
58 // ExtractRegExpFuncs - The functions, matched via regular expression, to
59 // extract from the module.
60 static cl::list<std::string>
61 ExtractRegExpFuncs("rfunc", cl::desc("Specify function(s) to extract using a "
62 "regular expression"),
63 cl::ZeroOrMore, cl::value_desc("rfunction"));
65 // ExtractAlias - The alias to extract from the module.
66 static cl::list<std::string>
67 ExtractAliases("alias", cl::desc("Specify alias to extract"),
68 cl::ZeroOrMore, cl::value_desc("alias"));
71 // ExtractRegExpAliases - The aliases, matched via regular expression, to
72 // extract from the module.
73 static cl::list<std::string>
74 ExtractRegExpAliases("ralias", cl::desc("Specify alias(es) to extract using a "
75 "regular expression"),
76 cl::ZeroOrMore, cl::value_desc("ralias"));
78 // ExtractGlobals - The globals to extract from the module.
79 static cl::list<std::string>
80 ExtractGlobals("glob", cl::desc("Specify global to extract"),
81 cl::ZeroOrMore, cl::value_desc("global"));
83 // ExtractRegExpGlobals - The globals, matched via regular expression, to
84 // extract from the module...
85 static cl::list<std::string>
86 ExtractRegExpGlobals("rglob", cl::desc("Specify global(s) to extract using a "
87 "regular expression"),
88 cl::ZeroOrMore, cl::value_desc("rglobal"));
92 cl::desc("Write output as LLVM assembly"), cl::Hidden);
94 int main(int argc, char **argv) {
95 // Print a stack trace if we signal out.
96 sys::PrintStackTraceOnErrorSignal();
97 PrettyStackTraceProgram X(argc, argv);
99 LLVMContext &Context = getGlobalContext();
100 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
102 // Turn on -preserve-bc-uselistorder by default, but let the command-line
104 setPreserveBitcodeUseListOrder(true);
106 cl::ParseCommandLineOptions(argc, argv, "llvm extractor\n");
108 // Use lazy loading, since we only care about selected global values.
110 std::unique_ptr<Module> M = getLazyIRFileModule(InputFilename, Err, Context);
113 Err.print(argv[0], errs());
117 // Use SetVector to avoid duplicates.
118 SetVector<GlobalValue *> GVs;
120 // Figure out which aliases we should extract.
121 for (size_t i = 0, e = ExtractAliases.size(); i != e; ++i) {
122 GlobalAlias *GA = M->getNamedAlias(ExtractAliases[i]);
124 errs() << argv[0] << ": program doesn't contain alias named '"
125 << ExtractAliases[i] << "'!\n";
131 // Extract aliases via regular expression matching.
132 for (size_t i = 0, e = ExtractRegExpAliases.size(); i != e; ++i) {
134 Regex RegEx(ExtractRegExpAliases[i]);
135 if (!RegEx.isValid(Error)) {
136 errs() << argv[0] << ": '" << ExtractRegExpAliases[i] << "' "
137 "invalid regex: " << Error;
140 for (Module::alias_iterator GA = M->alias_begin(), E = M->alias_end();
142 if (RegEx.match(GA->getName())) {
148 errs() << argv[0] << ": program doesn't contain global named '"
149 << ExtractRegExpAliases[i] << "'!\n";
154 // Figure out which globals we should extract.
155 for (size_t i = 0, e = ExtractGlobals.size(); i != e; ++i) {
156 GlobalValue *GV = M->getNamedGlobal(ExtractGlobals[i]);
158 errs() << argv[0] << ": program doesn't contain global named '"
159 << ExtractGlobals[i] << "'!\n";
165 // Extract globals via regular expression matching.
166 for (size_t i = 0, e = ExtractRegExpGlobals.size(); i != e; ++i) {
168 Regex RegEx(ExtractRegExpGlobals[i]);
169 if (!RegEx.isValid(Error)) {
170 errs() << argv[0] << ": '" << ExtractRegExpGlobals[i] << "' "
171 "invalid regex: " << Error;
174 for (auto &GV : M->globals()) {
175 if (RegEx.match(GV.getName())) {
181 errs() << argv[0] << ": program doesn't contain global named '"
182 << ExtractRegExpGlobals[i] << "'!\n";
187 // Figure out which functions we should extract.
188 for (size_t i = 0, e = ExtractFuncs.size(); i != e; ++i) {
189 GlobalValue *GV = M->getFunction(ExtractFuncs[i]);
191 errs() << argv[0] << ": program doesn't contain function named '"
192 << ExtractFuncs[i] << "'!\n";
197 // Extract functions via regular expression matching.
198 for (size_t i = 0, e = ExtractRegExpFuncs.size(); i != e; ++i) {
200 StringRef RegExStr = ExtractRegExpFuncs[i];
201 Regex RegEx(RegExStr);
202 if (!RegEx.isValid(Error)) {
203 errs() << argv[0] << ": '" << ExtractRegExpFuncs[i] << "' "
204 "invalid regex: " << Error;
207 for (Module::iterator F = M->begin(), E = M->end(); F != E;
209 if (RegEx.match(F->getName())) {
215 errs() << argv[0] << ": program doesn't contain global named '"
216 << ExtractRegExpFuncs[i] << "'!\n";
221 // Materialize requisite global values.
223 for (size_t i = 0, e = GVs.size(); i != e; ++i) {
224 GlobalValue *GV = GVs[i];
225 if (std::error_code EC = GV->materialize()) {
226 errs() << argv[0] << ": error reading input: " << EC.message() << "\n";
231 // Deleting. Materialize every GV that's *not* in GVs.
232 SmallPtrSet<GlobalValue *, 8> GVSet(GVs.begin(), GVs.end());
233 for (auto &G : M->globals()) {
234 if (!GVSet.count(&G)) {
235 if (std::error_code EC = G.materialize()) {
236 errs() << argv[0] << ": error reading input: " << EC.message()
243 if (!GVSet.count(&F)) {
244 if (std::error_code EC = F.materialize()) {
245 errs() << argv[0] << ": error reading input: " << EC.message()
253 // In addition to deleting all other functions, we also want to spiff it
254 // up a little bit. Do this now.
255 legacy::PassManager Passes;
257 std::vector<GlobalValue*> Gvs(GVs.begin(), GVs.end());
259 Passes.add(createGVExtractionPass(Gvs, DeleteFn));
261 Passes.add(createGlobalDCEPass()); // Delete unreachable globals
262 Passes.add(createStripDeadDebugInfoPass()); // Remove dead debug info
263 Passes.add(createStripDeadPrototypesPass()); // Remove dead func decls
266 tool_output_file Out(OutputFilename, EC, sys::fs::F_None);
268 errs() << EC.message() << '\n';
273 Passes.add(createPrintModulePass(Out.os()));
274 else if (Force || !CheckBitcodeOutputToConsole(Out.os(), true))
276 createBitcodeWriterPass(Out.os(), shouldPreserveBitcodeUseListOrder()));
278 Passes.run(*M.get());