clang.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*
  2. * llvm C frontend for perf. Support dynamically compile C file
  3. *
  4. * Inspired by clang example code:
  5. * http://llvm.org/svn/llvm-project/cfe/trunk/examples/clang-interpreter/main.cpp
  6. *
  7. * Copyright (C) 2016 Wang Nan <wangnan0@huawei.com>
  8. * Copyright (C) 2016 Huawei Inc.
  9. */
  10. #include "clang/CodeGen/CodeGenAction.h"
  11. #include "clang/Frontend/CompilerInvocation.h"
  12. #include "clang/Frontend/CompilerInstance.h"
  13. #include "clang/Frontend/TextDiagnosticPrinter.h"
  14. #include "clang/Tooling/Tooling.h"
  15. #include "llvm/IR/Module.h"
  16. #include "llvm/Option/Option.h"
  17. #include "llvm/Support/ManagedStatic.h"
  18. #include <memory>
  19. #include "clang.h"
  20. #include "clang-c.h"
  21. namespace perf {
  22. static std::unique_ptr<llvm::LLVMContext> LLVMCtx;
  23. using namespace clang;
  24. static vfs::InMemoryFileSystem *
  25. buildVFS(StringRef& Name, StringRef& Content)
  26. {
  27. vfs::InMemoryFileSystem *VFS = new vfs::InMemoryFileSystem(true);
  28. VFS->addFile(Twine(Name), 0, llvm::MemoryBuffer::getMemBuffer(Content));
  29. return VFS;
  30. }
  31. static CompilerInvocation *
  32. createCompilerInvocation(StringRef& Path, DiagnosticsEngine& Diags)
  33. {
  34. llvm::opt::ArgStringList CCArgs {
  35. "-cc1",
  36. "-triple", "bpf-pc-linux",
  37. "-fsyntax-only",
  38. "-ferror-limit", "19",
  39. "-fmessage-length", "127",
  40. "-O2",
  41. "-nostdsysteminc",
  42. "-nobuiltininc",
  43. "-vectorize-loops",
  44. "-vectorize-slp",
  45. "-Wno-unused-value",
  46. "-Wno-pointer-sign",
  47. "-x", "c"};
  48. CompilerInvocation *CI = tooling::newInvocation(&Diags, CCArgs);
  49. FrontendOptions& Opts = CI->getFrontendOpts();
  50. Opts.Inputs.clear();
  51. Opts.Inputs.emplace_back(Path, IK_C);
  52. return CI;
  53. }
  54. std::unique_ptr<llvm::Module>
  55. getModuleFromSource(StringRef Name, StringRef Content)
  56. {
  57. CompilerInstance Clang;
  58. Clang.createDiagnostics();
  59. IntrusiveRefCntPtr<vfs::FileSystem> VFS = buildVFS(Name, Content);
  60. Clang.setVirtualFileSystem(&*VFS);
  61. IntrusiveRefCntPtr<CompilerInvocation> CI =
  62. createCompilerInvocation(Name, Clang.getDiagnostics());
  63. Clang.setInvocation(&*CI);
  64. std::unique_ptr<CodeGenAction> Act(new EmitLLVMOnlyAction(&*LLVMCtx));
  65. if (!Clang.ExecuteAction(*Act))
  66. return std::unique_ptr<llvm::Module>(nullptr);
  67. return Act->takeModule();
  68. }
  69. }
  70. extern "C" {
  71. void perf_clang__init(void)
  72. {
  73. perf::LLVMCtx.reset(new llvm::LLVMContext());
  74. }
  75. void perf_clang__cleanup(void)
  76. {
  77. perf::LLVMCtx.reset(nullptr);
  78. llvm::llvm_shutdown();
  79. }
  80. }