llvm-extract.cpp 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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/IR/UseListOrder.h"
  22. #include "llvm/IRReader/IRReader.h"
  23. #include "llvm/IR/LegacyPassManager.h"
  24. #include "llvm/Support/CommandLine.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. int main(int argc, char **argv) {
  81. // Print a stack trace if we signal out.
  82. sys::PrintStackTraceOnErrorSignal();
  83. PrettyStackTraceProgram X(argc, argv);
  84. LLVMContext &Context = getGlobalContext();
  85. llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
  86. // Turn on -preserve-bc-uselistorder by default, but let the command-line
  87. // override it.
  88. setPreserveBitcodeUseListOrder(true);
  89. cl::ParseCommandLineOptions(argc, argv, "llvm extractor\n");
  90. // Use lazy loading, since we only care about selected global values.
  91. SMDiagnostic Err;
  92. std::unique_ptr<Module> M = getLazyIRFileModule(InputFilename, Err, Context);
  93. if (!M.get()) {
  94. Err.print(argv[0], errs());
  95. return 1;
  96. }
  97. // Use SetVector to avoid duplicates.
  98. SetVector<GlobalValue *> GVs;
  99. // Figure out which aliases we should extract.
  100. for (size_t i = 0, e = ExtractAliases.size(); i != e; ++i) {
  101. GlobalAlias *GA = M->getNamedAlias(ExtractAliases[i]);
  102. if (!GA) {
  103. errs() << argv[0] << ": program doesn't contain alias named '"
  104. << ExtractAliases[i] << "'!\n";
  105. return 1;
  106. }
  107. GVs.insert(GA);
  108. }
  109. // Extract aliases via regular expression matching.
  110. for (size_t i = 0, e = ExtractRegExpAliases.size(); i != e; ++i) {
  111. std::string Error;
  112. Regex RegEx(ExtractRegExpAliases[i]);
  113. if (!RegEx.isValid(Error)) {
  114. errs() << argv[0] << ": '" << ExtractRegExpAliases[i] << "' "
  115. "invalid regex: " << Error;
  116. }
  117. bool match = false;
  118. for (Module::alias_iterator GA = M->alias_begin(), E = M->alias_end();
  119. GA != E; GA++) {
  120. if (RegEx.match(GA->getName())) {
  121. GVs.insert(&*GA);
  122. match = true;
  123. }
  124. }
  125. if (!match) {
  126. errs() << argv[0] << ": program doesn't contain global named '"
  127. << ExtractRegExpAliases[i] << "'!\n";
  128. return 1;
  129. }
  130. }
  131. // Figure out which globals we should extract.
  132. for (size_t i = 0, e = ExtractGlobals.size(); i != e; ++i) {
  133. GlobalValue *GV = M->getNamedGlobal(ExtractGlobals[i]);
  134. if (!GV) {
  135. errs() << argv[0] << ": program doesn't contain global named '"
  136. << ExtractGlobals[i] << "'!\n";
  137. return 1;
  138. }
  139. GVs.insert(GV);
  140. }
  141. // Extract globals via regular expression matching.
  142. for (size_t i = 0, e = ExtractRegExpGlobals.size(); i != e; ++i) {
  143. std::string Error;
  144. Regex RegEx(ExtractRegExpGlobals[i]);
  145. if (!RegEx.isValid(Error)) {
  146. errs() << argv[0] << ": '" << ExtractRegExpGlobals[i] << "' "
  147. "invalid regex: " << Error;
  148. }
  149. bool match = false;
  150. for (auto &GV : M->globals()) {
  151. if (RegEx.match(GV.getName())) {
  152. GVs.insert(&GV);
  153. match = true;
  154. }
  155. }
  156. if (!match) {
  157. errs() << argv[0] << ": program doesn't contain global named '"
  158. << ExtractRegExpGlobals[i] << "'!\n";
  159. return 1;
  160. }
  161. }
  162. // Figure out which functions we should extract.
  163. for (size_t i = 0, e = ExtractFuncs.size(); i != e; ++i) {
  164. GlobalValue *GV = M->getFunction(ExtractFuncs[i]);
  165. if (!GV) {
  166. errs() << argv[0] << ": program doesn't contain function named '"
  167. << ExtractFuncs[i] << "'!\n";
  168. return 1;
  169. }
  170. GVs.insert(GV);
  171. }
  172. // Extract functions via regular expression matching.
  173. for (size_t i = 0, e = ExtractRegExpFuncs.size(); i != e; ++i) {
  174. std::string Error;
  175. StringRef RegExStr = ExtractRegExpFuncs[i];
  176. Regex RegEx(RegExStr);
  177. if (!RegEx.isValid(Error)) {
  178. errs() << argv[0] << ": '" << ExtractRegExpFuncs[i] << "' "
  179. "invalid regex: " << Error;
  180. }
  181. bool match = false;
  182. for (Module::iterator F = M->begin(), E = M->end(); F != E;
  183. F++) {
  184. if (RegEx.match(F->getName())) {
  185. GVs.insert(&*F);
  186. match = true;
  187. }
  188. }
  189. if (!match) {
  190. errs() << argv[0] << ": program doesn't contain global named '"
  191. << ExtractRegExpFuncs[i] << "'!\n";
  192. return 1;
  193. }
  194. }
  195. // Materialize requisite global values.
  196. if (!DeleteFn)
  197. for (size_t i = 0, e = GVs.size(); i != e; ++i) {
  198. GlobalValue *GV = GVs[i];
  199. if (std::error_code EC = GV->materialize()) {
  200. errs() << argv[0] << ": error reading input: " << EC.message() << "\n";
  201. return 1;
  202. }
  203. }
  204. else {
  205. // Deleting. Materialize every GV that's *not* in GVs.
  206. SmallPtrSet<GlobalValue *, 8> GVSet(GVs.begin(), GVs.end());
  207. for (auto &G : M->globals()) {
  208. if (!GVSet.count(&G)) {
  209. if (std::error_code EC = G.materialize()) {
  210. errs() << argv[0] << ": error reading input: " << EC.message()
  211. << "\n";
  212. return 1;
  213. }
  214. }
  215. }
  216. for (auto &F : *M) {
  217. if (!GVSet.count(&F)) {
  218. if (std::error_code EC = F.materialize()) {
  219. errs() << argv[0] << ": error reading input: " << EC.message()
  220. << "\n";
  221. return 1;
  222. }
  223. }
  224. }
  225. }
  226. // In addition to deleting all other functions, we also want to spiff it
  227. // up a little bit. Do this now.
  228. legacy::PassManager Passes;
  229. std::vector<GlobalValue*> Gvs(GVs.begin(), GVs.end());
  230. Passes.add(createGVExtractionPass(Gvs, DeleteFn));
  231. if (!DeleteFn)
  232. Passes.add(createGlobalDCEPass()); // Delete unreachable globals
  233. Passes.add(createStripDeadDebugInfoPass()); // Remove dead debug info
  234. Passes.add(createStripDeadPrototypesPass()); // Remove dead func decls
  235. std::error_code EC;
  236. tool_output_file Out(OutputFilename, EC, sys::fs::F_None);
  237. if (EC) {
  238. errs() << EC.message() << '\n';
  239. return 1;
  240. }
  241. if (OutputAssembly)
  242. Passes.add(createPrintModulePass(Out.os()));
  243. else if (Force || !CheckBitcodeOutputToConsole(Out.os(), true))
  244. Passes.add(
  245. createBitcodeWriterPass(Out.os(), shouldPreserveBitcodeUseListOrder()));
  246. Passes.run(*M.get());
  247. // Declare success.
  248. Out.keep();
  249. return 0;
  250. }