main.cpp 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. //===-- examples/clang-interpreter/main.cpp - Clang C Interpreter Example -===//
  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. #include "clang/CodeGen/CodeGenAction.h"
  10. #include "clang/Basic/DiagnosticOptions.h"
  11. #include "clang/Driver/Compilation.h"
  12. #include "clang/Driver/Driver.h"
  13. #include "clang/Driver/Tool.h"
  14. #include "clang/Frontend/CompilerInstance.h"
  15. #include "clang/Frontend/CompilerInvocation.h"
  16. #include "clang/Frontend/FrontendDiagnostic.h"
  17. #include "clang/Frontend/TextDiagnosticPrinter.h"
  18. #include "llvm/ADT/OwningPtr.h"
  19. #include "llvm/ADT/SmallString.h"
  20. #include "llvm/ExecutionEngine/ExecutionEngine.h"
  21. #include "llvm/ExecutionEngine/JIT.h"
  22. #include "llvm/IR/Module.h"
  23. #include "llvm/Support/Host.h"
  24. #include "llvm/Support/ManagedStatic.h"
  25. #include "llvm/Support/Path.h"
  26. #include "llvm/Support/TargetSelect.h"
  27. #include "llvm/Support/raw_ostream.h"
  28. using namespace clang;
  29. using namespace clang::driver;
  30. // This function isn't referenced outside its translation unit, but it
  31. // can't use the "static" keyword because its address is used for
  32. // GetMainExecutable (since some platforms don't support taking the
  33. // address of main, and some platforms can't implement GetMainExecutable
  34. // without being given the address of a function in the main executable).
  35. llvm::sys::Path GetExecutablePath(const char *Argv0) {
  36. // This just needs to be some symbol in the binary; C++ doesn't
  37. // allow taking the address of ::main however.
  38. void *MainAddr = (void*) (intptr_t) GetExecutablePath;
  39. return llvm::sys::Path::GetMainExecutable(Argv0, MainAddr);
  40. }
  41. static int Execute(llvm::Module *Mod, char * const *envp) {
  42. llvm::InitializeNativeTarget();
  43. std::string Error;
  44. OwningPtr<llvm::ExecutionEngine> EE(
  45. llvm::ExecutionEngine::createJIT(Mod, &Error));
  46. if (!EE) {
  47. llvm::errs() << "unable to make execution engine: " << Error << "\n";
  48. return 255;
  49. }
  50. llvm::Function *EntryFn = Mod->getFunction("main");
  51. if (!EntryFn) {
  52. llvm::errs() << "'main' function not found in module.\n";
  53. return 255;
  54. }
  55. // FIXME: Support passing arguments.
  56. std::vector<std::string> Args;
  57. Args.push_back(Mod->getModuleIdentifier());
  58. return EE->runFunctionAsMain(EntryFn, Args, envp);
  59. }
  60. int main(int argc, const char **argv, char * const *envp) {
  61. void *MainAddr = (void*) (intptr_t) GetExecutablePath;
  62. llvm::sys::Path Path = GetExecutablePath(argv[0]);
  63. IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
  64. TextDiagnosticPrinter *DiagClient =
  65. new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts);
  66. IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
  67. DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
  68. Driver TheDriver(Path.str(), llvm::sys::getDefaultTargetTriple(),
  69. "a.out", Diags);
  70. TheDriver.setTitle("clang interpreter");
  71. // FIXME: This is a hack to try to force the driver to do something we can
  72. // recognize. We need to extend the driver library to support this use model
  73. // (basically, exactly one input, and the operation mode is hard wired).
  74. SmallVector<const char *, 16> Args(argv, argv + argc);
  75. Args.push_back("-fsyntax-only");
  76. OwningPtr<Compilation> C(TheDriver.BuildCompilation(Args));
  77. if (!C)
  78. return 0;
  79. // FIXME: This is copied from ASTUnit.cpp; simplify and eliminate.
  80. // We expect to get back exactly one command job, if we didn't something
  81. // failed. Extract that job from the compilation.
  82. const driver::JobList &Jobs = C->getJobs();
  83. if (Jobs.size() != 1 || !isa<driver::Command>(*Jobs.begin())) {
  84. SmallString<256> Msg;
  85. llvm::raw_svector_ostream OS(Msg);
  86. C->PrintJob(OS, C->getJobs(), "; ", true);
  87. Diags.Report(diag::err_fe_expected_compiler_job) << OS.str();
  88. return 1;
  89. }
  90. const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
  91. if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
  92. Diags.Report(diag::err_fe_expected_clang_command);
  93. return 1;
  94. }
  95. // Initialize a compiler invocation object from the clang (-cc1) arguments.
  96. const driver::ArgStringList &CCArgs = Cmd->getArguments();
  97. OwningPtr<CompilerInvocation> CI(new CompilerInvocation);
  98. CompilerInvocation::CreateFromArgs(*CI,
  99. const_cast<const char **>(CCArgs.data()),
  100. const_cast<const char **>(CCArgs.data()) +
  101. CCArgs.size(),
  102. Diags);
  103. // Show the invocation, with -v.
  104. if (CI->getHeaderSearchOpts().Verbose) {
  105. llvm::errs() << "clang invocation:\n";
  106. C->PrintJob(llvm::errs(), C->getJobs(), "\n", true);
  107. llvm::errs() << "\n";
  108. }
  109. // FIXME: This is copied from cc1_main.cpp; simplify and eliminate.
  110. // Create a compiler instance to handle the actual work.
  111. CompilerInstance Clang;
  112. Clang.setInvocation(CI.take());
  113. // Create the compilers actual diagnostics engine.
  114. Clang.createDiagnostics(int(CCArgs.size()),const_cast<char**>(CCArgs.data()));
  115. if (!Clang.hasDiagnostics())
  116. return 1;
  117. // Infer the builtin include path if unspecified.
  118. if (Clang.getHeaderSearchOpts().UseBuiltinIncludes &&
  119. Clang.getHeaderSearchOpts().ResourceDir.empty())
  120. Clang.getHeaderSearchOpts().ResourceDir =
  121. CompilerInvocation::GetResourcesPath(argv[0], MainAddr);
  122. // Create and execute the frontend to generate an LLVM bitcode module.
  123. OwningPtr<CodeGenAction> Act(new EmitLLVMOnlyAction());
  124. if (!Clang.ExecuteAction(*Act))
  125. return 1;
  126. int Res = 255;
  127. if (llvm::Module *Module = Act->takeModule())
  128. Res = Execute(Module, envp);
  129. // Shutdown.
  130. llvm::llvm_shutdown();
  131. return Res;
  132. }