blob: 25b9825a266f373db17a1a5481fa5db69e3f495e [file] [log] [blame]
Daniel Dunbar0076d942010-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 Dunbarc1b17292010-06-15 17:48:49 +000010#include "clang/CodeGen/CodeGenAction.h"
Chandler Carruth8675b4a2012-12-04 09:37:22 +000011#include "clang/Basic/DiagnosticOptions.h"
Daniel Dunbar0076d942010-02-25 08:49:05 +000012#include "clang/Driver/Compilation.h"
13#include "clang/Driver/Driver.h"
14#include "clang/Driver/Tool.h"
Daniel Dunbar0076d942010-02-25 08:49:05 +000015#include "clang/Frontend/CompilerInstance.h"
Chandler Carruth8675b4a2012-12-04 09:37:22 +000016#include "clang/Frontend/CompilerInvocation.h"
Daniel Dunbar0076d942010-02-25 08:49:05 +000017#include "clang/Frontend/FrontendDiagnostic.h"
18#include "clang/Frontend/TextDiagnosticPrinter.h"
Daniel Dunbar0076d942010-02-25 08:49:05 +000019#include "llvm/ADT/SmallString.h"
Daniel Dunbar0076d942010-02-25 08:49:05 +000020#include "llvm/ExecutionEngine/ExecutionEngine.h"
Rafael Espindolae89d2892014-07-24 17:13:09 +000021#include "llvm/ExecutionEngine/MCJIT.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000022#include "llvm/IR/Module.h"
Rafael Espindola9678d272013-06-26 05:03:40 +000023#include "llvm/Support/FileSystem.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000024#include "llvm/Support/Host.h"
Chandler Carruth8675b4a2012-12-04 09:37:22 +000025#include "llvm/Support/ManagedStatic.h"
Michael J. Spencer8aaf4992010-11-29 18:12:39 +000026#include "llvm/Support/Path.h"
Evan Cheng494eb062011-08-24 18:09:14 +000027#include "llvm/Support/TargetSelect.h"
Chandler Carruth8675b4a2012-12-04 09:37:22 +000028#include "llvm/Support/raw_ostream.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000029#include <memory>
Daniel Dunbar0076d942010-02-25 08:49:05 +000030using namespace clang;
31using namespace clang::driver;
32
Dan Gohmanff66a7c2010-11-17 17:23:53 +000033// This function isn't referenced outside its translation unit, but it
34// can't use the "static" keyword because its address is used for
35// GetMainExecutable (since some platforms don't support taking the
36// address of main, and some platforms can't implement GetMainExecutable
37// without being given the address of a function in the main executable).
Rafael Espindola9678d272013-06-26 05:03:40 +000038std::string GetExecutablePath(const char *Argv0) {
Daniel Dunbar0076d942010-02-25 08:49:05 +000039 // This just needs to be some symbol in the binary; C++ doesn't
40 // allow taking the address of ::main however.
41 void *MainAddr = (void*) (intptr_t) GetExecutablePath;
Rafael Espindola9678d272013-06-26 05:03:40 +000042 return llvm::sys::fs::getMainExecutable(Argv0, MainAddr);
Daniel Dunbar0076d942010-02-25 08:49:05 +000043}
44
Rafael Espindolafb3d5d12014-07-24 15:54:23 +000045static llvm::ExecutionEngine *createExecutionEngine(llvm::Module *M,
46 std::string *ErrorStr) {
47 llvm::EngineBuilder EB = llvm::EngineBuilder(M)
Eric Christopher36685342014-08-07 22:09:08 +000048 .setUseMCJIT(true)
Rafael Espindolafb3d5d12014-07-24 15:54:23 +000049 .setEngineKind(llvm::EngineKind::Either)
50 .setErrorStr(ErrorStr);
51 return EB.create();
52}
53
Dan Gohmanba768022010-10-29 22:41:35 +000054static int Execute(llvm::Module *Mod, char * const *envp) {
Alp Toker60c88cb2014-07-01 03:19:50 +000055 llvm::InitializeNativeTarget();
Rafael Espindolae89d2892014-07-24 17:13:09 +000056 llvm::InitializeNativeTargetAsmPrinter();
Daniel Dunbar0076d942010-02-25 08:49:05 +000057
58 std::string Error;
Rafael Espindolafb3d5d12014-07-24 15:54:23 +000059 std::unique_ptr<llvm::ExecutionEngine> EE(createExecutionEngine(Mod, &Error));
Daniel Dunbar0076d942010-02-25 08:49:05 +000060 if (!EE) {
61 llvm::errs() << "unable to make execution engine: " << Error << "\n";
62 return 255;
63 }
64
65 llvm::Function *EntryFn = Mod->getFunction("main");
66 if (!EntryFn) {
67 llvm::errs() << "'main' function not found in module.\n";
68 return 255;
69 }
70
71 // FIXME: Support passing arguments.
72 std::vector<std::string> Args;
73 Args.push_back(Mod->getModuleIdentifier());
74
Rafael Espindolae89d2892014-07-24 17:13:09 +000075 EE->finalizeObject();
Daniel Dunbar0076d942010-02-25 08:49:05 +000076 return EE->runFunctionAsMain(EntryFn, Args, envp);
77}
78
79int main(int argc, const char **argv, char * const *envp) {
80 void *MainAddr = (void*) (intptr_t) GetExecutablePath;
Rafael Espindola9678d272013-06-26 05:03:40 +000081 std::string Path = GetExecutablePath(argv[0]);
Douglas Gregorcdb4d692012-10-23 22:36:49 +000082 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
Benjamin Kramer1921fac2010-08-26 13:48:56 +000083 TextDiagnosticPrinter *DiagClient =
Douglas Gregorcdb4d692012-10-23 22:36:49 +000084 new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts);
Daniel Dunbar0076d942010-02-25 08:49:05 +000085
Dylan Noblesmithc95d8192012-02-20 14:00:23 +000086 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
Douglas Gregorcdb4d692012-10-23 22:36:49 +000087 DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
Rafael Espindola3175daa2014-07-24 20:47:42 +000088
89 // Use ELF on windows for now.
90 std::string TripleStr = llvm::sys::getProcessTriple();
91 llvm::Triple T(TripleStr);
92 if (T.isOSBinFormatCOFF())
93 T.setObjectFormat(llvm::Triple::ELF);
94
95 Driver TheDriver(Path, T.str(), Diags);
Daniel Dunbar0076d942010-02-25 08:49:05 +000096 TheDriver.setTitle("clang interpreter");
Alp Tokered412da2014-07-09 01:37:36 +000097 TheDriver.setCheckInputsExist(false);
Daniel Dunbar0076d942010-02-25 08:49:05 +000098
99 // FIXME: This is a hack to try to force the driver to do something we can
100 // recognize. We need to extend the driver library to support this use model
101 // (basically, exactly one input, and the operation mode is hard wired).
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000102 SmallVector<const char *, 16> Args(argv, argv + argc);
Daniel Dunbar0076d942010-02-25 08:49:05 +0000103 Args.push_back("-fsyntax-only");
Ahmed Charlesaf94d562014-03-09 11:34:25 +0000104 std::unique_ptr<Compilation> C(TheDriver.BuildCompilation(Args));
Daniel Dunbar0076d942010-02-25 08:49:05 +0000105 if (!C)
106 return 0;
107
108 // FIXME: This is copied from ASTUnit.cpp; simplify and eliminate.
109
110 // We expect to get back exactly one command job, if we didn't something
111 // failed. Extract that job from the compilation.
112 const driver::JobList &Jobs = C->getJobs();
Manuel Klimekb66b5ce2011-05-23 18:25:41 +0000113 if (Jobs.size() != 1 || !isa<driver::Command>(*Jobs.begin())) {
Dylan Noblesmithf1a13f22012-02-13 12:32:26 +0000114 SmallString<256> Msg;
Daniel Dunbar0076d942010-02-25 08:49:05 +0000115 llvm::raw_svector_ostream OS(Msg);
Hans Wennborgb212b342013-09-12 18:23:34 +0000116 Jobs.Print(OS, "; ", true);
Daniel Dunbar0076d942010-02-25 08:49:05 +0000117 Diags.Report(diag::err_fe_expected_compiler_job) << OS.str();
118 return 1;
119 }
120
121 const driver::Command *Cmd = cast<driver::Command>(*Jobs.begin());
122 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang") {
123 Diags.Report(diag::err_fe_expected_clang_command);
124 return 1;
125 }
126
127 // Initialize a compiler invocation object from the clang (-cc1) arguments.
128 const driver::ArgStringList &CCArgs = Cmd->getArguments();
Ahmed Charlesaf94d562014-03-09 11:34:25 +0000129 std::unique_ptr<CompilerInvocation> CI(new CompilerInvocation);
Benjamin Kramer25d3d782010-04-20 11:50:39 +0000130 CompilerInvocation::CreateFromArgs(*CI,
131 const_cast<const char **>(CCArgs.data()),
132 const_cast<const char **>(CCArgs.data()) +
133 CCArgs.size(),
Benjamin Kramer6a2542b2010-04-20 11:55:38 +0000134 Diags);
Daniel Dunbar0076d942010-02-25 08:49:05 +0000135
136 // Show the invocation, with -v.
137 if (CI->getHeaderSearchOpts().Verbose) {
138 llvm::errs() << "clang invocation:\n";
Hans Wennborgb212b342013-09-12 18:23:34 +0000139 Jobs.Print(llvm::errs(), "\n", true);
Daniel Dunbar0076d942010-02-25 08:49:05 +0000140 llvm::errs() << "\n";
141 }
142
143 // FIXME: This is copied from cc1_main.cpp; simplify and eliminate.
144
145 // Create a compiler instance to handle the actual work.
146 CompilerInstance Clang;
Ahmed Charlesa3374442014-03-09 11:46:32 +0000147 Clang.setInvocation(CI.release());
Daniel Dunbar0076d942010-02-25 08:49:05 +0000148
149 // Create the compilers actual diagnostics engine.
Sean Silvaf1b49e22013-01-20 01:58:28 +0000150 Clang.createDiagnostics();
Daniel Dunbar0076d942010-02-25 08:49:05 +0000151 if (!Clang.hasDiagnostics())
152 return 1;
153
154 // Infer the builtin include path if unspecified.
155 if (Clang.getHeaderSearchOpts().UseBuiltinIncludes &&
156 Clang.getHeaderSearchOpts().ResourceDir.empty())
157 Clang.getHeaderSearchOpts().ResourceDir =
158 CompilerInvocation::GetResourcesPath(argv[0], MainAddr);
159
160 // Create and execute the frontend to generate an LLVM bitcode module.
Ahmed Charlesaf94d562014-03-09 11:34:25 +0000161 std::unique_ptr<CodeGenAction> Act(new EmitLLVMOnlyAction());
Daniel Dunbar0076d942010-02-25 08:49:05 +0000162 if (!Clang.ExecuteAction(*Act))
163 return 1;
164
165 int Res = 255;
166 if (llvm::Module *Module = Act->takeModule())
167 Res = Execute(Module, envp);
168
169 // Shutdown.
170
171 llvm::llvm_shutdown();
172
173 return Res;
174}