48#include "llvm/ADT/StringExtras.h"
49#include "llvm/ExecutionEngine/JITSymbol.h"
50#include "llvm/ExecutionEngine/Orc/EPCDynamicLibrarySearchGenerator.h"
51#include "llvm/ExecutionEngine/Orc/LLJIT.h"
52#include "llvm/IR/Module.h"
53#include "llvm/Support/Errc.h"
54#include "llvm/Support/ErrorHandling.h"
55#include "llvm/Support/Process.h"
56#include "llvm/Support/VirtualFileSystem.h"
57#include "llvm/Support/raw_ostream.h"
58#include "llvm/TargetParser/Host.h"
59#include "llvm/TargetParser/Triple.h"
60#include "llvm/Transforms/Utils/Cloning.h"
62#define DEBUG_TYPE "clang-repl"
77 return llvm::createStringError(llvm::errc::not_supported,
78 "Driver initialization failed. "
79 "Unable to create a driver job");
84 return llvm::createStringError(llvm::errc::not_supported,
85 "Driver initialization failed");
96 PICLevelReader(
unsigned &PICLevel) : PICLevel(PICLevel) {}
98 bool ReadLanguageOptions(
const LangOptions &LangOpts,
99 StringRef ModuleFilename,
bool Complain,
100 bool AllowCompatibleDifferences)
override {
101 PICLevel = LangOpts.PICLevel;
116 StringRef Filename) {
120 unsigned ASTPICLevel = 0;
121 PICLevelReader Reader(ASTPICLevel);
127 return llvm::createStringError(
128 llvm::errc::not_supported,
129 "AST file '%s' was built with PIC level %u, which is incompatible "
130 "with clang-repl's PIC level %u",
131 Filename.str().c_str(), ASTPICLevel, Clang.
getLangOpts().PICLevel);
132 return llvm::Error::success();
136CreateCI(
const llvm::opt::ArgStringList &Argv) {
141 auto PCHOps = Clang->getPCHContainerOperations();
142 PCHOps->registerWriter(std::make_unique<ObjectFilePCHContainerWriter>());
143 PCHOps->registerReader(std::make_unique<ObjectFilePCHContainerReader>());
151 Clang->getInvocation(),
llvm::ArrayRef(Argv.begin(), Argv.size()), Diags);
154 if (Clang->getHeaderSearchOpts().UseBuiltinIncludes &&
155 Clang->getHeaderSearchOpts().ResourceDir.empty())
156 Clang->getHeaderSearchOpts().ResourceDir =
159 Clang->createVirtualFileSystem();
162 Clang->createDiagnostics();
166 return llvm::createStringError(llvm::errc::not_supported,
167 "Initialization failed. "
168 "Unable to flush diagnostics");
171 llvm::MemoryBuffer *MB = llvm::MemoryBuffer::getMemBuffer(
"").release();
172 Clang->getPreprocessorOpts().addRemappedFile(
"<<< inputs >>>", MB);
175 Clang->getDiagnostics(), Clang->getInvocation().getTargetOpts()));
176 if (!Clang->hasTarget())
177 return llvm::createStringError(llvm::errc::not_supported,
178 "Initialization failed. "
179 "Target is missing");
181 Clang->getTarget().adjust(Clang->getDiagnostics(), Clang->getLangOpts(),
182 Clang->getAuxTarget());
186 Clang->getCodeGenOpts().ClearASTBeforeBackend =
false;
188 Clang->getFrontendOpts().DisableFree =
false;
189 Clang->getCodeGenOpts().DisableFree =
false;
194 StringRef PCHInclude = Clang->getPreprocessorOpts().ImplicitPCHInclude;
195 if (!PCHInclude.empty())
196 if (llvm::Error Err = checkASTFilePICLevel(*Clang, PCHInclude))
197 return std::move(Err);
201 for (StringRef ModuleFile : Clang->getFrontendOpts().ModuleFiles)
202 if (llvm::Error Err = checkASTFilePICLevel(*Clang, ModuleFile))
203 return std::move(Err);
204 for (
const auto &NameAndFile :
205 Clang->getHeaderSearchOpts().PrebuiltModuleFiles)
206 if (llvm::Error Err = checkASTFilePICLevel(*Clang, NameAndFile.second))
207 return std::move(Err);
209 return std::move(Clang);
215 return llvm::createStringError(llvm::errc::not_supported,
216 "Failed to execute incremental action");
218 return llvm::Error::success();
226IncrementalCompilerBuilder::create(std::string TT,
227 std::vector<const char *> &ClangArgv) {
231 std::string MainExecutableName =
232 llvm::sys::fs::getMainExecutable(
nullptr,
nullptr);
234 ClangArgv.insert(ClangArgv.begin(), MainExecutableName.c_str());
248 llvm::Triple TargetTriple(TT);
249 if (!TargetTriple.isOSWindows() || TargetTriple.isOSCygMing())
250 ClangArgv.insert(ClangArgv.begin() + 1,
"-fPIC");
257 ClangArgv.insert(ClangArgv.end(),
"-Xclang");
258 ClangArgv.insert(ClangArgv.end(),
"-fincremental-extensions");
259 ClangArgv.insert(ClangArgv.end(),
"-c");
263 ClangArgv.push_back(
"<<< inputs >>>");
267 std::unique_ptr<DiagnosticOptions> DiagOpts =
269 TextDiagnosticBuffer *DiagsBuffer =
new TextDiagnosticBuffer;
272 driver::Driver
Driver(ClangArgv[0], TT, Diags);
273 Driver.setCheckInputsExist(
false);
274 llvm::ArrayRef<const char *> RF = llvm::ArrayRef(ClangArgv);
275 std::unique_ptr<driver::Compilation> Compilation(
Driver.BuildCompilation(RF));
278 if (
auto Err = (*CompilationCB)(*Compilation.get()))
279 return std::move(Err);
281 if (Compilation->getArgs().hasArg(options::OPT_v))
282 Compilation->getJobs().Print(llvm::errs(),
"\n",
false);
284 auto ErrOrCC1Args = GetCC1Arguments(&Diags, Compilation.get());
285 if (
auto Err = ErrOrCC1Args.takeError())
286 return std::move(Err);
288 return CreateCI(**ErrOrCC1Args);
293 std::string TT = TargetTriple ? *TargetTriple : llvm::sys::getProcessTriple();
295 std::vector<const char *> Argv;
296 Argv.reserve(5 + 1 + UserArgs.size());
297 Argv.push_back(
"-xc++");
299 Argv.push_back(
"-target");
300 Argv.push_back(TT.c_str());
301 Argv.push_back(
"-fvisibility=default");
303 llvm::append_range(Argv, UserArgs);
305 return IncrementalCompilerBuilder::create(TT, Argv);
309IncrementalCompilerBuilder::createOffload(
OffloadType Type,
bool device) {
311 std::vector<const char *> Argv;
312 Argv.reserve(5 + 4 + UserArgs.size());
313 Argv.push_back(HipEnabled ?
"-xhip" :
"-xcuda");
314 Argv.push_back(device ?
"--cuda-device-only" :
"--cuda-host-only");
316 llvm::StringRef SDKPath = HipEnabled ? RocmSDKPath : CudaSDKPath;
317 std::string SDKPathArg = HipEnabled ?
"--rocm-path=" :
"--cuda-path=";
318 if (!SDKPath.empty()) {
319 SDKPathArg += SDKPath;
320 Argv.push_back(SDKPathArg.c_str());
323 std::string ArchArg =
"--offload-arch=";
326 Argv.push_back(ArchArg.c_str());
329 if (OffloadCUID.empty())
330 OffloadCUID = llvm::utohexstr(llvm::sys::Process::GetRandomNumber(),
332 std::string CUIDArg =
"-cuid=" + OffloadCUID;
333 Argv.push_back(CUIDArg.c_str());
335 llvm::append_range(Argv, UserArgs);
337 std::string TT = TargetTriple ? *TargetTriple : llvm::sys::getProcessTriple();
338 return IncrementalCompilerBuilder::create(TT, Argv);
343 return IncrementalCompilerBuilder::createOffload(
Type,
true);
348 return IncrementalCompilerBuilder::createOffload(
Type,
false);
353 std::unique_ptr<IncrementalExecutorBuilder> IEB,
354 std::unique_ptr<clang::ASTConsumer> Consumer)
355 : IncrExecutorBuilder(
std::move(IEB)) {
356 CI = std::move(Instance);
357 llvm::ErrorAsOutParameter EAO(&ErrOut);
358 auto LLVMCtx = std::make_unique<llvm::LLVMContext>();
359 TSCtx = std::make_unique<llvm::orc::ThreadSafeContext>(std::move(LLVMCtx));
361 Act = TSCtx->withContextDo([&](llvm::LLVMContext *Ctx) {
362 return std::make_unique<IncrementalAction>(*CI, *Ctx, ErrOut, *
this,
363 std::move(Consumer));
369 if (llvm::Error E = ExecuteIncrementalAction(*CI, *Act)) {
370 ErrOut = joinErrors(std::move(ErrOut), std::move(E));
375 std::make_unique<IncrementalParser>(*CI, Act.get(), ErrOut, PTUs);
380 if (Act->getCodeGen()) {
381 Act->CacheCodeGenModule();
384 if (!CI->getPreprocessorOpts().Includes.empty() ||
385 !CI->getPreprocessorOpts().ImplicitPCHInclude.empty()) {
389 auto M = llvm::CloneModule(*Act->getCachedCodeGenModule());
391 IncrParser->RegisterPTU(
C.getTranslationUnitDecl(), std::move(M));
394 ErrOut = joinErrors(std::move(ErrOut), std::move(Err));
400 if (Act->getCodeGen()) {
404 if (llvm::Error Err =
Execute(PTU)) {
405 ErrOut = joinErrors(std::move(ErrOut), std::move(Err));
413 Act->FinalizeAction();
415 DeviceParser.reset();
417 DeviceAct->FinalizeAction();
419 if (llvm::Error Err = IncrExecutor->cleanUp())
420 llvm::report_fatal_error(
421 llvm::Twine(
"Failed to clean up IncrementalExecutor: ") +
430 #define __CLANG_REPL__ 1
432 #define EXTERN_C extern "C"
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(const T* Src, void* Placement, unsigned long Size) {
437 for (unsigned long Idx = 0; Idx < Size; ++Idx)
438 new ((void*)(((T*)Placement) + Idx), __ci_newtag) T(Src[Idx]);
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);
445 #if __STDC_VERSION__ < 199901L
449 #define CI_RESTRICT restrict
450 #define CI_INLINE inline
452 #define EXTERN_C extern
453 EXTERN_C void *memcpy(void *CI_RESTRICT dst, const void *CI_RESTRICT src, __SIZE_TYPE__ n);
454 EXTERN_C CI_INLINE void __clang_Interpreter_SetValueCopyArr(const void* Src, void* Placement, unsigned long Size) {
455 memcpy(Placement, Src, Size);
458 EXTERN_C void *__clang_Interpreter_SetValueWithAlloc(void*, void*, void*);
459 EXTERN_C void __clang_Interpreter_SetValueNoAlloc(void *This, void *OutVal, void *OpaqueType, ...);
463 std::unique_ptr<CompilerInstance> CI,
464 std::unique_ptr<IncrementalExecutorBuilder> IEB ) {
465 llvm::Error Err = llvm::Error::success();
467 auto Interp = std::unique_ptr<Interpreter>(
new Interpreter(
468 std::move(CI), Err, std::move(IEB),
nullptr));
469 if (
auto E = std::move(Err))
474 if (
auto E = Interp->ParseAndExecute(
Runtimes))
477 Interp->markUserCodeStart();
479 return std::move(Interp);
484 std::unique_ptr<CompilerInstance> CI,
485 std::unique_ptr<CompilerInstance> DCI) {
488 std::make_unique<llvm::vfs::InMemoryFileSystem>();
490 std::make_unique<llvm::vfs::OverlayFileSystem>(
491 llvm::vfs::getRealFileSystem());
492 OverlayVFS->pushOverlay(IMVFS);
493 CI->createVirtualFileSystem(OverlayVFS);
494 CI->createFileManager();
501 std::unique_ptr<Interpreter> Interp = std::move(*InterpOrErr);
503 llvm::Error Err = llvm::Error::success();
505 auto DeviceAct = Interp->TSCtx->withContextDo([&](llvm::LLVMContext *Ctx) {
506 return std::make_unique<IncrementalAction>(*DCI, *Ctx, Err, *Interp);
510 return std::move(Err);
512 Interp->DeviceAct = std::move(DeviceAct);
514 if (llvm::Error E = ExecuteIncrementalAction(*DCI, *Interp->DeviceAct))
517 Interp->DeviceCI = std::move(DCI);
523 auto DeviceParser = std::make_unique<IncrementalCUDADeviceParser>(
524 *Interp->DeviceCI, *Interp->getCompilerInstance(),
525 Interp->DeviceAct.get(), IMVFS, Err, Interp->PTUs);
528 return std::move(Err);
530 Interp->DeviceParser = std::move(DeviceParser);
533 return std::move(Interp);
544 return std::move(Err);
547 return *IncrExecutor.get();
558void Interpreter::markUserCodeStart() {
559 assert(!InitPTUSize &&
"We only do this once");
560 InitPTUSize = PTUs.size();
563size_t Interpreter::getEffectivePTUSize()
const {
564 assert(PTUs.size() >= InitPTUSize &&
"empty PTU list?");
565 return PTUs.size() - InitPTUSize;
574 if (
auto E = DeviceTU.takeError())
577 DeviceParser->RegisterPTU(*DeviceTU);
581 return PTX.takeError();
583 llvm::Error Err = DeviceParser->GenerateFatbinary();
585 return std::move(Err);
595 return TuOrErr.takeError();
603 LastPTU.
TheModule->print(llvm::outs(),
nullptr);
610 return llvm::make_error<llvm::StringError>(
"Operation failed. "
611 "Execution engine exists",
613 if (!Act->getCodeGen())
614 return llvm::make_error<llvm::StringError>(
"Operation failed. "
615 "No code generator available",
618 if (!IncrExecutorBuilder)
619 IncrExecutorBuilder = std::make_unique<IncrementalExecutorBuilder>();
621 auto ExecutorOrErr = IncrExecutorBuilder->create(*TSCtx, CI->getTarget());
623 IncrExecutor = std::move(*ExecutorOrErr);
625 return ExecutorOrErr.takeError();
631 llvm::dbgs() <<
"execute-ptu "
632 << (llvm::is_contained(PTUs,
T)
633 ? std::distance(PTUs.begin(), llvm::find(PTUs,
T))
635 <<
": [TU=" <<
T.TUPart <<
", M=" <<
T.TheModule.get()
636 <<
" (" <<
T.TheModule->getName() <<
")]\n");
643 if (
auto Err = IncrExecutor->addModule(
T))
646 if (
auto Err = IncrExecutor->runCtors())
649 return llvm::Error::success();
654 auto PTU =
Parse(Code);
656 return PTU.takeError();
658 if (llvm::Error Err =
Execute(*PTU))
661 if (LastValue.isValid()) {
666 *
V = std::move(LastValue);
668 return llvm::Error::success();
674 return llvm::make_error<llvm::StringError>(
"Operation failed. "
675 "No execution engine",
677 llvm::StringRef MangledName = Act->getCodeGen()->GetMangledName(GD);
684 return llvm::make_error<llvm::StringError>(
"Operation failed. "
685 "No execution engine",
694 return llvm::make_error<llvm::StringError>(
"Operation failed. "
695 "No execution engine",
703 if (getEffectivePTUSize() == 0) {
704 return llvm::make_error<llvm::StringError>(
"Operation failed. "
705 "No input left to undo",
707 }
else if (N > getEffectivePTUSize()) {
708 return llvm::make_error<llvm::StringError>(
710 "Operation failed. Wanted to undo {0} inputs, only have {1}.", N,
711 getEffectivePTUSize()),
715 for (
unsigned I = 0; I < N; I++) {
717 if (llvm::Error Err = IncrExecutor->removeModule(PTUs.back()))
721 IncrParser->CleanUpPTU(PTUs.back().TUPart);
724 return llvm::Error::success();
730 return EEOrErr.takeError();
732 return EEOrErr->LoadDynamicLibrary(name);
Defines the clang::ASTContext interface.
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 ...
Abstract interface for callback invocations by the ASTReader.
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.
LangOptions & getLangOpts()
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.
bool hasErrorOccurred() const
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.
GlobalDecl - represents a global declaration.
A custom action enabling the incremental processing functionality.
llvm::Expected< std::unique_ptr< CompilerInstance > > CreateCpp()
llvm::Expected< std::unique_ptr< CompilerInstance > > CreateHost(OffloadType Type)
llvm::Expected< std::unique_ptr< CompilerInstance > > CreateDevice(OffloadType Type)
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.
llvm::Expected< PartialTranslationUnit & > Parse(llvm::StringRef Code)
llvm::Expected< llvm::orc::ExecutorAddr > getSymbolAddressFromLinkerName(llvm::StringRef LinkerName) const
static llvm::Expected< std::unique_ptr< Interpreter > > createWithDevice(OffloadType Type, std::unique_ptr< CompilerInstance > CI, std::unique_ptr< CompilerInstance > DCI)
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
const ASTContext & getASTContext() const
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.
Encodes a location in the source.
static TargetInfo * CreateTargetInfo(DiagnosticsEngine &Diags, TargetOptions &Opts)
Construct a target for the given options.
void FlushDiagnostics(DiagnosticsEngine &Diags) const
FlushDiagnostics - Flush the buffered diagnostics to an given diagnostic engine.
The base class of the type hierarchy.
Command - An executable path/name and argument vector to execute.
const Tool & getCreator() const
getCreator - Return the Tool which caused the creation of this job.
const llvm::opt::ArgStringList & getArguments() const
Compilation - A set of tasks to perform for a single driver invocation.
JobList - A sequence of jobs to perform.
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)
@ Success
Annotation was successful.
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.
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
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.