1 //===- LLVMPrintFunctionNames.cpp 2 //---------------------------------------------===// 3 // 4 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 5 // See https://llvm.org/LICENSE.txt for license information. 6 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // Example clang plugin which simply prints the names of all the functions 11 // within the generated LLVM code. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "clang/AST/AST.h" 16 #include "clang/AST/ASTConsumer.h" 17 #include "clang/AST/RecursiveASTVisitor.h" 18 #include "clang/Frontend/CompilerInstance.h" 19 #include "clang/Frontend/FrontendPluginRegistry.h" 20 #include "clang/Sema/Sema.h" 21 #include "llvm/IR/PassManager.h" 22 #include "llvm/Passes/OptimizationLevel.h" 23 #include "llvm/Passes/PassBuilder.h" 24 #include "llvm/Support/raw_ostream.h" 25 using namespace clang; 26 27 namespace { 28 29 class PrintPass final : public llvm::AnalysisInfoMixin<PrintPass> { 30 friend struct llvm::AnalysisInfoMixin<PrintPass>; 31 32 public: 33 using Result = llvm::PreservedAnalyses; 34 35 Result run(llvm::Module &M, llvm::ModuleAnalysisManager &MAM) { 36 for (auto &F : M) 37 llvm::outs() << "[PrintPass] Found function: " << F.getName() << "\n"; 38 return llvm::PreservedAnalyses::all(); 39 } 40 static bool isRequired() { return true; } 41 }; 42 43 void PrintCallback(llvm::PassBuilder &PB) { 44 PB.registerPipelineStartEPCallback( 45 [](llvm::ModulePassManager &MPM, llvm::OptimizationLevel) { 46 MPM.addPass(PrintPass()); 47 }); 48 } 49 50 class LLVMPrintFunctionsConsumer : public ASTConsumer { 51 public: 52 LLVMPrintFunctionsConsumer(CompilerInstance &Instance) { 53 Instance.getCodeGenOpts().PassBuilderCallbacks.push_back(PrintCallback); 54 } 55 }; 56 57 class LLVMPrintFunctionNamesAction : public PluginASTAction { 58 protected: 59 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI, 60 llvm::StringRef) override { 61 return std::make_unique<LLVMPrintFunctionsConsumer>(CI); 62 } 63 bool ParseArgs(const CompilerInstance &, 64 const std::vector<std::string> &) override { 65 return true; 66 } 67 PluginASTAction::ActionType getActionType() override { 68 return AddBeforeMainAction; 69 } 70 }; 71 72 } // namespace 73 74 static FrontendPluginRegistry::Add<LLVMPrintFunctionNamesAction> 75 X("llvm-print-fns", "print function names, llvm level"); 76