llvm-extract.cpp 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. //===- llvm-extract.cpp - LLVM function extraction utility ----------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This utility changes the input module to only contain a single function,
  11. // which is primarily used for debugging transformations.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/ADT/SetVector.h"
  15. #include "llvm/ADT/SmallPtrSet.h"
  16. #include "llvm/Bitcode/BitcodeWriterPass.h"
  17. #include "llvm/IR/DataLayout.h"
  18. #include "llvm/IR/IRPrintingPasses.h"
  19. #include "llvm/IR/LLVMContext.h"
  20. #include "llvm/IR/Module.h"
  21. #include "llvm/IRReader/IRReader.h"
  22. #include "llvm/IR/LegacyPassManager.h"
  23. #include "llvm/Support/CommandLine.h"
  24. #include "llvm/Support/Error.h"
  25. #include "llvm/Support/FileSystem.h"
  26. #include "llvm/Support/ManagedStatic.h"
  27. #include "llvm/Support/PrettyStackTrace.h"
  28. #include "llvm/Support/Regex.h"
  29. #include "llvm/Support/Signals.h"
  30. #include "llvm/Support/SourceMgr.h"
  31. #include "llvm/Support/SystemUtils.h"
  32. #include "llvm/Support/ToolOutputFile.h"
  33. #include "llvm/Transforms/IPO.h"
  34. #include <memory>
  35. using namespace llvm;
  36. // InputFilename - The filename to read from.
  37. static cl::opt<std::string>
  38. InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
  39. cl::init("-"), cl::value_desc("filename"));
  40. static cl::opt<std::string>
  41. OutputFilename("o", cl::desc("Specify output filename"),
  42. cl::value_desc("filename"), cl::init("-"));
  43. static cl::opt<bool>
  44. Force("f", cl::desc("Enable binary output on terminals"));
  45. static cl::opt<bool>
  46. DeleteFn("delete", cl::desc("Delete specified Globals from Module"));
  47. // ExtractFuncs - The functions to extract from the module.
  48. static cl::list<std::string>
  49. ExtractFuncs("func", cl::desc("Specify function to extract"),
  50. cl::ZeroOrMore, cl::value_desc("function"));
  51. // ExtractRegExpFuncs - The functions, matched via regular expression, to
  52. // extract from the module.
  53. static cl::list<std::string>
  54. ExtractRegExpFuncs("rfunc", cl::desc("Specify function(s) to extract using a "
  55. "regular expression"),
  56. cl::ZeroOrMore, cl::value_desc("rfunction"));
  57. // ExtractAlias - The alias to extract from the module.
  58. static cl::list<std::string>
  59. ExtractAliases("alias", cl::desc("Specify alias to extract"),
  60. cl::ZeroOrMore, cl::value_desc("alias"));
  61. // ExtractRegExpAliases - The aliases, matched via regular expression, to
  62. // extract from the module.
  63. static cl::list<std::string>
  64. ExtractRegExpAliases("ralias", cl::desc("Specify alias(es) to extract using a "
  65. "regular expression"),
  66. cl::ZeroOrMore, cl::value_desc("ralias"));
  67. // ExtractGlobals - The globals to extract from the module.
  68. static cl::list<std::string>
  69. ExtractGlobals("glob", cl::desc("Specify global to extract"),
  70. cl::ZeroOrMore, cl::value_desc("global"));
  71. // ExtractRegExpGlobals - The globals, matched via regular expression, to
  72. // extract from the module...
  73. static cl::list<std::string>
  74. ExtractRegExpGlobals("rglob", cl::desc("Specify global(s) to extract using a "
  75. "regular expression"),
  76. cl::ZeroOrMore, cl::value_desc("rglobal"));
  77. static cl::opt<bool>
  78. OutputAssembly("S",
  79. cl::desc("Write output as LLVM assembly"), cl::Hidden);
  80. static cl::opt<bool> PreserveBitcodeUseListOrder(
  81. "preserve-bc-uselistorder",
  82. cl::desc("Preserve use-list order when writing LLVM bitcode."),
  83. cl::init(true), cl::Hidden);
  84. static cl::opt<bool> PreserveAssemblyUseListOrder(
  85. "preserve-ll-uselistorder",
  86. cl::desc("Preserve use-list order when writing LLVM assembly."),
  87. cl::init(false), cl::Hidden);
  88. int main(int argc, char **argv) {
  89. // Print a stack trace if we signal out.
  90. sys::PrintStackTraceOnErrorSignal(argv[0]);
  91. PrettyStackTraceProgram X(argc, argv);
  92. LLVMContext Context;
  93. llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
  94. cl::ParseCommandLineOptions(argc, argv, "llvm extractor\n");
  95. // Use lazy loading, since we only care about selected global values.
  96. SMDiagnostic Err;
  97. std::unique_ptr<Module> M = getLazyIRFileModule(InputFilename, Err, Context);
  98. if (!M.get()) {
  99. Err.print(argv[0], errs());
  100. return 1;
  101. }
  102. // Use SetVector to avoid duplicates.
  103. SetVector<GlobalValue *> GVs;
  104. // Figure out which aliases we should extract.
  105. for (size_t i = 0, e = ExtractAliases.size(); i != e; ++i) {
  106. GlobalAlias *GA = M->getNamedAlias(ExtractAliases[i]);
  107. if (!GA) {
  108. errs() << argv[0] << ": program doesn't contain alias named '"
  109. << ExtractAliases[i] << "'!\n";
  110. return 1;
  111. }
  112. GVs.insert(GA);
  113. }
  114. // Extract aliases via regular expression matching.
  115. for (size_t i = 0, e = ExtractRegExpAliases.size(); i != e; ++i) {
  116. std::string Error;
  117. Regex RegEx(ExtractRegExpAliases[i]);
  118. if (!RegEx.isValid(Error)) {
  119. errs() << argv[0] << ": '" << ExtractRegExpAliases[i] << "' "
  120. "invalid regex: " << Error;
  121. }
  122. bool match = false;
  123. for (Module::alias_iterator GA = M->alias_begin(), E = M->alias_end();
  124. GA != E; GA++) {
  125. if (RegEx.match(GA->getName())) {
  126. GVs.insert(&*GA);
  127. match = true;
  128. }
  129. }
  130. if (!match) {
  131. errs() << argv[0] << ": program doesn't contain global named '"
  132. << ExtractRegExpAliases[i] << "'!\n";
  133. return 1;
  134. }
  135. }
  136. // Figure out which globals we should extract.
  137. for (size_t i = 0, e = ExtractGlobals.size(); i != e; ++i) {
  138. GlobalValue *GV = M->getNamedGlobal(ExtractGlobals[i]);
  139. if (!GV) {
  140. errs() << argv[0] << ": program doesn't contain global named '"
  141. << ExtractGlobals[i] << "'!\n";
  142. return 1;
  143. }
  144. GVs.insert(GV);
  145. }
  146. // Extract globals via regular expression matching.
  147. for (size_t i = 0, e = ExtractRegExpGlobals.size(); i != e; ++i) {
  148. std::string Error;
  149. Regex RegEx(ExtractRegExpGlobals[i]);
  150. if (!RegEx.isValid(Error)) {
  151. errs() << argv[0] << ": '" << ExtractRegExpGlobals[i] << "' "
  152. "invalid regex: " << Error;
  153. }
  154. bool match = false;
  155. for (auto &GV : M->globals()) {
  156. if (RegEx.match(GV.getName())) {
  157. GVs.insert(&GV);
  158. match = true;
  159. }
  160. }
  161. if (!match) {
  162. errs() << argv[0] << ": program doesn't contain global named '"
  163. << ExtractRegExpGlobals[i] << "'!\n";
  164. return 1;
  165. }
  166. }
  167. // Figure out which functions we should extract.
  168. for (size_t i = 0, e = ExtractFuncs.size(); i != e; ++i) {
  169. GlobalValue *GV = M->getFunction(ExtractFuncs[i]);
  170. if (!GV) {
  171. errs() << argv[0] << ": program doesn't contain function named '"
  172. << ExtractFuncs[i] << "'!\n";
  173. return 1;
  174. }
  175. GVs.insert(GV);
  176. }
  177. // Extract functions via regular expression matching.
  178. for (size_t i = 0, e = ExtractRegExpFuncs.size(); i != e; ++i) {
  179. std::string Error;
  180. StringRef RegExStr = ExtractRegExpFuncs[i];
  181. Regex RegEx(RegExStr);
  182. if (!RegEx.isValid(Error)) {
  183. errs() << argv[0] << ": '" << ExtractRegExpFuncs[i] << "' "
  184. "invalid regex: " << Error;
  185. }
  186. bool match = false;
  187. for (Module::iterator F = M->begin(), E = M->end(); F != E;
  188. F++) {
  189. if (RegEx.match(F->getName())) {
  190. GVs.insert(&*F);
  191. match = true;
  192. }
  193. }
  194. if (!match) {
  195. errs() << argv[0] << ": program doesn't contain global named '"
  196. << ExtractRegExpFuncs[i] << "'!\n";
  197. return 1;
  198. }
  199. }
  200. ExitOnError ExitOnErr(std::string(argv[0]) + ": error reading input: ");
  201. auto Materialize = [&](GlobalValue &GV) { ExitOnErr(GV.materialize()); };
  202. // Materialize requisite global values.
  203. if (!DeleteFn) {
  204. for (size_t i = 0, e = GVs.size(); i != e; ++i)
  205. Materialize(*GVs[i]);
  206. } else {
  207. // Deleting. Materialize every GV that's *not* in GVs.
  208. SmallPtrSet<GlobalValue *, 8> GVSet(GVs.begin(), GVs.end());
  209. for (auto &F : *M) {
  210. if (!GVSet.count(&F))
  211. Materialize(F);
  212. }
  213. }
  214. {
  215. std::vector<GlobalValue *> Gvs(GVs.begin(), GVs.end());
  216. legacy::PassManager Extract;
  217. Extract.add(createGVExtractionPass(Gvs, DeleteFn));
  218. Extract.run(*M);
  219. // Now that we have all the GVs we want, mark the module as fully
  220. // materialized.
  221. // FIXME: should the GVExtractionPass handle this?
  222. ExitOnErr(M->materializeAll());
  223. }
  224. // In addition to deleting all other functions, we also want to spiff it
  225. // up a little bit. Do this now.
  226. legacy::PassManager Passes;
  227. if (!DeleteFn)
  228. Passes.add(createGlobalDCEPass()); // Delete unreachable globals
  229. Passes.add(createStripDeadDebugInfoPass()); // Remove dead debug info
  230. Passes.add(createStripDeadPrototypesPass()); // Remove dead func decls
  231. std::error_code EC;
  232. tool_output_file Out(OutputFilename, EC, sys::fs::F_None);
  233. if (EC) {
  234. errs() << EC.message() << '\n';
  235. return 1;
  236. }
  237. if (OutputAssembly)
  238. Passes.add(
  239. createPrintModulePass(Out.os(), "", PreserveAssemblyUseListOrder));
  240. else if (Force || !CheckBitcodeOutputToConsole(Out.os(), true))
  241. Passes.add(createBitcodeWriterPass(Out.os(), PreserveBitcodeUseListOrder));
  242. Passes.run(*M.get());
  243. // Declare success.
  244. Out.keep();
  245. return 0;
  246. }