blob: 835a5a90ad179123e1a93cbb6e1b11401023f387 [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"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000029#include "llvm/Support/Host.h"
30#include "llvm/Support/Path.h"
Daniel Dunbare2246282010-02-25 08:49:05 +000031#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
Eli Friedman97ab3ac2010-11-24 00:32:51 +000077 llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
78 Diagnostic Diags(DiagID, DiagClient);
Peter Collingbournefa9fe0c2010-07-24 17:59:51 +000079 Driver TheDriver(Path.str(), llvm::sys::getHostTriple(),
Daniel Dunbar5d93ed32010-04-01 18:21:41 +000080 "a.out", /*IsProduction=*/false, /*CXXIsProduction=*/false,
81 Diags);
Daniel Dunbare2246282010-02-25 08:49:05 +000082 TheDriver.setTitle("clang interpreter");
83
84 // FIXME: This is a hack to try to force the driver to do something we can
85 // recognize. We need to extend the driver library to support this use model
86 // (basically, exactly one input, and the operation mode is hard wired).
87 llvm::SmallVector<const char *, 16> Args(argv, argv + argc);
88 Args.push_back("-fsyntax-only");
89 llvm::OwningPtr<Compilation> C(TheDriver.BuildCompilation(Args.size(),
90 Args.data()));
91 if (!C)
92 return 0;
93
94 // FIXME: This is copied from ASTUnit.cpp; simplify and eliminate.
95
96 // We expect to get back exactly one command job, if we didn't something
97 // failed. Extract that job from the compilation.
98 const driver::JobList &Jobs = C->getJobs();
99 if (Jobs.size() != 1 || !isa<driver::Command>(Jobs.begin())) {
100 llvm::SmallString<256> Msg;
101 llvm::raw_svector_ostream OS(Msg);
102 C->PrintJob(OS, C->getJobs(), "; ", true);
103 Diags.Report(diag::err_fe_expected_compiler_job) << OS.str();
104 return 1;
105 }
106
107 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
108 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
109 Diags.Report(diag::err_fe_expected_clang_command);
110 return 1;
111 }
112
113 // Initialize a compiler invocation object from the clang (-cc1) arguments.
114 const driver::ArgStringList &CCArgs = Cmd->getArguments();
115 llvm::OwningPtr<CompilerInvocation> CI(new CompilerInvocation);
Benjamin Kramer9e8635a2010-04-20 11:50:39 +0000116 CompilerInvocation::CreateFromArgs(*CI,
117 const_cast<const char **>(CCArgs.data()),
118 const_cast<const char **>(CCArgs.data()) +
119 CCArgs.size(),
Benjamin Kramera4f0a802010-04-20 11:55:38 +0000120 Diags);
Daniel Dunbare2246282010-02-25 08:49:05 +0000121
122 // Show the invocation, with -v.
123 if (CI->getHeaderSearchOpts().Verbose) {
124 llvm::errs() << "clang invocation:\n";
125 C->PrintJob(llvm::errs(), C->getJobs(), "\n", true);
126 llvm::errs() << "\n";
127 }
128
129 // FIXME: This is copied from cc1_main.cpp; simplify and eliminate.
130
131 // Create a compiler instance to handle the actual work.
132 CompilerInstance Clang;
133 Clang.setLLVMContext(new llvm::LLVMContext);
134 Clang.setInvocation(CI.take());
135
136 // Create the compilers actual diagnostics engine.
Benjamin Kramera4f0a802010-04-20 11:55:38 +0000137 Clang.createDiagnostics(int(CCArgs.size()),const_cast<char**>(CCArgs.data()));
Daniel Dunbare2246282010-02-25 08:49:05 +0000138 if (!Clang.hasDiagnostics())
139 return 1;
140
141 // Infer the builtin include path if unspecified.
142 if (Clang.getHeaderSearchOpts().UseBuiltinIncludes &&
143 Clang.getHeaderSearchOpts().ResourceDir.empty())
144 Clang.getHeaderSearchOpts().ResourceDir =
145 CompilerInvocation::GetResourcesPath(argv[0], MainAddr);
146
147 // Create and execute the frontend to generate an LLVM bitcode module.
148 llvm::OwningPtr<CodeGenAction> Act(new EmitLLVMOnlyAction());
149 if (!Clang.ExecuteAction(*Act))
150 return 1;
151
152 int Res = 255;
153 if (llvm::Module *Module = Act->takeModule())
154 Res = Execute(Module, envp);
155
156 // Shutdown.
157
158 llvm::llvm_shutdown();
159
160 return Res;
161}