xref: /llvm-project/clang/lib/Interpreter/Interpreter.cpp (revision a8744066e9ef252b687c1206ccbd1a6e3ae1c890)
1 //===------ Interpreter.cpp - Incremental Compilation and Execution -------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the component which performs incremental code
10 // compilation and execution.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "DeviceOffload.h"
15 #include "IncrementalExecutor.h"
16 #include "IncrementalParser.h"
17 #include "InterpreterUtils.h"
18 #ifdef __EMSCRIPTEN__
19 #include "Wasm.h"
20 #endif // __EMSCRIPTEN__
21 
22 #include "clang/AST/ASTConsumer.h"
23 #include "clang/AST/ASTContext.h"
24 #include "clang/AST/Mangle.h"
25 #include "clang/AST/TypeVisitor.h"
26 #include "clang/Basic/DiagnosticSema.h"
27 #include "clang/Basic/TargetInfo.h"
28 #include "clang/CodeGen/CodeGenAction.h"
29 #include "clang/CodeGen/ModuleBuilder.h"
30 #include "clang/CodeGen/ObjectFilePCHContainerWriter.h"
31 #include "clang/Driver/Compilation.h"
32 #include "clang/Driver/Driver.h"
33 #include "clang/Driver/Job.h"
34 #include "clang/Driver/Options.h"
35 #include "clang/Driver/Tool.h"
36 #include "clang/Frontend/CompilerInstance.h"
37 #include "clang/Frontend/FrontendAction.h"
38 #include "clang/Frontend/MultiplexConsumer.h"
39 #include "clang/Frontend/TextDiagnosticBuffer.h"
40 #include "clang/FrontendTool/Utils.h"
41 #include "clang/Interpreter/Interpreter.h"
42 #include "clang/Interpreter/Value.h"
43 #include "clang/Lex/PreprocessorOptions.h"
44 #include "clang/Sema/Lookup.h"
45 #include "clang/Serialization/ObjectFilePCHContainerReader.h"
46 #include "llvm/ExecutionEngine/JITSymbol.h"
47 #include "llvm/ExecutionEngine/Orc/LLJIT.h"
48 #include "llvm/IR/Module.h"
49 #include "llvm/Support/Errc.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/raw_ostream.h"
52 #include "llvm/TargetParser/Host.h"
53 #include "llvm/Transforms/Utils/Cloning.h" // for CloneModule
54 
55 #define DEBUG_TYPE "clang-repl"
56 
57 using namespace clang;
58 // FIXME: Figure out how to unify with namespace init_convenience from
59 //        tools/clang-import-test/clang-import-test.cpp
60 namespace {
61 /// Retrieves the clang CC1 specific flags out of the compilation's jobs.
62 /// \returns NULL on error.
63 static llvm::Expected<const llvm::opt::ArgStringList *>
64 GetCC1Arguments(DiagnosticsEngine *Diagnostics,
65                 driver::Compilation *Compilation) {
66   // We expect to get back exactly one Command job, if we didn't something
67   // failed. Extract that job from the Compilation.
68   const driver::JobList &Jobs = Compilation->getJobs();
69   if (!Jobs.size() || !isa<driver::Command>(*Jobs.begin()))
70     return llvm::createStringError(llvm::errc::not_supported,
71                                    "Driver initialization failed. "
72                                    "Unable to create a driver job");
73 
74   // The one job we find should be to invoke clang again.
75   const driver::Command *Cmd = cast<driver::Command>(&(*Jobs.begin()));
76   if (llvm::StringRef(Cmd->getCreator().getName()) != "clang")
77     return llvm::createStringError(llvm::errc::not_supported,
78                                    "Driver initialization failed");
79 
80   return &Cmd->getArguments();
81 }
82 
83 static llvm::Expected<std::unique_ptr<CompilerInstance>>
84 CreateCI(const llvm::opt::ArgStringList &Argv) {
85   std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
86   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
87 
88   // Register the support for object-file-wrapped Clang modules.
89   // FIXME: Clang should register these container operations automatically.
90   auto PCHOps = Clang->getPCHContainerOperations();
91   PCHOps->registerWriter(std::make_unique<ObjectFilePCHContainerWriter>());
92   PCHOps->registerReader(std::make_unique<ObjectFilePCHContainerReader>());
93 
94   // Buffer diagnostics from argument parsing so that we can output them using
95   // a well formed diagnostic object.
96   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
97   TextDiagnosticBuffer *DiagsBuffer = new TextDiagnosticBuffer;
98   DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagsBuffer);
99   bool Success = CompilerInvocation::CreateFromArgs(
100       Clang->getInvocation(), llvm::ArrayRef(Argv.begin(), Argv.size()), Diags);
101 
102   // Infer the builtin include path if unspecified.
103   if (Clang->getHeaderSearchOpts().UseBuiltinIncludes &&
104       Clang->getHeaderSearchOpts().ResourceDir.empty())
105     Clang->getHeaderSearchOpts().ResourceDir =
106         CompilerInvocation::GetResourcesPath(Argv[0], nullptr);
107 
108   // Create the actual diagnostics engine.
109   Clang->createDiagnostics();
110   if (!Clang->hasDiagnostics())
111     return llvm::createStringError(llvm::errc::not_supported,
112                                    "Initialization failed. "
113                                    "Unable to create diagnostics engine");
114 
115   DiagsBuffer->FlushDiagnostics(Clang->getDiagnostics());
116   if (!Success)
117     return llvm::createStringError(llvm::errc::not_supported,
118                                    "Initialization failed. "
119                                    "Unable to flush diagnostics");
120 
121   // FIXME: Merge with CompilerInstance::ExecuteAction.
122   llvm::MemoryBuffer *MB = llvm::MemoryBuffer::getMemBuffer("").release();
123   Clang->getPreprocessorOpts().addRemappedFile("<<< inputs >>>", MB);
124 
125   Clang->setTarget(TargetInfo::CreateTargetInfo(
126       Clang->getDiagnostics(), Clang->getInvocation().TargetOpts));
127   if (!Clang->hasTarget())
128     return llvm::createStringError(llvm::errc::not_supported,
129                                    "Initialization failed. "
130                                    "Target is missing");
131 
132   Clang->getTarget().adjust(Clang->getDiagnostics(), Clang->getLangOpts());
133 
134   // Don't clear the AST before backend codegen since we do codegen multiple
135   // times, reusing the same AST.
136   Clang->getCodeGenOpts().ClearASTBeforeBackend = false;
137 
138   Clang->getFrontendOpts().DisableFree = false;
139   Clang->getCodeGenOpts().DisableFree = false;
140   return std::move(Clang);
141 }
142 
143 } // anonymous namespace
144 
145 namespace clang {
146 
147 llvm::Expected<std::unique_ptr<CompilerInstance>>
148 IncrementalCompilerBuilder::create(std::string TT,
149                                    std::vector<const char *> &ClangArgv) {
150 
151   // If we don't know ClangArgv0 or the address of main() at this point, try
152   // to guess it anyway (it's possible on some platforms).
153   std::string MainExecutableName =
154       llvm::sys::fs::getMainExecutable(nullptr, nullptr);
155 
156   ClangArgv.insert(ClangArgv.begin(), MainExecutableName.c_str());
157 
158   // Prepending -c to force the driver to do something if no action was
159   // specified. By prepending we allow users to override the default
160   // action and use other actions in incremental mode.
161   // FIXME: Print proper driver diagnostics if the driver flags are wrong.
162   // We do C++ by default; append right after argv[0] if no "-x" given
163   ClangArgv.insert(ClangArgv.end(), "-Xclang");
164   ClangArgv.insert(ClangArgv.end(), "-fincremental-extensions");
165   ClangArgv.insert(ClangArgv.end(), "-c");
166 
167   // Put a dummy C++ file on to ensure there's at least one compile job for the
168   // driver to construct.
169   ClangArgv.push_back("<<< inputs >>>");
170 
171   // Buffer diagnostics from argument parsing so that we can output them using a
172   // well formed diagnostic object.
173   IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
174   IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts =
175       CreateAndPopulateDiagOpts(ClangArgv);
176   TextDiagnosticBuffer *DiagsBuffer = new TextDiagnosticBuffer;
177   DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagsBuffer);
178 
179   driver::Driver Driver(/*MainBinaryName=*/ClangArgv[0], TT, Diags);
180   Driver.setCheckInputsExist(false); // the input comes from mem buffers
181   llvm::ArrayRef<const char *> RF = llvm::ArrayRef(ClangArgv);
182   std::unique_ptr<driver::Compilation> Compilation(Driver.BuildCompilation(RF));
183 
184   if (Compilation->getArgs().hasArg(driver::options::OPT_v))
185     Compilation->getJobs().Print(llvm::errs(), "\n", /*Quote=*/false);
186 
187   auto ErrOrCC1Args = GetCC1Arguments(&Diags, Compilation.get());
188   if (auto Err = ErrOrCC1Args.takeError())
189     return std::move(Err);
190 
191   return CreateCI(**ErrOrCC1Args);
192 }
193 
194 llvm::Expected<std::unique_ptr<CompilerInstance>>
195 IncrementalCompilerBuilder::CreateCpp() {
196   std::vector<const char *> Argv;
197   Argv.reserve(5 + 1 + UserArgs.size());
198   Argv.push_back("-xc++");
199 #ifdef __EMSCRIPTEN__
200   Argv.push_back("-target");
201   Argv.push_back("wasm32-unknown-emscripten");
202   Argv.push_back("-shared");
203 #endif
204   Argv.insert(Argv.end(), UserArgs.begin(), UserArgs.end());
205 
206   std::string TT = TargetTriple ? *TargetTriple : llvm::sys::getProcessTriple();
207   return IncrementalCompilerBuilder::create(TT, Argv);
208 }
209 
210 llvm::Expected<std::unique_ptr<CompilerInstance>>
211 IncrementalCompilerBuilder::createCuda(bool device) {
212   std::vector<const char *> Argv;
213   Argv.reserve(5 + 4 + UserArgs.size());
214 
215   Argv.push_back("-xcuda");
216   if (device)
217     Argv.push_back("--cuda-device-only");
218   else
219     Argv.push_back("--cuda-host-only");
220 
221   std::string SDKPathArg = "--cuda-path=";
222   if (!CudaSDKPath.empty()) {
223     SDKPathArg += CudaSDKPath;
224     Argv.push_back(SDKPathArg.c_str());
225   }
226 
227   std::string ArchArg = "--offload-arch=";
228   if (!OffloadArch.empty()) {
229     ArchArg += OffloadArch;
230     Argv.push_back(ArchArg.c_str());
231   }
232 
233   Argv.insert(Argv.end(), UserArgs.begin(), UserArgs.end());
234 
235   std::string TT = TargetTriple ? *TargetTriple : llvm::sys::getProcessTriple();
236   return IncrementalCompilerBuilder::create(TT, Argv);
237 }
238 
239 llvm::Expected<std::unique_ptr<CompilerInstance>>
240 IncrementalCompilerBuilder::CreateCudaDevice() {
241   return IncrementalCompilerBuilder::createCuda(true);
242 }
243 
244 llvm::Expected<std::unique_ptr<CompilerInstance>>
245 IncrementalCompilerBuilder::CreateCudaHost() {
246   return IncrementalCompilerBuilder::createCuda(false);
247 }
248 
249 class InProcessPrintingASTConsumer final : public MultiplexConsumer {
250   Interpreter &Interp;
251 
252 public:
253   InProcessPrintingASTConsumer(std::unique_ptr<ASTConsumer> C, Interpreter &I)
254       : MultiplexConsumer(std::move(C)), Interp(I) {}
255   bool HandleTopLevelDecl(DeclGroupRef DGR) override final {
256     if (DGR.isNull())
257       return true;
258 
259     for (Decl *D : DGR)
260       if (auto *TLSD = llvm::dyn_cast<TopLevelStmtDecl>(D))
261         if (TLSD && TLSD->isSemiMissing()) {
262           auto ExprOrErr =
263               Interp.ExtractValueFromExpr(cast<Expr>(TLSD->getStmt()));
264           if (llvm::Error E = ExprOrErr.takeError()) {
265             llvm::logAllUnhandledErrors(std::move(E), llvm::errs(),
266                                         "Value printing failed: ");
267             return false; // abort parsing
268           }
269           TLSD->setStmt(*ExprOrErr);
270         }
271 
272     return MultiplexConsumer::HandleTopLevelDecl(DGR);
273   }
274 };
275 
276 /// A custom action enabling the incremental processing functionality.
277 ///
278 /// The usual \p FrontendAction expects one call to ExecuteAction and once it
279 /// sees a call to \p EndSourceFile it deletes some of the important objects
280 /// such as \p Preprocessor and \p Sema assuming no further input will come.
281 ///
282 /// \p IncrementalAction ensures it keep its underlying action's objects alive
283 /// as long as the \p IncrementalParser needs them.
284 ///
285 class IncrementalAction : public WrapperFrontendAction {
286 private:
287   bool IsTerminating = false;
288   Interpreter &Interp;
289   std::unique_ptr<ASTConsumer> Consumer;
290 
291 public:
292   IncrementalAction(CompilerInstance &CI, llvm::LLVMContext &LLVMCtx,
293                     llvm::Error &Err, Interpreter &I,
294                     std::unique_ptr<ASTConsumer> Consumer = nullptr)
295       : WrapperFrontendAction([&]() {
296           llvm::ErrorAsOutParameter EAO(&Err);
297           std::unique_ptr<FrontendAction> Act;
298           switch (CI.getFrontendOpts().ProgramAction) {
299           default:
300             Err = llvm::createStringError(
301                 std::errc::state_not_recoverable,
302                 "Driver initialization failed. "
303                 "Incremental mode for action %d is not supported",
304                 CI.getFrontendOpts().ProgramAction);
305             return Act;
306           case frontend::ASTDump:
307           case frontend::ASTPrint:
308           case frontend::ParseSyntaxOnly:
309             Act = CreateFrontendAction(CI);
310             break;
311           case frontend::PluginAction:
312           case frontend::EmitAssembly:
313           case frontend::EmitBC:
314           case frontend::EmitObj:
315           case frontend::PrintPreprocessedInput:
316           case frontend::EmitLLVMOnly:
317             Act.reset(new EmitLLVMOnlyAction(&LLVMCtx));
318             break;
319           }
320           return Act;
321         }()),
322         Interp(I), Consumer(std::move(Consumer)) {}
323   FrontendAction *getWrapped() const { return WrappedAction.get(); }
324   TranslationUnitKind getTranslationUnitKind() override {
325     return TU_Incremental;
326   }
327 
328   std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
329                                                  StringRef InFile) override {
330     std::unique_ptr<ASTConsumer> C =
331         WrapperFrontendAction::CreateASTConsumer(CI, InFile);
332 
333     if (Consumer) {
334       std::vector<std::unique_ptr<ASTConsumer>> Cs;
335       Cs.push_back(std::move(Consumer));
336       Cs.push_back(std::move(C));
337       return std::make_unique<MultiplexConsumer>(std::move(Cs));
338     }
339 
340     return std::make_unique<InProcessPrintingASTConsumer>(std::move(C), Interp);
341   }
342 
343   void ExecuteAction() override {
344     WrapperFrontendAction::ExecuteAction();
345     getCompilerInstance().getSema().CurContext = nullptr;
346   }
347 
348   // Do not terminate after processing the input. This allows us to keep various
349   // clang objects alive and to incrementally grow the current TU.
350   void EndSourceFile() override {
351     // The WrappedAction can be nullptr if we issued an error in the ctor.
352     if (IsTerminating && getWrapped())
353       WrapperFrontendAction::EndSourceFile();
354   }
355 
356   void FinalizeAction() {
357     assert(!IsTerminating && "Already finalized!");
358     IsTerminating = true;
359     EndSourceFile();
360   }
361 };
362 
363 Interpreter::Interpreter(std::unique_ptr<CompilerInstance> Instance,
364                          llvm::Error &ErrOut,
365                          std::unique_ptr<llvm::orc::LLJITBuilder> JITBuilder,
366                          std::unique_ptr<clang::ASTConsumer> Consumer)
367     : JITBuilder(std::move(JITBuilder)) {
368   CI = std::move(Instance);
369   llvm::ErrorAsOutParameter EAO(&ErrOut);
370   auto LLVMCtx = std::make_unique<llvm::LLVMContext>();
371   TSCtx = std::make_unique<llvm::orc::ThreadSafeContext>(std::move(LLVMCtx));
372 
373   Act = std::make_unique<IncrementalAction>(*CI, *TSCtx->getContext(), ErrOut,
374                                             *this, std::move(Consumer));
375   if (ErrOut)
376     return;
377   CI->ExecuteAction(*Act);
378 
379   IncrParser = std::make_unique<IncrementalParser>(*CI, ErrOut);
380 
381   if (ErrOut)
382     return;
383 
384   if (getCodeGen()) {
385     CachedInCodeGenModule = GenModule();
386     // The initial PTU is filled by `-include` or by CUDA includes
387     // automatically.
388     if (!CI->getPreprocessorOpts().Includes.empty()) {
389       // We can't really directly pass the CachedInCodeGenModule to the Jit
390       // because it will steal it, causing dangling references as explained in
391       // Interpreter::Execute
392       auto M = llvm::CloneModule(*CachedInCodeGenModule);
393       ASTContext &C = CI->getASTContext();
394       RegisterPTU(C.getTranslationUnitDecl(), std::move(M));
395     }
396     if (llvm::Error Err = CreateExecutor()) {
397       ErrOut = joinErrors(std::move(ErrOut), std::move(Err));
398       return;
399     }
400   }
401 
402   // Not all frontends support code-generation, e.g. ast-dump actions don't
403   if (getCodeGen()) {
404     // Process the PTUs that came from initialization. For example -include will
405     // give us a header that's processed at initialization of the preprocessor.
406     for (PartialTranslationUnit &PTU : PTUs)
407       if (llvm::Error Err = Execute(PTU)) {
408         ErrOut = joinErrors(std::move(ErrOut), std::move(Err));
409         return;
410       }
411   }
412 }
413 
414 Interpreter::~Interpreter() {
415   IncrParser.reset();
416   Act->FinalizeAction();
417   if (IncrExecutor) {
418     if (llvm::Error Err = IncrExecutor->cleanUp())
419       llvm::report_fatal_error(
420           llvm::Twine("Failed to clean up IncrementalExecutor: ") +
421           toString(std::move(Err)));
422   }
423 }
424 
425 // These better to put in a runtime header but we can't. This is because we
426 // can't find the precise resource directory in unittests so we have to hard
427 // code them.
428 const char *const Runtimes = R"(
429     #define __CLANG_REPL__ 1
430 #ifdef __cplusplus
431     #define EXTERN_C extern "C"
432     void *__clang_Interpreter_SetValueWithAlloc(void*, void*, void*);
433     struct __clang_Interpreter_NewTag{} __ci_newtag;
434     void* operator new(__SIZE_TYPE__, void* __p, __clang_Interpreter_NewTag) noexcept;
435     template <class T, class = T (*)() /*disable for arrays*/>
436     void __clang_Interpreter_SetValueCopyArr(T* Src, void* Placement, unsigned long Size) {
437       for (auto Idx = 0; Idx < Size; ++Idx)
438         new ((void*)(((T*)Placement) + Idx), __ci_newtag) T(Src[Idx]);
439     }
440     template <class T, unsigned long N>
441     void __clang_Interpreter_SetValueCopyArr(const T (*Src)[N], void* Placement, unsigned long Size) {
442       __clang_Interpreter_SetValueCopyArr(Src[0], Placement, Size);
443     }
444 #else
445     #define EXTERN_C extern
446 #endif // __cplusplus
447 
448   EXTERN_C void __clang_Interpreter_SetValueNoAlloc(void *This, void *OutVal, void *OpaqueType, ...);
449 )";
450 
451 llvm::Expected<std::unique_ptr<Interpreter>>
452 Interpreter::create(std::unique_ptr<CompilerInstance> CI) {
453   llvm::Error Err = llvm::Error::success();
454   auto Interp =
455       std::unique_ptr<Interpreter>(new Interpreter(std::move(CI), Err));
456   if (Err)
457     return std::move(Err);
458 
459   // Add runtime code and set a marker to hide it from user code. Undo will not
460   // go through that.
461   auto PTU = Interp->Parse(Runtimes);
462   if (!PTU)
463     return PTU.takeError();
464   Interp->markUserCodeStart();
465 
466   Interp->ValuePrintingInfo.resize(4);
467   return std::move(Interp);
468 }
469 
470 llvm::Expected<std::unique_ptr<Interpreter>>
471 Interpreter::createWithCUDA(std::unique_ptr<CompilerInstance> CI,
472                             std::unique_ptr<CompilerInstance> DCI) {
473   // avoid writing fat binary to disk using an in-memory virtual file system
474   llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> IMVFS =
475       std::make_unique<llvm::vfs::InMemoryFileSystem>();
476   llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayVFS =
477       std::make_unique<llvm::vfs::OverlayFileSystem>(
478           llvm::vfs::getRealFileSystem());
479   OverlayVFS->pushOverlay(IMVFS);
480   CI->createFileManager(OverlayVFS);
481 
482   auto Interp = Interpreter::create(std::move(CI));
483   if (auto E = Interp.takeError())
484     return std::move(E);
485 
486   llvm::Error Err = llvm::Error::success();
487   auto DeviceParser = std::make_unique<IncrementalCUDADeviceParser>(
488       std::move(DCI), *(*Interp)->getCompilerInstance(), IMVFS, Err,
489       (*Interp)->PTUs);
490   if (Err)
491     return std::move(Err);
492 
493   (*Interp)->DeviceParser = std::move(DeviceParser);
494 
495   return Interp;
496 }
497 
498 const CompilerInstance *Interpreter::getCompilerInstance() const {
499   return CI.get();
500 }
501 
502 CompilerInstance *Interpreter::getCompilerInstance() { return CI.get(); }
503 
504 llvm::Expected<llvm::orc::LLJIT &> Interpreter::getExecutionEngine() {
505   if (!IncrExecutor) {
506     if (auto Err = CreateExecutor())
507       return std::move(Err);
508   }
509 
510   return IncrExecutor->GetExecutionEngine();
511 }
512 
513 ASTContext &Interpreter::getASTContext() {
514   return getCompilerInstance()->getASTContext();
515 }
516 
517 const ASTContext &Interpreter::getASTContext() const {
518   return getCompilerInstance()->getASTContext();
519 }
520 
521 void Interpreter::markUserCodeStart() {
522   assert(!InitPTUSize && "We only do this once");
523   InitPTUSize = PTUs.size();
524 }
525 
526 size_t Interpreter::getEffectivePTUSize() const {
527   assert(PTUs.size() >= InitPTUSize && "empty PTU list?");
528   return PTUs.size() - InitPTUSize;
529 }
530 
531 PartialTranslationUnit &
532 Interpreter::RegisterPTU(TranslationUnitDecl *TU,
533                          std::unique_ptr<llvm::Module> M /*={}*/) {
534   PTUs.emplace_back(PartialTranslationUnit());
535   PartialTranslationUnit &LastPTU = PTUs.back();
536   LastPTU.TUPart = TU;
537 
538   if (!M)
539     M = GenModule();
540 
541   assert((!getCodeGen() || M) && "Must have a llvm::Module at this point");
542 
543   LastPTU.TheModule = std::move(M);
544   LLVM_DEBUG(llvm::dbgs() << "compile-ptu " << PTUs.size() - 1
545                           << ": [TU=" << LastPTU.TUPart);
546   if (LastPTU.TheModule)
547     LLVM_DEBUG(llvm::dbgs() << ", M=" << LastPTU.TheModule.get() << " ("
548                             << LastPTU.TheModule->getName() << ")");
549   LLVM_DEBUG(llvm::dbgs() << "]\n");
550   return LastPTU;
551 }
552 
553 llvm::Expected<PartialTranslationUnit &>
554 Interpreter::Parse(llvm::StringRef Code) {
555   // If we have a device parser, parse it first. The generated code will be
556   // included in the host compilation
557   if (DeviceParser) {
558     llvm::Expected<TranslationUnitDecl *> DeviceTU = DeviceParser->Parse(Code);
559     if (auto E = DeviceTU.takeError())
560       return std::move(E);
561   }
562 
563   // Tell the interpreter sliently ignore unused expressions since value
564   // printing could cause it.
565   getCompilerInstance()->getDiagnostics().setSeverity(
566       clang::diag::warn_unused_expr, diag::Severity::Ignored, SourceLocation());
567 
568   llvm::Expected<TranslationUnitDecl *> TuOrErr = IncrParser->Parse(Code);
569   if (!TuOrErr)
570     return TuOrErr.takeError();
571 
572   return RegisterPTU(*TuOrErr);
573 }
574 
575 static llvm::Expected<llvm::orc::JITTargetMachineBuilder>
576 createJITTargetMachineBuilder(const std::string &TT) {
577   if (TT == llvm::sys::getProcessTriple())
578     // This fails immediately if the target backend is not registered
579     return llvm::orc::JITTargetMachineBuilder::detectHost();
580 
581   // If the target backend is not registered, LLJITBuilder::create() will fail
582   return llvm::orc::JITTargetMachineBuilder(llvm::Triple(TT));
583 }
584 
585 llvm::Error Interpreter::CreateExecutor() {
586   if (IncrExecutor)
587     return llvm::make_error<llvm::StringError>("Operation failed. "
588                                                "Execution engine exists",
589                                                std::error_code());
590   if (!getCodeGen())
591     return llvm::make_error<llvm::StringError>("Operation failed. "
592                                                "No code generator available",
593                                                std::error_code());
594   if (!JITBuilder) {
595     const std::string &TT = getCompilerInstance()->getTargetOpts().Triple;
596     auto JTMB = createJITTargetMachineBuilder(TT);
597     if (!JTMB)
598       return JTMB.takeError();
599     auto JB = IncrementalExecutor::createDefaultJITBuilder(std::move(*JTMB));
600     if (!JB)
601       return JB.takeError();
602     JITBuilder = std::move(*JB);
603   }
604 
605   llvm::Error Err = llvm::Error::success();
606 #ifdef __EMSCRIPTEN__
607   auto Executor = std::make_unique<WasmIncrementalExecutor>(*TSCtx);
608 #else
609   auto Executor =
610       std::make_unique<IncrementalExecutor>(*TSCtx, *JITBuilder, Err);
611 #endif
612   if (!Err)
613     IncrExecutor = std::move(Executor);
614 
615   return Err;
616 }
617 
618 void Interpreter::ResetExecutor() { IncrExecutor.reset(); }
619 
620 llvm::Error Interpreter::Execute(PartialTranslationUnit &T) {
621   assert(T.TheModule);
622   LLVM_DEBUG(llvm::dbgs()
623              << "execute-ptu "
624              << ((std::find(PTUs.begin(), PTUs.end(), T) != PTUs.end())
625                      ? std::distance(PTUs.begin(),
626                                      std::find(PTUs.begin(), PTUs.end(), T))
627                      : -1)
628              << ": [TU=" << T.TUPart << ", M=" << T.TheModule.get() << " ("
629              << T.TheModule->getName() << ")]\n");
630   if (!IncrExecutor) {
631     auto Err = CreateExecutor();
632     if (Err)
633       return Err;
634   }
635   // FIXME: Add a callback to retain the llvm::Module once the JIT is done.
636   if (auto Err = IncrExecutor->addModule(T))
637     return Err;
638 
639   if (auto Err = IncrExecutor->runCtors())
640     return Err;
641 
642   return llvm::Error::success();
643 }
644 
645 llvm::Error Interpreter::ParseAndExecute(llvm::StringRef Code, Value *V) {
646 
647   auto PTU = Parse(Code);
648   if (!PTU)
649     return PTU.takeError();
650   if (PTU->TheModule)
651     if (llvm::Error Err = Execute(*PTU))
652       return Err;
653 
654   if (LastValue.isValid()) {
655     if (!V) {
656       LastValue.dump();
657       LastValue.clear();
658     } else
659       *V = std::move(LastValue);
660   }
661   return llvm::Error::success();
662 }
663 
664 llvm::Expected<llvm::orc::ExecutorAddr>
665 Interpreter::getSymbolAddress(GlobalDecl GD) const {
666   if (!IncrExecutor)
667     return llvm::make_error<llvm::StringError>("Operation failed. "
668                                                "No execution engine",
669                                                std::error_code());
670   llvm::StringRef MangledName = getCodeGen()->GetMangledName(GD);
671   return getSymbolAddress(MangledName);
672 }
673 
674 llvm::Expected<llvm::orc::ExecutorAddr>
675 Interpreter::getSymbolAddress(llvm::StringRef IRName) const {
676   if (!IncrExecutor)
677     return llvm::make_error<llvm::StringError>("Operation failed. "
678                                                "No execution engine",
679                                                std::error_code());
680 
681   return IncrExecutor->getSymbolAddress(IRName, IncrementalExecutor::IRName);
682 }
683 
684 llvm::Expected<llvm::orc::ExecutorAddr>
685 Interpreter::getSymbolAddressFromLinkerName(llvm::StringRef Name) const {
686   if (!IncrExecutor)
687     return llvm::make_error<llvm::StringError>("Operation failed. "
688                                                "No execution engine",
689                                                std::error_code());
690 
691   return IncrExecutor->getSymbolAddress(Name, IncrementalExecutor::LinkerName);
692 }
693 
694 llvm::Error Interpreter::Undo(unsigned N) {
695 
696   if (N > getEffectivePTUSize())
697     return llvm::make_error<llvm::StringError>("Operation failed. "
698                                                "Too many undos",
699                                                std::error_code());
700   for (unsigned I = 0; I < N; I++) {
701     if (IncrExecutor) {
702       if (llvm::Error Err = IncrExecutor->removeModule(PTUs.back()))
703         return Err;
704     }
705 
706     IncrParser->CleanUpPTU(PTUs.back().TUPart);
707     PTUs.pop_back();
708   }
709   return llvm::Error::success();
710 }
711 
712 llvm::Error Interpreter::LoadDynamicLibrary(const char *name) {
713   auto EE = getExecutionEngine();
714   if (!EE)
715     return EE.takeError();
716 
717   auto &DL = EE->getDataLayout();
718 
719   if (auto DLSG = llvm::orc::DynamicLibrarySearchGenerator::Load(
720           name, DL.getGlobalPrefix()))
721     EE->getMainJITDylib().addGenerator(std::move(*DLSG));
722   else
723     return DLSG.takeError();
724 
725   return llvm::Error::success();
726 }
727 
728 std::unique_ptr<llvm::Module> Interpreter::GenModule() {
729   static unsigned ID = 0;
730   if (CodeGenerator *CG = getCodeGen()) {
731     // Clang's CodeGen is designed to work with a single llvm::Module. In many
732     // cases for convenience various CodeGen parts have a reference to the
733     // llvm::Module (TheModule or Module) which does not change when a new
734     // module is pushed. However, the execution engine wants to take ownership
735     // of the module which does not map well to CodeGen's design. To work this
736     // around we created an empty module to make CodeGen happy. We should make
737     // sure it always stays empty.
738     assert(((!CachedInCodeGenModule ||
739              !getCompilerInstance()->getPreprocessorOpts().Includes.empty()) ||
740             (CachedInCodeGenModule->empty() &&
741              CachedInCodeGenModule->global_empty() &&
742              CachedInCodeGenModule->alias_empty() &&
743              CachedInCodeGenModule->ifunc_empty())) &&
744            "CodeGen wrote to a readonly module");
745     std::unique_ptr<llvm::Module> M(CG->ReleaseModule());
746     CG->StartModule("incr_module_" + std::to_string(ID++), M->getContext());
747     return M;
748   }
749   return nullptr;
750 }
751 
752 CodeGenerator *Interpreter::getCodeGen() const {
753   FrontendAction *WrappedAct = Act->getWrapped();
754   if (!WrappedAct->hasIRSupport())
755     return nullptr;
756   return static_cast<CodeGenAction *>(WrappedAct)->getCodeGenerator();
757 }
758 } // namespace clang
759