clang 24.0.0git
Interpreter.cpp
Go to the documentation of this file.
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 "IncrementalAction.h"
16#include "IncrementalParser.h"
17#include "InterpreterUtils.h"
18
21#include "clang/AST/Mangle.h"
29#include "clang/Driver/Driver.h"
30#include "clang/Driver/Job.h"
31#include "clang/Driver/Tool.h"
44#include "clang/Sema/Lookup.h"
48#include "llvm/ExecutionEngine/JITSymbol.h"
49#include "llvm/ExecutionEngine/Orc/EPCDynamicLibrarySearchGenerator.h"
50#include "llvm/ExecutionEngine/Orc/LLJIT.h"
51#include "llvm/IR/Module.h"
52#include "llvm/Support/Errc.h"
53#include "llvm/Support/ErrorHandling.h"
54#include "llvm/Support/VirtualFileSystem.h"
55#include "llvm/Support/raw_ostream.h"
56#include "llvm/TargetParser/Host.h"
57#include "llvm/TargetParser/Triple.h"
58#include "llvm/Transforms/Utils/Cloning.h" // for CloneModule
59
60#define DEBUG_TYPE "clang-repl"
61
62using namespace clang;
63// FIXME: Figure out how to unify with namespace init_convenience from
64// tools/clang-import-test/clang-import-test.cpp
65namespace {
66/// Retrieves the clang CC1 specific flags out of the compilation's jobs.
67/// \returns NULL on error.
69GetCC1Arguments(DiagnosticsEngine *Diagnostics,
70 driver::Compilation *Compilation) {
71 // We expect to get back exactly one Command job, if we didn't something
72 // failed. Extract that job from the Compilation.
73 const driver::JobList &Jobs = Compilation->getJobs();
74 if (!Jobs.size())
75 return llvm::createStringError(llvm::errc::not_supported,
76 "Driver initialization failed. "
77 "Unable to create a driver job");
78
79 // The one job we find should be to invoke clang again.
80 const driver::Command *Cmd = &*Jobs.begin();
81 if (llvm::StringRef(Cmd->getCreator().getName()) != "clang")
82 return llvm::createStringError(llvm::errc::not_supported,
83 "Driver initialization failed");
84
85 return &Cmd->getArguments();
86}
87
88// ASTReaderListener that captures the PIC level stored in a serialized AST
89// file (PCH or PCM) so the interpreter can compare it against its own.
90class PICLevelReader : public ASTReaderListener {
91 unsigned &PICLevel;
92
93public:
94 PICLevelReader(unsigned &PICLevel) : PICLevel(PICLevel) {}
95
96 bool ReadLanguageOptions(const LangOptions &LangOpts,
97 StringRef ModuleFilename, bool Complain,
98 bool AllowCompatibleDifferences) override {
99 PICLevel = LangOpts.PICLevel;
100 return false;
101 }
102};
103
104// clang-repl always compiles position-independent code (it injects -fPIC), so a
105// PCH/PCM that was built with a different PIC level is incompatible: mixing the
106// two leads to relocations that may be out of range once the JIT maps code more
107// than 2GB away. PICLevel is a "compatible" language option, so the ASTReader
108// would otherwise accept the mismatch silently. Reject it up front.
109//
110// The file is probed with its own FileManager and ModuleCache (sharing only the
111// VFS) so this read leaves the CompilerInstance's state untouched for the real
112// load performed later by ExecuteAction().
113static llvm::Error checkASTFilePICLevel(CompilerInstance &Clang,
114 StringRef Filename) {
117 std::shared_ptr<ModuleCache> ModCache = createCrossProcessModuleCache();
118 unsigned ASTPICLevel = 0;
119 PICLevelReader Reader(ASTPICLevel);
121 Filename, *FileMgr, *ModCache, Clang.getPCHContainerReader(),
122 /*FindModuleFileExtensions=*/false, Reader,
123 /*ValidateDiagnosticOptions=*/false) &&
124 ASTPICLevel != Clang.getLangOpts().PICLevel)
125 return llvm::createStringError(
126 llvm::errc::not_supported,
127 "AST file '%s' was built with PIC level %u, which is incompatible "
128 "with clang-repl's PIC level %u",
129 Filename.str().c_str(), ASTPICLevel, Clang.getLangOpts().PICLevel);
130 return llvm::Error::success();
131}
132
134CreateCI(const llvm::opt::ArgStringList &Argv) {
135 std::unique_ptr<CompilerInstance> Clang(new CompilerInstance());
136
137 // Register the support for object-file-wrapped Clang modules.
138 // FIXME: Clang should register these container operations automatically.
139 auto PCHOps = Clang->getPCHContainerOperations();
140 PCHOps->registerWriter(std::make_unique<ObjectFilePCHContainerWriter>());
141 PCHOps->registerReader(std::make_unique<ObjectFilePCHContainerReader>());
142
143 // Buffer diagnostics from argument parsing so that we can output them using
144 // a well formed diagnostic object.
145 DiagnosticOptions DiagOpts;
147 DiagnosticsEngine Diags(DiagnosticIDs::create(), DiagOpts, DiagsBuffer);
149 Clang->getInvocation(), llvm::ArrayRef(Argv.begin(), Argv.size()), Diags);
150
151 // Infer the builtin include path if unspecified.
152 if (Clang->getHeaderSearchOpts().UseBuiltinIncludes &&
153 Clang->getHeaderSearchOpts().ResourceDir.empty())
154 Clang->getHeaderSearchOpts().ResourceDir =
155 GetResourcesPath(Argv[0], nullptr);
156
157 Clang->createVirtualFileSystem();
158
159 // Create the actual diagnostics engine.
160 Clang->createDiagnostics();
161
162 DiagsBuffer->FlushDiagnostics(Clang->getDiagnostics());
163 if (!Success)
164 return llvm::createStringError(llvm::errc::not_supported,
165 "Initialization failed. "
166 "Unable to flush diagnostics");
167
168 // FIXME: Merge with CompilerInstance::ExecuteAction.
169 llvm::MemoryBuffer *MB = llvm::MemoryBuffer::getMemBuffer("").release();
170 Clang->getPreprocessorOpts().addRemappedFile("<<< inputs >>>", MB);
171
172 Clang->setTarget(TargetInfo::CreateTargetInfo(
173 Clang->getDiagnostics(), Clang->getInvocation().getTargetOpts()));
174 if (!Clang->hasTarget())
175 return llvm::createStringError(llvm::errc::not_supported,
176 "Initialization failed. "
177 "Target is missing");
178
179 Clang->getTarget().adjust(Clang->getDiagnostics(), Clang->getLangOpts(),
180 Clang->getAuxTarget());
181
182 // Don't clear the AST before backend codegen since we do codegen multiple
183 // times, reusing the same AST.
184 Clang->getCodeGenOpts().ClearASTBeforeBackend = false;
185
186 Clang->getFrontendOpts().DisableFree = false;
187 Clang->getCodeGenOpts().DisableFree = false;
188
189 // Reject any precompiled input (PCH or PCM) built with a PIC level that
190 // differs from clang-repl's own, before any Interpreter/FrontendAction is
191 // constructed. See checkASTFilePICLevel for the rationale.
192 StringRef PCHInclude = Clang->getPreprocessorOpts().ImplicitPCHInclude;
193 if (!PCHInclude.empty())
194 if (llvm::Error Err = checkASTFilePICLevel(*Clang, PCHInclude))
195 return std::move(Err);
196
197 // Explicitly loaded modules: -fmodule-file=<path> and
198 // -fmodule-file=<name>=<path>.
199 for (StringRef ModuleFile : Clang->getFrontendOpts().ModuleFiles)
200 if (llvm::Error Err = checkASTFilePICLevel(*Clang, ModuleFile))
201 return std::move(Err);
202 for (const auto &NameAndFile :
203 Clang->getHeaderSearchOpts().PrebuiltModuleFiles)
204 if (llvm::Error Err = checkASTFilePICLevel(*Clang, NameAndFile.second))
205 return std::move(Err);
206
207 return std::move(Clang);
208}
209
210static llvm::Error ExecuteIncrementalAction(CompilerInstance &CI,
211 IncrementalAction &Act) {
212 if (!CI.ExecuteAction(Act) || CI.getDiagnostics().hasErrorOccurred()) {
213 return llvm::createStringError(llvm::errc::not_supported,
214 "Failed to execute incremental action");
215 }
216 return llvm::Error::success();
217}
218
219} // anonymous namespace
220
221namespace clang {
222
224IncrementalCompilerBuilder::create(std::string TT,
225 std::vector<const char *> &ClangArgv) {
226
227 // If we don't know ClangArgv0 or the address of main() at this point, try
228 // to guess it anyway (it's possible on some platforms).
229 std::string MainExecutableName =
230 llvm::sys::fs::getMainExecutable(nullptr, nullptr);
231
232 ClangArgv.insert(ClangArgv.begin(), MainExecutableName.c_str());
233
234 // Compile as position-independent code. This prevents the frontend from
235 // marking external symbols (e.g. C++ type-info such as _ZTIPKc used for
236 // exception handling) as dso_local and emitting direct PC-relative
237 // references. JITLink can place the GOT entry near the JIT'd code, keeping
238 // the relocation in range. Without -fPIC, a direct Delta32 relocation to a
239 // host symbol may be out of range when the JIT memory is mapped more than
240 // 2GB away (as on FreeBSD), breaking tests such as
241 // Interpreter/simple-exception.cpp. Insert before user arguments so it can
242 // still be overridden. On Windows (excluding Cygwin/MinGW) an explicit
243 // -fPIC is an unsupported driver option that would drop non-x86_64 targets
244 // to PIC level 0; PIC is already the forced default there where relevant,
245 // so don't inject it.
246 llvm::Triple TargetTriple(TT);
247 if (!TargetTriple.isOSWindows() || TargetTriple.isOSCygMing())
248 ClangArgv.insert(ClangArgv.begin() + 1, "-fPIC");
249
250 // Prepending -c to force the driver to do something if no action was
251 // specified. By prepending we allow users to override the default
252 // action and use other actions in incremental mode.
253 // FIXME: Print proper driver diagnostics if the driver flags are wrong.
254 // We do C++ by default; append right after argv[0] if no "-x" given
255 ClangArgv.insert(ClangArgv.end(), "-Xclang");
256 ClangArgv.insert(ClangArgv.end(), "-fincremental-extensions");
257 ClangArgv.insert(ClangArgv.end(), "-c");
258
259 // Put a dummy C++ file on to ensure there's at least one compile job for the
260 // driver to construct.
261 ClangArgv.push_back("<<< inputs >>>");
262
263 // Buffer diagnostics from argument parsing so that we can output them using a
264 // well formed diagnostic object.
265 std::unique_ptr<DiagnosticOptions> DiagOpts =
266 CreateAndPopulateDiagOpts(ClangArgv);
267 TextDiagnosticBuffer *DiagsBuffer = new TextDiagnosticBuffer;
268 DiagnosticsEngine Diags(DiagnosticIDs::create(), *DiagOpts, DiagsBuffer);
269
270 driver::Driver Driver(/*MainBinaryName=*/ClangArgv[0], TT, Diags);
271 Driver.setCheckInputsExist(false); // the input comes from mem buffers
272 llvm::ArrayRef<const char *> RF = llvm::ArrayRef(ClangArgv);
273 std::unique_ptr<driver::Compilation> Compilation(Driver.BuildCompilation(RF));
274
275 if (CompilationCB)
276 if (auto Err = (*CompilationCB)(*Compilation.get()))
277 return std::move(Err);
278
279 if (Compilation->getArgs().hasArg(options::OPT_v))
280 Compilation->getJobs().Print(llvm::errs(), "\n", /*Quote=*/false);
281
282 auto ErrOrCC1Args = GetCC1Arguments(&Diags, Compilation.get());
283 if (auto Err = ErrOrCC1Args.takeError())
284 return std::move(Err);
285
286 return CreateCI(**ErrOrCC1Args);
287}
288
291 std::string TT = TargetTriple ? *TargetTriple : llvm::sys::getProcessTriple();
292
293 std::vector<const char *> Argv;
294 Argv.reserve(5 + 1 + UserArgs.size());
295 Argv.push_back("-xc++");
296#ifdef __EMSCRIPTEN__
297 Argv.push_back("-target");
298 Argv.push_back(TT.c_str());
299 Argv.push_back("-fvisibility=default");
300#endif
301 llvm::append_range(Argv, UserArgs);
302
303 return IncrementalCompilerBuilder::create(TT, Argv);
304}
305
307IncrementalCompilerBuilder::createCuda(bool device) {
308 std::vector<const char *> Argv;
309 Argv.reserve(5 + 4 + UserArgs.size());
310
311 Argv.push_back("-xcuda");
312 if (device)
313 Argv.push_back("--cuda-device-only");
314 else
315 Argv.push_back("--cuda-host-only");
316
317 std::string SDKPathArg = "--cuda-path=";
318 if (!CudaSDKPath.empty()) {
319 SDKPathArg += CudaSDKPath;
320 Argv.push_back(SDKPathArg.c_str());
321 }
322
323 std::string ArchArg = "--offload-arch=";
324 if (!OffloadArch.empty()) {
325 ArchArg += OffloadArch;
326 Argv.push_back(ArchArg.c_str());
327 }
328
329 llvm::append_range(Argv, UserArgs);
330
331 std::string TT = TargetTriple ? *TargetTriple : llvm::sys::getProcessTriple();
332 return IncrementalCompilerBuilder::create(TT, Argv);
333}
334
337 return IncrementalCompilerBuilder::createCuda(true);
338}
339
342 return IncrementalCompilerBuilder::createCuda(false);
343}
344
345Interpreter::Interpreter(std::unique_ptr<CompilerInstance> Instance,
346 llvm::Error &ErrOut,
347 std::unique_ptr<IncrementalExecutorBuilder> IEB,
348 std::unique_ptr<clang::ASTConsumer> Consumer)
349 : IncrExecutorBuilder(std::move(IEB)) {
350 CI = std::move(Instance);
351 llvm::ErrorAsOutParameter EAO(&ErrOut);
352 auto LLVMCtx = std::make_unique<llvm::LLVMContext>();
353 TSCtx = std::make_unique<llvm::orc::ThreadSafeContext>(std::move(LLVMCtx));
354
355 // Honor -mllvm options
356 CI->parseLLVMArgs();
357
358 Act = TSCtx->withContextDo([&](llvm::LLVMContext *Ctx) {
359 return std::make_unique<IncrementalAction>(*CI, *Ctx, ErrOut, *this,
360 std::move(Consumer));
361 });
362
363 if (ErrOut)
364 return;
365
366 if (llvm::Error E = ExecuteIncrementalAction(*CI, *Act)) {
367 ErrOut = joinErrors(std::move(ErrOut), std::move(E));
368 return;
369 }
370
371 IncrParser =
372 std::make_unique<IncrementalParser>(*CI, Act.get(), ErrOut, PTUs);
373
374 if (ErrOut)
375 return;
376
377 if (Act->getCodeGen()) {
378 Act->CacheCodeGenModule();
379 // The initial PTU is filled by `-include`/`-include-pch` or by CUDA
380 // includes automatically.
381 if (!CI->getPreprocessorOpts().Includes.empty() ||
382 !CI->getPreprocessorOpts().ImplicitPCHInclude.empty()) {
383 // We can't really directly pass the CachedInCodeGenModule to the Jit
384 // because it will steal it, causing dangling references as explained in
385 // Interpreter::Execute
386 auto M = llvm::CloneModule(*Act->getCachedCodeGenModule());
387 ASTContext &C = CI->getASTContext();
388 IncrParser->RegisterPTU(C.getTranslationUnitDecl(), std::move(M));
389 }
390 if (llvm::Error Err = CreateExecutor()) {
391 ErrOut = joinErrors(std::move(ErrOut), std::move(Err));
392 return;
393 }
394 }
395
396 // Not all frontends support code-generation, e.g. ast-dump actions don't
397 if (Act->getCodeGen()) {
398 // Process the PTUs that came from initialization. For example -include will
399 // give us a header that's processed at initialization of the preprocessor.
400 for (PartialTranslationUnit &PTU : PTUs)
401 if (llvm::Error Err = Execute(PTU)) {
402 ErrOut = joinErrors(std::move(ErrOut), std::move(Err));
403 return;
404 }
405 }
406}
407
409 IncrParser.reset();
410 Act->FinalizeAction();
411 if (DeviceParser)
412 DeviceParser.reset();
413 if (DeviceAct)
414 DeviceAct->FinalizeAction();
415 if (IncrExecutor) {
416 if (llvm::Error Err = IncrExecutor->cleanUp())
417 llvm::report_fatal_error(
418 llvm::Twine("Failed to clean up IncrementalExecutor: ") +
419 toString(std::move(Err)));
420 }
421}
422
423// These better to put in a runtime header but we can't. This is because we
424// can't find the precise resource directory in unittests so we have to hard
425// code them.
426const char *const Runtimes = R"(
427 #define __CLANG_REPL__ 1
428#ifdef __cplusplus
429 #define EXTERN_C extern "C"
430 struct __clang_Interpreter_NewTag{} __ci_newtag;
431 void* operator new(__SIZE_TYPE__, void* __p, __clang_Interpreter_NewTag) noexcept;
432 template <class T, class = T (*)() /*disable for arrays*/>
433 void __clang_Interpreter_SetValueCopyArr(const T* Src, void* Placement, unsigned long Size) {
434 for (unsigned long Idx = 0; Idx < Size; ++Idx)
435 new ((void*)(((T*)Placement) + Idx), __ci_newtag) T(Src[Idx]);
436 }
437 template <class T, unsigned long N>
438 void __clang_Interpreter_SetValueCopyArr(const T (*Src)[N], void* Placement, unsigned long Size) {
439 __clang_Interpreter_SetValueCopyArr(Src[0], Placement, Size);
440 }
441#else
442 #if __STDC_VERSION__ < 199901L
443 #define CI_RESTRICT
444 #define CI_INLINE
445 #else
446 #define CI_RESTRICT restrict
447 #define CI_INLINE inline
448 #endif
449 #define EXTERN_C extern
450 EXTERN_C void *memcpy(void *CI_RESTRICT dst, const void *CI_RESTRICT src, __SIZE_TYPE__ n);
451 EXTERN_C CI_INLINE void __clang_Interpreter_SetValueCopyArr(const void* Src, void* Placement, unsigned long Size) {
452 memcpy(Placement, Src, Size);
453 }
454#endif // __cplusplus
455 EXTERN_C void *__clang_Interpreter_SetValueWithAlloc(void*, void*, void*);
456 EXTERN_C void __clang_Interpreter_SetValueNoAlloc(void *This, void *OutVal, void *OpaqueType, ...);
457)";
458
460 std::unique_ptr<CompilerInstance> CI,
461 std::unique_ptr<IncrementalExecutorBuilder> IEB /*=nullptr*/) {
462 llvm::Error Err = llvm::Error::success();
463
464 auto Interp = std::unique_ptr<Interpreter>(new Interpreter(
465 std::move(CI), Err, std::move(IEB), /*Consumer=*/nullptr));
466 if (auto E = std::move(Err))
467 return std::move(E);
468
469 // Add runtime code and set a marker to hide it from user code. Undo will not
470 // go through that.
471 if (auto E = Interp->ParseAndExecute(Runtimes))
472 return std::move(E);
473
474 Interp->markUserCodeStart();
475
476 return std::move(Interp);
477}
478
480Interpreter::createWithCUDA(std::unique_ptr<CompilerInstance> CI,
481 std::unique_ptr<CompilerInstance> DCI) {
482 return createWithDevice(std::move(CI), std::move(DCI), OffloadType::CUDA);
483}
484
486Interpreter::createWithDevice(std::unique_ptr<CompilerInstance> CI,
487 std::unique_ptr<CompilerInstance> DCI,
490 return llvm::make_error<llvm::StringError>(
491 "Detecting the device vendor is not supported yet.",
492 llvm::inconvertibleErrorCode());
493
494 // avoid writing fat binary to disk using an in-memory virtual file system
496 std::make_unique<llvm::vfs::InMemoryFileSystem>();
498 std::make_unique<llvm::vfs::OverlayFileSystem>(
499 llvm::vfs::getRealFileSystem());
500 OverlayVFS->pushOverlay(IMVFS);
501 CI->createVirtualFileSystem(OverlayVFS);
502 CI->createFileManager();
503
505 Interpreter::create(std::move(CI));
506 if (!InterpOrErr)
507 return InterpOrErr;
508
509 std::unique_ptr<Interpreter> Interp = std::move(*InterpOrErr);
510
511 llvm::Error Err = llvm::Error::success();
512
513 auto DeviceAct = Interp->TSCtx->withContextDo([&](llvm::LLVMContext *Ctx) {
514 return std::make_unique<IncrementalAction>(*DCI, *Ctx, Err, *Interp);
515 });
516
517 if (Err)
518 return std::move(Err);
519
520 Interp->DeviceAct = std::move(DeviceAct);
521
522 if (llvm::Error E = ExecuteIncrementalAction(*DCI, *Interp->DeviceAct))
523 return std::move(E);
524
525 // Set the finalized initial device module aside, as the host path does.
526 Interp->DeviceAct->CacheCodeGenModule();
527
528 Interp->DeviceCI = std::move(DCI);
529
530 std::unique_ptr<IncrementalDeviceParser> DeviceParser;
531 if (Type == OffloadType::HIP)
532 DeviceParser = std::make_unique<IncrementalHIPDeviceParser>(
533 *Interp->DeviceCI, *Interp->getCompilerInstance(),
534 Interp->DeviceAct.get(), IMVFS, Err, Interp->PTUs);
535 else
536 DeviceParser = std::make_unique<IncrementalCUDADeviceParser>(
537 *Interp->DeviceCI, *Interp->getCompilerInstance(),
538 Interp->DeviceAct.get(), IMVFS, Err, Interp->PTUs);
539
540 if (Err)
541 return std::move(Err);
542
543 Interp->DeviceParser = std::move(DeviceParser);
544 return std::move(Interp);
545}
546
549 return const_cast<Interpreter *>(this)->getCompilerInstance();
550}
551
553 if (!IncrExecutor) {
554 if (auto Err = CreateExecutor())
555 return std::move(Err);
556 }
557
558 return *IncrExecutor.get();
559}
560
564
568
569void Interpreter::markUserCodeStart() {
570 assert(!InitPTUSize && "We only do this once");
571 InitPTUSize = PTUs.size();
572}
573
574size_t Interpreter::getEffectivePTUSize() const {
575 assert(PTUs.size() >= InitPTUSize && "empty PTU list?");
576 return PTUs.size() - InitPTUSize;
577}
578
580Interpreter::Parse(llvm::StringRef Code) {
581 // If we have a device parser, parse it first. The generated code will be
582 // included in the host compilation
583 if (DeviceParser) {
584 llvm::Expected<TranslationUnitDecl *> DeviceTU = DeviceParser->Parse(Code);
585 if (auto E = DeviceTU.takeError())
586 return std::move(E);
587
588 DeviceParser->RegisterPTU(*DeviceTU);
589
590 llvm::Error Err = DeviceParser->GenerateOffloadBinary();
591 if (Err)
592 return std::move(Err);
593 }
594
595 // Tell the interpreter sliently ignore unused expressions since value
596 // printing could cause it.
598 clang::diag::warn_unused_expr, diag::Severity::Ignored, SourceLocation());
599
600 llvm::Expected<TranslationUnitDecl *> TuOrErr = IncrParser->Parse(Code);
601 if (!TuOrErr)
602 return TuOrErr.takeError();
603
604 PartialTranslationUnit &LastPTU = IncrParser->RegisterPTU(*TuOrErr);
605
606 // Under -emit-llvm, print the module IR.
607 if (InitPTUSize && LastPTU.TheModule &&
608 getCompilerInstance()->getFrontendOpts().ProgramAction ==
610 LastPTU.TheModule->print(llvm::outs(), /*AAW=*/nullptr);
611
612 return LastPTU;
613}
614
616 if (IncrExecutor)
617 return llvm::make_error<llvm::StringError>("Operation failed. "
618 "Execution engine exists",
619 std::error_code());
620 if (!Act->getCodeGen())
621 return llvm::make_error<llvm::StringError>("Operation failed. "
622 "No code generator available",
623 std::error_code());
624
625 if (!IncrExecutorBuilder)
626 IncrExecutorBuilder = std::make_unique<IncrementalExecutorBuilder>();
627
628 // Propagate mllvm args so the wasm executor can restore them after each
629 // lldMain invocation (which resets all cl options for test isolation).
630 IncrExecutorBuilder->LLVMArgs = CI->getFrontendOpts().LLVMArgs;
631
632 auto ExecutorOrErr = IncrExecutorBuilder->create(*TSCtx, CI->getTarget());
633 if (ExecutorOrErr)
634 IncrExecutor = std::move(*ExecutorOrErr);
635
636 return ExecutorOrErr.takeError();
637}
638
640 assert(T.TheModule);
641 LLVM_DEBUG(
642 llvm::dbgs() << "execute-ptu "
643 << (llvm::is_contained(PTUs, T)
644 ? std::distance(PTUs.begin(), llvm::find(PTUs, T))
645 : -1)
646 << ": [TU=" << T.TUPart << ", M=" << T.TheModule.get()
647 << " (" << T.TheModule->getName() << ")]\n");
648 if (!IncrExecutor) {
649 auto Err = CreateExecutor();
650 if (Err)
651 return Err;
652 }
653 // FIXME: Add a callback to retain the llvm::Module once the JIT is done.
654 if (auto Err = IncrExecutor->addModule(T))
655 return Err;
656
657 if (auto Err = IncrExecutor->runCtors())
658 return Err;
659
660 return llvm::Error::success();
661}
662
663llvm::Error Interpreter::ParseAndExecute(llvm::StringRef Code, Value *V) {
664
665 auto PTU = Parse(Code);
666 if (!PTU)
667 return PTU.takeError();
668 if (PTU->TheModule)
669 if (llvm::Error Err = Execute(*PTU))
670 return Err;
671
672 if (LastValue.isValid()) {
673 if (!V) {
674 LastValue.dump();
675 LastValue.clear();
676 } else
677 *V = std::move(LastValue);
678 }
679 return llvm::Error::success();
680}
681
684 if (!IncrExecutor)
685 return llvm::make_error<llvm::StringError>("Operation failed. "
686 "No execution engine",
687 std::error_code());
688 llvm::StringRef MangledName = Act->getCodeGen()->GetMangledName(GD);
689 return getSymbolAddress(MangledName);
690}
691
693Interpreter::getSymbolAddress(llvm::StringRef IRName) const {
694 if (!IncrExecutor)
695 return llvm::make_error<llvm::StringError>("Operation failed. "
696 "No execution engine",
697 std::error_code());
698
699 return IncrExecutor->getSymbolAddress(IRName, IncrementalExecutor::IRName);
700}
701
704 if (!IncrExecutor)
705 return llvm::make_error<llvm::StringError>("Operation failed. "
706 "No execution engine",
707 std::error_code());
708
709 return IncrExecutor->getSymbolAddress(Name, IncrementalExecutor::LinkerName);
710}
711
712llvm::Error Interpreter::Undo(unsigned N) {
713
714 if (getEffectivePTUSize() == 0) {
715 return llvm::make_error<llvm::StringError>("Operation failed. "
716 "No input left to undo",
717 std::error_code());
718 } else if (N > getEffectivePTUSize()) {
719 return llvm::make_error<llvm::StringError>(
720 llvm::formatv(
721 "Operation failed. Wanted to undo {0} inputs, only have {1}.", N,
722 getEffectivePTUSize()),
723 std::error_code());
724 }
725
726 for (unsigned I = 0; I < N; I++) {
727 if (IncrExecutor) {
728 if (llvm::Error Err = IncrExecutor->removeModule(PTUs.back()))
729 return Err;
730 }
731
732 IncrParser->CleanUpPTU(PTUs.back().TUPart);
733 PTUs.pop_back();
734 }
735 return llvm::Error::success();
736}
737
738llvm::Error Interpreter::LoadDynamicLibrary(const char *name) {
739 auto EEOrErr = getExecutionEngine();
740 if (!EEOrErr)
741 return EEOrErr.takeError();
742
743 return EEOrErr->LoadDynamicLibrary(name);
744}
745} // end namespace clang
Defines the clang::ASTContext interface.
#define V(N, I)
Defines the clang::FileManager interface and associated types.
Defines the clang::FrontendAction interface and various convenience abstract classes (clang::ASTFront...
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
Abstract interface for callback invocations by the ASTReader.
Definition ASTReader.h:117
static bool readASTFileControlBlock(StringRef Filename, FileManager &FileMgr, const ModuleCache &ModCache, const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions, ASTReaderListener &Listener, bool ValidateDiagnosticOptions, unsigned ClientLoadCapabilities=ARR_ConfigurationMismatch|ARR_OutOfDate)
Read the control block for the named AST file.
CompilerInstance - Helper class for managing a single instance of the Clang compiler.
const PCHContainerReader & getPCHContainerReader() const
Return the appropriate PCHContainerReader depending on the current CodeGenOptions.
DiagnosticsEngine & getDiagnostics() const
Get the current diagnostics engine.
FileSystemOptions & getFileSystemOpts()
ASTContext & getASTContext() const
IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVirtualFileSystemPtr() const
bool ExecuteAction(FrontendAction &Act)
ExecuteAction - Execute the provided action against the compiler's CompilerInvocation object.
static bool CreateFromArgs(CompilerInvocation &Res, ArrayRef< const char * > CommandLineArgs, DiagnosticsEngine &Diags, const char *Argv0=nullptr)
Create a compiler invocation from a list of input options.
static llvm::IntrusiveRefCntPtr< DiagnosticIDs > create()
Options for controlling the compiler diagnostics engine.
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:241
bool hasErrorOccurred() const
Definition Diagnostic.h:913
void setSeverity(diag::kind Diag, diag::Severity Map, SourceLocation Loc)
This allows the client to specify that certain warnings are ignored.
Implements support for file system lookup, file system caching, and directory search management.
Definition FileManager.h:57
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:60
A custom action enabling the incremental processing functionality.
llvm::Expected< std::unique_ptr< CompilerInstance > > CreateCudaHost()
llvm::Expected< std::unique_ptr< CompilerInstance > > CreateCudaDevice()
llvm::Expected< std::unique_ptr< CompilerInstance > > CreateCpp()
llvm::Expected< IncrementalExecutor & > getExecutionEngine()
llvm::Error ParseAndExecute(llvm::StringRef Code, Value *V=nullptr)
static llvm::Expected< std::unique_ptr< Interpreter > > create(std::unique_ptr< CompilerInstance > CI, std::unique_ptr< IncrementalExecutorBuilder > IEB=nullptr)
llvm::Error CreateExecutor()
llvm::Expected< llvm::orc::ExecutorAddr > getSymbolAddress(GlobalDecl GD) const
llvm::Error LoadDynamicLibrary(const char *name)
Link a dynamic library.
static llvm::Expected< std::unique_ptr< Interpreter > > createWithCUDA(std::unique_ptr< CompilerInstance > CI, std::unique_ptr< CompilerInstance > DCI)
llvm::Expected< PartialTranslationUnit & > Parse(llvm::StringRef Code)
llvm::Expected< llvm::orc::ExecutorAddr > getSymbolAddressFromLinkerName(llvm::StringRef LinkerName) const
Interpreter(std::unique_ptr< CompilerInstance > Instance, llvm::Error &Err, std::unique_ptr< IncrementalExecutorBuilder > IEB=nullptr, std::unique_ptr< clang::ASTConsumer > Consumer=nullptr)
llvm::Error Undo(unsigned N=1)
Undo N previous incremental inputs.
const CompilerInstance * getCompilerInstance() const
static llvm::Expected< std::unique_ptr< Interpreter > > createWithDevice(std::unique_ptr< CompilerInstance > CI, std::unique_ptr< CompilerInstance > DCI, OffloadType Type=OffloadType::Detect)
const ASTContext & getASTContext() const
friend class Value
llvm::Error Execute(PartialTranslationUnit &T)
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
A processor an offloading action can target.
Definition OffloadArch.h:32
Encodes a location in the source.
static TargetInfo * CreateTargetInfo(DiagnosticsEngine &Diags, TargetOptions &Opts)
Construct a target for the given options.
Definition Targets.cpp:840
void FlushDiagnostics(DiagnosticsEngine &Diags) const
FlushDiagnostics - Flush the buffered diagnostics to an given diagnostic engine.
The base class of the type hierarchy.
Definition TypeBase.h:1879
Command - An executable path/name and argument vector to execute.
Definition Job.h:107
const Tool & getCreator() const
getCreator - Return the Tool which caused the creation of this job.
Definition Job.h:199
const llvm::opt::ArgStringList & getArguments() const
Definition Job.h:243
Compilation - A set of tasks to perform for a single driver invocation.
Definition Compilation.h:46
JobList - A sequence of jobs to perform.
Definition Job.h:279
size_type size() const
Definition Job.h:305
iterator begin()
Definition Job.h:306
const char * getName() const
Definition Tool.h:48
Defines the clang::TargetInfo interface.
@ Ignored
Do not present this diagnostic, ignore it.
@ EmitLLVM
Emit a .ll file.
Top level wrappers for InstallAPI frontend operations.
std::unique_ptr< DiagnosticOptions > CreateAndPopulateDiagOpts(ArrayRef< const char * > Argv)
OffloadType
The device language to offload to.
Definition Interpreter.h:51
@ Success
Annotation was successful.
Definition Parser.h:65
std::shared_ptr< ModuleCache > createCrossProcessModuleCache()
Creates new ModuleCache backed by a file system directory that may be operated on by multiple process...
@ Parse
Parse the block; this code is always used.
Definition Parser.h:137
const char *const Runtimes
const FunctionProtoType * T
std::string GetResourcesPath(StringRef BinaryPath)
Get the directory where the compiler headers reside, relative to the compiler binary path BinaryPath.
bool(*)(llvm::ArrayRef< const char * >, llvm::raw_ostream &, llvm::raw_ostream &, bool, bool) Driver
Definition Wasm.cpp:38
The class keeps track of various objects created as part of processing incremental inputs.
std::unique_ptr< llvm::Module > TheModule
The llvm IR produced for the input.