blob: 1890848f3501bd43301947a5a7b88100916637a9 [file] [log] [blame]
Daniel Dunbare2246282010-02-25 08:49:05 +00001//===-- 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
Daniel Dunbar9b414d32010-06-15 17:48:49 +000010#include "clang/CodeGen/CodeGenAction.h"
Daniel Dunbare2246282010-02-25 08:49:05 +000011#include "clang/Driver/Compilation.h"
12#include "clang/Driver/Driver.h"
13#include "clang/Driver/Tool.h"
Daniel Dunbare2246282010-02-25 08:49:05 +000014#include "clang/Frontend/CompilerInvocation.h"
15#include "clang/Frontend/CompilerInstance.h"
16#include "clang/Frontend/DiagnosticOptions.h"
17#include "clang/Frontend/FrontendDiagnostic.h"
18#include "clang/Frontend/TextDiagnosticPrinter.h"
19
20#include "llvm/LLVMContext.h"
21#include "llvm/Module.h"
22#include "llvm/Config/config.h"
23#include "llvm/ADT/OwningPtr.h"
24#include "llvm/ADT/SmallString.h"
25#include "llvm/Config/config.h"
26#include "llvm/ExecutionEngine/ExecutionEngine.h"
27#include "llvm/Support/ManagedStatic.h"
28#include "llvm/Support/raw_ostream.h"
29#include "llvm/System/Host.h"
30#include "llvm/System/Path.h"
31#include "llvm/Target/TargetSelect.h"
32using namespace clang;
33using namespace clang::driver;
34
Dan Gohmanea1924e2010-11-17 17:23:53 +000035// This function isn't referenced outside its translation unit, but it
36// can't use the "static" keyword because its address is used for
37// GetMainExecutable (since some platforms don't support taking the
38// address of main, and some platforms can't implement GetMainExecutable
39// without being given the address of a function in the main executable).
Benjamin Krameraeed3da2010-10-30 17:32:40 +000040llvm::sys::Path GetExecutablePath(const char *Argv0) {
Daniel Dunbare2246282010-02-25 08:49:05 +000041 // This just needs to be some symbol in the binary; C++ doesn't
42 // allow taking the address of ::main however.
43 void *MainAddr = (void*) (intptr_t) GetExecutablePath;
44 return llvm::sys::Path::GetMainExecutable(Argv0, MainAddr);
45}
46
Dan Gohmanf1295622010-10-29 22:41:35 +000047static int Execute(llvm::Module *Mod, char * const *envp) {
Daniel Dunbare2246282010-02-25 08:49:05 +000048 llvm::InitializeNativeTarget();
49
50 std::string Error;
51 llvm::OwningPtr<llvm::ExecutionEngine> EE(
52 llvm::ExecutionEngine::createJIT(Mod, &Error));
53 if (!EE) {
54 llvm::errs() << "unable to make execution engine: " << Error << "\n";
55 return 255;
56 }
57
58 llvm::Function *EntryFn = Mod->getFunction("main");
59 if (!EntryFn) {
60 llvm::errs() << "'main' function not found in module.\n";
61 return 255;
62 }
63
64 // FIXME: Support passing arguments.
65 std::vector<std::string> Args;
66 Args.push_back(Mod->getModuleIdentifier());
67
68 return EE->runFunctionAsMain(EntryFn, Args, envp);
69}
70
71int main(int argc, const char **argv, char * const *envp) {
72 void *MainAddr = (void*) (intptr_t) GetExecutablePath;
73 llvm::sys::Path Path = GetExecutablePath(argv[0]);
Benjamin Kramer06b901b2010-08-26 13:48:56 +000074 TextDiagnosticPrinter *DiagClient =
75 new TextDiagnosticPrinter(llvm::errs(), DiagnosticOptions());
Daniel Dunbare2246282010-02-25 08:49:05 +000076
Benjamin Kramer06b901b2010-08-26 13:48:56 +000077 Diagnostic Diags(DiagClient);
Peter Collingbournefa9fe0c2010-07-24 17:59:51 +000078 Driver TheDriver(Path.str(), llvm::sys::getHostTriple(),
Daniel Dunbar5d93ed32010-04-01 18:21:41 +000079 "a.out", /*IsProduction=*/false, /*CXXIsProduction=*/false,
80 Diags);
Daniel Dunbare2246282010-02-25 08:49:05 +000081 TheDriver.setTitle("clang interpreter");
82
83 // FIXME: This is a hack to try to force the driver to do something we can
84 // recognize. We need to extend the driver library to support this use model
85 // (basically, exactly one input, and the operation mode is hard wired).
86 llvm::SmallVector<const char *, 16> Args(argv, argv + argc);
87 Args.push_back("-fsyntax-only");
88 llvm::OwningPtr<Compilation> C(TheDriver.BuildCompilation(Args.size(),
89 Args.data()));
90 if (!C)
91 return 0;
92
93 // FIXME: This is copied from ASTUnit.cpp; simplify and eliminate.
94
95 // We expect to get back exactly one command job, if we didn't something
96 // failed. Extract that job from the compilation.
97 const driver::JobList &Jobs = C->getJobs();
98 if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
99 llvm::SmallString<256> Msg;
100 llvm::raw_svector_ostream OS(Msg);
101 C->PrintJob(OS, C->getJobs(), "; ", true);
102 Diags.Report(diag::err_fe_expected_compiler_job) << OS.str();
103 return 1;
104 }
105
106 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
107 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
108 Diags.Report(diag::err_fe_expected_clang_command);
109 return 1;
110 }
111
112 // Initialize a compiler invocation object from the clang (-cc1) arguments.
113 const driver::ArgStringList &CCArgs = Cmd->getArguments();
114 llvm::OwningPtr<CompilerInvocation> CI(new CompilerInvocation);
Benjamin Kramer9e8635a2010-04-20 11:50:39 +0000115 CompilerInvocation::CreateFromArgs(*CI,
116 const_cast<const char **>(CCArgs.data()),
117 const_cast<const char **>(CCArgs.data()) +
118 CCArgs.size(),
Benjamin Kramera4f0a802010-04-20 11:55:38 +0000119 Diags);
Daniel Dunbare2246282010-02-25 08:49:05 +0000120
121 // Show the invocation, with -v.
122 if (CI->getHeaderSearchOpts().Verbose) {
123 llvm::errs() << "clang invocation:\n";
124 C->PrintJob(llvm::errs(), C->getJobs(), "\n", true);
125 llvm::errs() << "\n";
126 }
127
128 // FIXME: This is copied from cc1_main.cpp; simplify and eliminate.
129
130 // Create a compiler instance to handle the actual work.
131 CompilerInstance Clang;
132 Clang.setLLVMContext(new llvm::LLVMContext);
133 Clang.setInvocation(CI.take());
134
135 // Create the compilers actual diagnostics engine.
Benjamin Kramera4f0a802010-04-20 11:55:38 +0000136 Clang.createDiagnostics(int(CCArgs.size()),const_cast<char**>(CCArgs.data()));
Daniel Dunbare2246282010-02-25 08:49:05 +0000137 if (!Clang.hasDiagnostics())
138 return 1;
139
140 // Infer the builtin include path if unspecified.
141 if (Clang.getHeaderSearchOpts().UseBuiltinIncludes &&
142 Clang.getHeaderSearchOpts().ResourceDir.empty())
143 Clang.getHeaderSearchOpts().ResourceDir =
144 CompilerInvocation::GetResourcesPath(argv[0], MainAddr);
145
146 // Create and execute the frontend to generate an LLVM bitcode module.
147 llvm::OwningPtr<CodeGenAction> Act(new EmitLLVMOnlyAction());
148 if (!Clang.ExecuteAction(*Act))
149 return 1;
150
151 int Res = 255;
152 if (llvm::Module *Module = Act->takeModule())
153 Res = Execute(Module, envp);
154
155 // Shutdown.
156
157 llvm::llvm_shutdown();
158
159 return Res;
160}