blob: 3d0d6409d90ec34da94b1d4f692ad95276a1610b [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"
Chandler Carruthe0c6e932012-12-04 09:37:22 +000011#include "clang/Basic/DiagnosticOptions.h"
Daniel Dunbare2246282010-02-25 08:49:05 +000012#include "clang/Driver/Compilation.h"
13#include "clang/Driver/Driver.h"
14#include "clang/Driver/Tool.h"
Daniel Dunbare2246282010-02-25 08:49:05 +000015#include "clang/Frontend/CompilerInstance.h"
Chandler Carruthe0c6e932012-12-04 09:37:22 +000016#include "clang/Frontend/CompilerInvocation.h"
Daniel Dunbare2246282010-02-25 08:49:05 +000017#include "clang/Frontend/FrontendDiagnostic.h"
18#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Dunbare2246282010-02-25 08:49:05 +000019#include "llvm/ADT/OwningPtr.h"
20#include "llvm/ADT/SmallString.h"
Daniel Dunbare2246282010-02-25 08:49:05 +000021#include "llvm/ExecutionEngine/ExecutionEngine.h"
Chandler Carruthe0c6e932012-12-04 09:37:22 +000022#include "llvm/ExecutionEngine/JIT.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000023#include "llvm/IR/Module.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000024#include "llvm/Support/Host.h"
Chandler Carruthe0c6e932012-12-04 09:37:22 +000025#include "llvm/Support/ManagedStatic.h"
Michael J. Spencer03013fa2010-11-29 18:12:39 +000026#include "llvm/Support/Path.h"
Evan Chenga6b40452011-08-24 18:09:14 +000027#include "llvm/Support/TargetSelect.h"
Chandler Carruthe0c6e932012-12-04 09:37:22 +000028#include "llvm/Support/raw_ostream.h"
Daniel Dunbare2246282010-02-25 08:49:05 +000029using namespace clang;
30using namespace clang::driver;
31
Dan Gohmanea1924e2010-11-17 17:23:53 +000032// This function isn't referenced outside its translation unit, but it
33// can't use the "static" keyword because its address is used for
34// GetMainExecutable (since some platforms don't support taking the
35// address of main, and some platforms can't implement GetMainExecutable
36// without being given the address of a function in the main executable).
Benjamin Krameraeed3da2010-10-30 17:32:40 +000037llvm::sys::Path GetExecutablePath(const char *Argv0) {
Daniel Dunbare2246282010-02-25 08:49:05 +000038 // This just needs to be some symbol in the binary; C++ doesn't
39 // allow taking the address of ::main however.
40 void *MainAddr = (void*) (intptr_t) GetExecutablePath;
41 return llvm::sys::Path::GetMainExecutable(Argv0, MainAddr);
42}
43
Dan Gohmanf1295622010-10-29 22:41:35 +000044static int Execute(llvm::Module *Mod, char * const *envp) {
Daniel Dunbare2246282010-02-25 08:49:05 +000045 llvm::InitializeNativeTarget();
46
47 std::string Error;
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +000048 OwningPtr<llvm::ExecutionEngine> EE(
Daniel Dunbare2246282010-02-25 08:49:05 +000049 llvm::ExecutionEngine::createJIT(Mod, &Error));
50 if (!EE) {
51 llvm::errs() << "unable to make execution engine: " << Error << "\n";
52 return 255;
53 }
54
55 llvm::Function *EntryFn = Mod->getFunction("main");
56 if (!EntryFn) {
57 llvm::errs() << "'main' function not found in module.\n";
58 return 255;
59 }
60
61 // FIXME: Support passing arguments.
62 std::vector<std::string> Args;
63 Args.push_back(Mod->getModuleIdentifier());
64
65 return EE->runFunctionAsMain(EntryFn, Args, envp);
66}
67
68int main(int argc, const char **argv, char * const *envp) {
69 void *MainAddr = (void*) (intptr_t) GetExecutablePath;
70 llvm::sys::Path Path = GetExecutablePath(argv[0]);
Douglas Gregor35d516c2012-10-23 22:36:49 +000071 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Benjamin Kramer06b901b2010-08-26 13:48:56 +000072 TextDiagnosticPrinter *DiagClient =
Douglas Gregor35d516c2012-10-23 22:36:49 +000073 new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts);
Daniel Dunbare2246282010-02-25 08:49:05 +000074
Dylan Noblesmithc93dc782012-02-20 14:00:23 +000075 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
Douglas Gregor35d516c2012-10-23 22:36:49 +000076 DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
Peter Collingbourne804381d2013-01-16 22:37:09 +000077 Driver TheDriver(Path.str(), llvm::sys::getProcessTriple(), "a.out", Diags);
Daniel Dunbare2246282010-02-25 08:49:05 +000078 TheDriver.setTitle("clang interpreter");
79
80 // FIXME: This is a hack to try to force the driver to do something we can
81 // recognize. We need to extend the driver library to support this use model
82 // (basically, exactly one input, and the operation mode is hard wired).
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000083 SmallVector<const char *, 16> Args(argv, argv + argc);
Daniel Dunbare2246282010-02-25 08:49:05 +000084 Args.push_back("-fsyntax-only");
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +000085 OwningPtr<Compilation> C(TheDriver.BuildCompilation(Args));
Daniel Dunbare2246282010-02-25 08:49:05 +000086 if (!C)
87 return 0;
88
89 // FIXME: This is copied from ASTUnit.cpp; simplify and eliminate.
90
91 // We expect to get back exactly one command job, if we didn't something
92 // failed. Extract that job from the compilation.
93 const driver::JobList &Jobs = C->getJobs();
Manuel Klimekc8b3e632011-05-23 18:25:41 +000094 if (Jobs.size() != 1 || !isa<driver::Command>(*Jobs.begin())) {
Dylan Noblesmith36d59272012-02-13 12:32:26 +000095 SmallString<256> Msg;
Daniel Dunbare2246282010-02-25 08:49:05 +000096 llvm::raw_svector_ostream OS(Msg);
97 C->PrintJob(OS, C->getJobs(), "; ", true);
98 Diags.Report(diag::err_fe_expected_compiler_job) << OS.str();
99 return 1;
100 }
101
102 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
103 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
104 Diags.Report(diag::err_fe_expected_clang_command);
105 return 1;
106 }
107
108 // Initialize a compiler invocation object from the clang (-cc1) arguments.
109 const driver::ArgStringList &CCArgs = Cmd->getArguments();
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +0000110 OwningPtr<CompilerInvocation> CI(new CompilerInvocation);
Benjamin Kramer9e8635a2010-04-20 11:50:39 +0000111 CompilerInvocation::CreateFromArgs(*CI,
112 const_cast<const char **>(CCArgs.data()),
113 const_cast<const char **>(CCArgs.data()) +
114 CCArgs.size(),
Benjamin Kramera4f0a802010-04-20 11:55:38 +0000115 Diags);
Daniel Dunbare2246282010-02-25 08:49:05 +0000116
117 // Show the invocation, with -v.
118 if (CI->getHeaderSearchOpts().Verbose) {
119 llvm::errs() << "clang invocation:\n";
120 C->PrintJob(llvm::errs(), C->getJobs(), "\n", true);
121 llvm::errs() << "\n";
122 }
123
124 // FIXME: This is copied from cc1_main.cpp; simplify and eliminate.
125
126 // Create a compiler instance to handle the actual work.
127 CompilerInstance Clang;
Daniel Dunbare2246282010-02-25 08:49:05 +0000128 Clang.setInvocation(CI.take());
129
130 // Create the compilers actual diagnostics engine.
Sean Silvad47afb92013-01-20 01:58:28 +0000131 Clang.createDiagnostics();
Daniel Dunbare2246282010-02-25 08:49:05 +0000132 if (!Clang.hasDiagnostics())
133 return 1;
134
135 // Infer the builtin include path if unspecified.
136 if (Clang.getHeaderSearchOpts().UseBuiltinIncludes &&
137 Clang.getHeaderSearchOpts().ResourceDir.empty())
138 Clang.getHeaderSearchOpts().ResourceDir =
139 CompilerInvocation::GetResourcesPath(argv[0], MainAddr);
140
141 // Create and execute the frontend to generate an LLVM bitcode module.
Dylan Noblesmith1e4c01b2012-02-13 12:32:21 +0000142 OwningPtr<CodeGenAction> Act(new EmitLLVMOnlyAction());
Daniel Dunbare2246282010-02-25 08:49:05 +0000143 if (!Clang.ExecuteAction(*Act))
144 return 1;
145
146 int Res = 255;
147 if (llvm::Module *Module = Act->takeModule())
148 Res = Execute(Module, envp);
149
150 // Shutdown.
151
152 llvm::llvm_shutdown();
153
154 return Res;
155}