xref: /netbsd-src/external/apache2/llvm/dist/clang/examples/clang-interpreter/main.cpp (revision e038c9c4676b0f19b1b7dd08a940c6ed64a6d5ae)
17330f729Sjoerg //===-- examples/clang-interpreter/main.cpp - Clang C Interpreter Example -===//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg 
97330f729Sjoerg #include "clang/Basic/DiagnosticOptions.h"
107330f729Sjoerg #include "clang/CodeGen/CodeGenAction.h"
117330f729Sjoerg #include "clang/Driver/Compilation.h"
127330f729Sjoerg #include "clang/Driver/Driver.h"
137330f729Sjoerg #include "clang/Driver/Tool.h"
147330f729Sjoerg #include "clang/Frontend/CompilerInstance.h"
157330f729Sjoerg #include "clang/Frontend/CompilerInvocation.h"
167330f729Sjoerg #include "clang/Frontend/FrontendDiagnostic.h"
177330f729Sjoerg #include "clang/Frontend/TextDiagnosticPrinter.h"
187330f729Sjoerg #include "llvm/ADT/SmallString.h"
197330f729Sjoerg #include "llvm/ExecutionEngine/ExecutionEngine.h"
207330f729Sjoerg #include "llvm/ExecutionEngine/Orc/CompileUtils.h"
217330f729Sjoerg #include "llvm/ExecutionEngine/Orc/ExecutionUtils.h"
227330f729Sjoerg #include "llvm/ExecutionEngine/Orc/IRCompileLayer.h"
237330f729Sjoerg #include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h"
247330f729Sjoerg #include "llvm/ExecutionEngine/SectionMemoryManager.h"
257330f729Sjoerg #include "llvm/IR/DataLayout.h"
267330f729Sjoerg #include "llvm/IR/Mangler.h"
277330f729Sjoerg #include "llvm/IR/Module.h"
287330f729Sjoerg #include "llvm/Support/FileSystem.h"
297330f729Sjoerg #include "llvm/Support/Host.h"
307330f729Sjoerg #include "llvm/Support/ManagedStatic.h"
317330f729Sjoerg #include "llvm/Support/Path.h"
327330f729Sjoerg #include "llvm/Support/TargetSelect.h"
337330f729Sjoerg #include "llvm/Support/raw_ostream.h"
347330f729Sjoerg #include "llvm/Target/TargetMachine.h"
357330f729Sjoerg 
367330f729Sjoerg using namespace clang;
377330f729Sjoerg using namespace clang::driver;
387330f729Sjoerg 
397330f729Sjoerg // This function isn't referenced outside its translation unit, but it
407330f729Sjoerg // can't use the "static" keyword because its address is used for
417330f729Sjoerg // GetMainExecutable (since some platforms don't support taking the
427330f729Sjoerg // address of main, and some platforms can't implement GetMainExecutable
437330f729Sjoerg // without being given the address of a function in the main executable).
GetExecutablePath(const char * Argv0,void * MainAddr)447330f729Sjoerg std::string GetExecutablePath(const char *Argv0, void *MainAddr) {
457330f729Sjoerg   return llvm::sys::fs::getMainExecutable(Argv0, MainAddr);
467330f729Sjoerg }
477330f729Sjoerg 
487330f729Sjoerg namespace llvm {
497330f729Sjoerg namespace orc {
507330f729Sjoerg 
517330f729Sjoerg class SimpleJIT {
527330f729Sjoerg private:
537330f729Sjoerg   ExecutionSession ES;
547330f729Sjoerg   std::unique_ptr<TargetMachine> TM;
557330f729Sjoerg   const DataLayout DL;
567330f729Sjoerg   MangleAndInterner Mangle{ES, DL};
57*e038c9c4Sjoerg   JITDylib &MainJD{ES.createBareJITDylib("<main>")};
587330f729Sjoerg   RTDyldObjectLinkingLayer ObjectLayer{ES, createMemMgr};
59*e038c9c4Sjoerg   IRCompileLayer CompileLayer{ES, ObjectLayer,
60*e038c9c4Sjoerg                               std::make_unique<SimpleCompiler>(*TM)};
617330f729Sjoerg 
createMemMgr()627330f729Sjoerg   static std::unique_ptr<SectionMemoryManager> createMemMgr() {
637330f729Sjoerg     return std::make_unique<SectionMemoryManager>();
647330f729Sjoerg   }
657330f729Sjoerg 
SimpleJIT(std::unique_ptr<TargetMachine> TM,DataLayout DL,std::unique_ptr<DynamicLibrarySearchGenerator> ProcessSymbolsGenerator)667330f729Sjoerg   SimpleJIT(
677330f729Sjoerg       std::unique_ptr<TargetMachine> TM, DataLayout DL,
687330f729Sjoerg       std::unique_ptr<DynamicLibrarySearchGenerator> ProcessSymbolsGenerator)
697330f729Sjoerg       : TM(std::move(TM)), DL(std::move(DL)) {
707330f729Sjoerg     llvm::sys::DynamicLibrary::LoadLibraryPermanently(nullptr);
71*e038c9c4Sjoerg     MainJD.addGenerator(std::move(ProcessSymbolsGenerator));
727330f729Sjoerg   }
737330f729Sjoerg 
747330f729Sjoerg public:
~SimpleJIT()75*e038c9c4Sjoerg   ~SimpleJIT() {
76*e038c9c4Sjoerg     if (auto Err = ES.endSession())
77*e038c9c4Sjoerg       ES.reportError(std::move(Err));
78*e038c9c4Sjoerg   }
79*e038c9c4Sjoerg 
Create()807330f729Sjoerg   static Expected<std::unique_ptr<SimpleJIT>> Create() {
817330f729Sjoerg     auto JTMB = JITTargetMachineBuilder::detectHost();
827330f729Sjoerg     if (!JTMB)
837330f729Sjoerg       return JTMB.takeError();
847330f729Sjoerg 
857330f729Sjoerg     auto TM = JTMB->createTargetMachine();
867330f729Sjoerg     if (!TM)
877330f729Sjoerg       return TM.takeError();
887330f729Sjoerg 
897330f729Sjoerg     auto DL = (*TM)->createDataLayout();
907330f729Sjoerg 
917330f729Sjoerg     auto ProcessSymbolsGenerator =
927330f729Sjoerg         DynamicLibrarySearchGenerator::GetForCurrentProcess(
937330f729Sjoerg             DL.getGlobalPrefix());
947330f729Sjoerg 
957330f729Sjoerg     if (!ProcessSymbolsGenerator)
967330f729Sjoerg       return ProcessSymbolsGenerator.takeError();
977330f729Sjoerg 
987330f729Sjoerg     return std::unique_ptr<SimpleJIT>(new SimpleJIT(
997330f729Sjoerg         std::move(*TM), std::move(DL), std::move(*ProcessSymbolsGenerator)));
1007330f729Sjoerg   }
1017330f729Sjoerg 
getTargetMachine() const1027330f729Sjoerg   const TargetMachine &getTargetMachine() const { return *TM; }
1037330f729Sjoerg 
addModule(ThreadSafeModule M)1047330f729Sjoerg   Error addModule(ThreadSafeModule M) {
105*e038c9c4Sjoerg     return CompileLayer.add(MainJD, std::move(M));
1067330f729Sjoerg   }
1077330f729Sjoerg 
findSymbol(const StringRef & Name)1087330f729Sjoerg   Expected<JITEvaluatedSymbol> findSymbol(const StringRef &Name) {
109*e038c9c4Sjoerg     return ES.lookup({&MainJD}, Mangle(Name));
1107330f729Sjoerg   }
1117330f729Sjoerg 
getSymbolAddress(const StringRef & Name)1127330f729Sjoerg   Expected<JITTargetAddress> getSymbolAddress(const StringRef &Name) {
1137330f729Sjoerg     auto Sym = findSymbol(Name);
1147330f729Sjoerg     if (!Sym)
1157330f729Sjoerg       return Sym.takeError();
1167330f729Sjoerg     return Sym->getAddress();
1177330f729Sjoerg   }
1187330f729Sjoerg };
1197330f729Sjoerg 
1207330f729Sjoerg } // end namespace orc
1217330f729Sjoerg } // end namespace llvm
1227330f729Sjoerg 
1237330f729Sjoerg llvm::ExitOnError ExitOnErr;
1247330f729Sjoerg 
main(int argc,const char ** argv)1257330f729Sjoerg int main(int argc, const char **argv) {
1267330f729Sjoerg   // This just needs to be some symbol in the binary; C++ doesn't
1277330f729Sjoerg   // allow taking the address of ::main however.
1287330f729Sjoerg   void *MainAddr = (void*) (intptr_t) GetExecutablePath;
1297330f729Sjoerg   std::string Path = GetExecutablePath(argv[0], MainAddr);
1307330f729Sjoerg   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
1317330f729Sjoerg   TextDiagnosticPrinter *DiagClient =
1327330f729Sjoerg     new TextDiagnosticPrinter(llvm::errs(), &*DiagOpts);
1337330f729Sjoerg 
1347330f729Sjoerg   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
1357330f729Sjoerg   DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient);
1367330f729Sjoerg 
1377330f729Sjoerg   const std::string TripleStr = llvm::sys::getProcessTriple();
1387330f729Sjoerg   llvm::Triple T(TripleStr);
1397330f729Sjoerg 
1407330f729Sjoerg   // Use ELF on Windows-32 and MingW for now.
1417330f729Sjoerg #ifndef CLANG_INTERPRETER_COFF_FORMAT
1427330f729Sjoerg   if (T.isOSBinFormatCOFF())
1437330f729Sjoerg     T.setObjectFormat(llvm::Triple::ELF);
1447330f729Sjoerg #endif
1457330f729Sjoerg 
1467330f729Sjoerg   ExitOnErr.setBanner("clang interpreter");
1477330f729Sjoerg 
1487330f729Sjoerg   Driver TheDriver(Path, T.str(), Diags);
1497330f729Sjoerg   TheDriver.setTitle("clang interpreter");
1507330f729Sjoerg   TheDriver.setCheckInputsExist(false);
1517330f729Sjoerg 
1527330f729Sjoerg   // FIXME: This is a hack to try to force the driver to do something we can
1537330f729Sjoerg   // recognize. We need to extend the driver library to support this use model
1547330f729Sjoerg   // (basically, exactly one input, and the operation mode is hard wired).
1557330f729Sjoerg   SmallVector<const char *, 16> Args(argv, argv + argc);
1567330f729Sjoerg   Args.push_back("-fsyntax-only");
1577330f729Sjoerg   std::unique_ptr<Compilation> C(TheDriver.BuildCompilation(Args));
1587330f729Sjoerg   if (!C)
1597330f729Sjoerg     return 0;
1607330f729Sjoerg 
1617330f729Sjoerg   // FIXME: This is copied from ASTUnit.cpp; simplify and eliminate.
1627330f729Sjoerg 
1637330f729Sjoerg   // We expect to get back exactly one command job, if we didn't something
1647330f729Sjoerg   // failed. Extract that job from the compilation.
1657330f729Sjoerg   const driver::JobList &Jobs = C->getJobs();
1667330f729Sjoerg   if (Jobs.size() != 1 || !isa<driver::Command>(*Jobs.begin())) {
1677330f729Sjoerg     SmallString<256> Msg;
1687330f729Sjoerg     llvm::raw_svector_ostream OS(Msg);
1697330f729Sjoerg     Jobs.Print(OS, "; ", true);
1707330f729Sjoerg     Diags.Report(diag::err_fe_expected_compiler_job) << OS.str();
1717330f729Sjoerg     return 1;
1727330f729Sjoerg   }
1737330f729Sjoerg 
1747330f729Sjoerg   const driver::Command &Cmd = cast<driver::Command>(*Jobs.begin());
1757330f729Sjoerg   if (llvm::StringRef(Cmd.getCreator().getName()) != "clang") {
1767330f729Sjoerg     Diags.Report(diag::err_fe_expected_clang_command);
1777330f729Sjoerg     return 1;
1787330f729Sjoerg   }
1797330f729Sjoerg 
1807330f729Sjoerg   // Initialize a compiler invocation object from the clang (-cc1) arguments.
1817330f729Sjoerg   const llvm::opt::ArgStringList &CCArgs = Cmd.getArguments();
1827330f729Sjoerg   std::unique_ptr<CompilerInvocation> CI(new CompilerInvocation);
1837330f729Sjoerg   CompilerInvocation::CreateFromArgs(*CI, CCArgs, Diags);
1847330f729Sjoerg 
1857330f729Sjoerg   // Show the invocation, with -v.
1867330f729Sjoerg   if (CI->getHeaderSearchOpts().Verbose) {
1877330f729Sjoerg     llvm::errs() << "clang invocation:\n";
1887330f729Sjoerg     Jobs.Print(llvm::errs(), "\n", true);
1897330f729Sjoerg     llvm::errs() << "\n";
1907330f729Sjoerg   }
1917330f729Sjoerg 
1927330f729Sjoerg   // FIXME: This is copied from cc1_main.cpp; simplify and eliminate.
1937330f729Sjoerg 
1947330f729Sjoerg   // Create a compiler instance to handle the actual work.
1957330f729Sjoerg   CompilerInstance Clang;
1967330f729Sjoerg   Clang.setInvocation(std::move(CI));
1977330f729Sjoerg 
1987330f729Sjoerg   // Create the compilers actual diagnostics engine.
1997330f729Sjoerg   Clang.createDiagnostics();
2007330f729Sjoerg   if (!Clang.hasDiagnostics())
2017330f729Sjoerg     return 1;
2027330f729Sjoerg 
2037330f729Sjoerg   // Infer the builtin include path if unspecified.
2047330f729Sjoerg   if (Clang.getHeaderSearchOpts().UseBuiltinIncludes &&
2057330f729Sjoerg       Clang.getHeaderSearchOpts().ResourceDir.empty())
2067330f729Sjoerg     Clang.getHeaderSearchOpts().ResourceDir =
2077330f729Sjoerg       CompilerInvocation::GetResourcesPath(argv[0], MainAddr);
2087330f729Sjoerg 
2097330f729Sjoerg   // Create and execute the frontend to generate an LLVM bitcode module.
2107330f729Sjoerg   std::unique_ptr<CodeGenAction> Act(new EmitLLVMOnlyAction());
2117330f729Sjoerg   if (!Clang.ExecuteAction(*Act))
2127330f729Sjoerg     return 1;
2137330f729Sjoerg 
2147330f729Sjoerg   llvm::InitializeNativeTarget();
2157330f729Sjoerg   llvm::InitializeNativeTargetAsmPrinter();
2167330f729Sjoerg 
2177330f729Sjoerg   int Res = 255;
2187330f729Sjoerg   std::unique_ptr<llvm::LLVMContext> Ctx(Act->takeLLVMContext());
2197330f729Sjoerg   std::unique_ptr<llvm::Module> Module = Act->takeModule();
2207330f729Sjoerg 
2217330f729Sjoerg   if (Module) {
2227330f729Sjoerg     auto J = ExitOnErr(llvm::orc::SimpleJIT::Create());
2237330f729Sjoerg 
2247330f729Sjoerg     ExitOnErr(J->addModule(
2257330f729Sjoerg         llvm::orc::ThreadSafeModule(std::move(Module), std::move(Ctx))));
2267330f729Sjoerg     auto Main = (int (*)(...))ExitOnErr(J->getSymbolAddress("main"));
2277330f729Sjoerg     Res = Main();
2287330f729Sjoerg   }
2297330f729Sjoerg 
2307330f729Sjoerg   // Shutdown.
2317330f729Sjoerg   llvm::llvm_shutdown();
2327330f729Sjoerg 
2337330f729Sjoerg   return Res;
2347330f729Sjoerg }
235