17#include "cling/Interpreter/DynamicLibraryManager.h"
18#include "cling/Interpreter/Interpreter.h"
19#include "cling/Interpreter/InterpreterCallbacks.h"
20#include "cling/Interpreter/Transaction.h"
21#include "cling/Utils/AST.h"
23#include "clang/AST/ASTConsumer.h"
24#include "clang/AST/ASTContext.h"
25#include "clang/AST/DeclBase.h"
26#include "clang/AST/DeclTemplate.h"
27#include "clang/AST/GlobalDecl.h"
28#include "clang/Frontend/CompilerInstance.h"
29#include "clang/Lex/HeaderSearch.h"
30#include "clang/Lex/PPCallbacks.h"
31#include "clang/Lex/Preprocessor.h"
32#include "clang/Parse/Parser.h"
33#include "clang/Sema/Lookup.h"
34#include "clang/Sema/Scope.h"
35#include "clang/Serialization/ASTReader.h"
36#include "clang/Serialization/GlobalModuleIndex.h"
37#include "clang/Basic/DiagnosticSema.h"
39#include "llvm/ExecutionEngine/Orc/AbsoluteSymbols.h"
40#include "llvm/ExecutionEngine/Orc/Core.h"
42#include "llvm/Support/Error.h"
43#include "llvm/Support/FileSystem.h"
44#include "llvm/Support/Path.h"
45#include "llvm/Support/Process.h"
75 std::string &args, std::string &io, std::string &fname);
79 llvm::StringRef canonicalName);
81 llvm::StringRef canonicalName);
96 llvm::Error
tryToGenerate(llvm::orc::LookupState &LS, llvm::orc::LookupKind K, llvm::orc::JITDylib &JD,
97 llvm::orc::JITDylibLookupFlags JDLookupFlags,
98 const llvm::orc::SymbolLookupSet &Symbols)
override
108 return llvm::Error::success();
114 std::unordered_map<std::string, llvm::orc::SymbolNameVector> found;
119 for (
auto &&KV : Symbols) {
120 llvm::orc::SymbolStringPtr
name = KV.first;
122 const cling::DynamicLibraryManager &DLM = *
fInterpreter->getDynamicLibraryManager();
124 std::string libName = DLM.searchLibrariesForSymbol((*name).str(),
128 assert(libName.find(
"/libNew.") == std::string::npos &&
"We must not autoload libNew!");
134 assert(libName.find(
"/libCling.") == std::string::npos &&
"Must not autoload libCling!");
136 if (!libName.empty())
137 found[libName].push_back(
name);
140 llvm::orc::SymbolMap loadedSymbols;
141 for (
const auto &KV : found) {
148 for (
const auto &symbol : KV.second) {
149 std::string symbolStr = (*symbol).str();
152 void *addr = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(nameForDlsym);
154 loadedSymbols[symbol] = {llvm::orc::ExecutorAddr::fromPtr(addr), llvm::JITSymbolFlags::Exported};
159 if (!loadedSymbols.empty()) {
160 return JD.define(absoluteSymbols(std::move(loadedSymbols)));
163 return llvm::Error::success();
170 Transaction* T =
nullptr;
171 m_Interpreter->declare(
"namespace __ROOT_SpecialObjects{}", &T);
174 interp->addGenerator(std::make_unique<AutoloadLibraryGenerator>(interp, *
this));
182 const clang::Token &,
183 llvm::StringRef FileName,
185 clang::CharSourceRange ,
186 clang::OptionalFileEntryRef FE,
189 const clang::Module * Imported,
191 clang::SrcMgr::CharacteristicKind FileType) {
193 Sema &SemaR = m_Interpreter->getSema();
196 if (!SemaR.isModuleVisible(Imported))
198 "Module %s resolved but not visible!", Imported->Name.c_str());
214 bool isHeaderFile = FileName.ends_with(
".h") || FileName.ends_with(
".hxx") || FileName.ends_with(
".hpp");
218 std::string localString(FileName.str());
220 DeclarationName Name = &SemaR.getASTContext().Idents.get(localString.c_str());
221 LookupResult RHeader(SemaR, Name, sLoc, Sema::LookupOrdinaryName);
228 bool permanent,
bool resolved) {
243 Preprocessor& PP = m_Interpreter->getCI()->getPreprocessor();
246 std::string
filename(FileName.str().substr(0,FileName.str().find_last_of(
'"')));
247 std::string fname,
mode, arguments, io;
250 if (
mode.length() > 0) {
251 if (llvm::sys::fs::exists(fname)) {
253 std::string options =
"k";
254 if (
mode.find(
"++") != std::string::npos) options +=
"f";
255 if (
mode.find(
"g") != std::string::npos) options +=
"g";
256 if (
mode.find(
"O") != std::string::npos) options +=
"O";
259 Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP);
260 Parser& P =
const_cast<Parser&
>(m_Interpreter->getParser());
262 clang::Parser::ParserCurTokRestoreRAII fSavedCurToken(P);
266 Token& Tok =
const_cast<Token&
>(P.getCurToken());
267 Tok.setKind(tok::semi);
279 Sema& SemaR = m_Interpreter->getSema();
280 ASTContext& C = SemaR.getASTContext();
281 Sema::ContextAndScopeRAII pushedDCAndS(SemaR, C.getTranslationUnitDecl(),
299 DeclContext* DC = S->getEntity();
308 clang::DeclContext* MaybeTU = DC;
309 while (MaybeTU && !isa<TranslationUnitDecl>(MaybeTU)) {
311 MaybeTU = MaybeTU->getParent();
313 return isa<FunctionDecl>(DC);
331 if (m_Interpreter->getSema().getDiagnostics().hasErrorOccurred())
369 std::optional<std::string> envUseGMI = llvm::sys::Process::GetEnv(
"ROOT_USE_GMI");
370 if (envUseGMI.has_value())
374 const CompilerInstance *CI = m_Interpreter->getCI();
375 const LangOptions &LangOpts = CI->getPreprocessor().getLangOpts();
377 if (!LangOpts.Modules)
381 if (LangOpts.isCompilingModule())
391 Sema &SemaR = m_Interpreter->getSema();
392 if (SemaR.inTemplateInstantiation())
395 GlobalModuleIndex *Index = CI->getASTReader()->getGlobalIndex();
401 GlobalModuleIndex::FileNameHitSet FoundModules;
405 if (Index->lookupIdentifier(Name.getAsString(), FoundModules)) {
406 for (llvm::StringRef FileName : FoundModules) {
407 StringRef ModuleName = llvm::sys::path::stem(FileName);
412 llvm::errs() <<
"Module '" << ModuleName <<
"' already loaded"
413 <<
" for '" << Name.getAsString() <<
"'\n";
419 llvm::errs() <<
"Loading '" << ModuleName <<
"' on demand"
420 <<
" for '" << Name.getAsString() <<
"'\n";
422 m_Interpreter->loadModule(ModuleName.str());
425 if (loadFirstMatchOnly)
445 if (
Name.getNameKind() != DeclarationName::Identifier)
448 Sema &SemaR = m_Interpreter->getSema();
449 auto *D = cast<Decl>(DC);
450 SourceLocation Loc = D->getLocation();
451 if (Loc.isValid() && SemaR.getSourceManager().isInSystemHeader(Loc)) {
460 NamespaceDecl* NSD = dyn_cast<NamespaceDecl>(
const_cast<DeclContext*
>(DC));
471 const DeclContext* primaryDC = NSD->getPrimaryContext();
475 LookupResult
R(SemaR, Name, SourceLocation(), Sema::LookupOrdinaryName);
476 R.suppressDiagnostics();
479 = NSD->getQualifiedNameAsString() +
"::" +
Name.getAsString();
485 clang::Scope
S(SemaR.TUScope, clang::Scope::DeclScope, SemaR.getDiagnostics());
486 S.setEntity(
const_cast<DeclContext*
>(DC));
487 Sema::ContextAndScopeRAII pushedDCAndS(SemaR,
const_cast<DeclContext*
>(DC), &S);
490 llvm::SmallVector<NamedDecl*, 4> lookupResults;
491 for(LookupResult::iterator I =
R.begin(), E =
R.end(); I <
E; ++I)
492 lookupResults.push_back(*I);
493 UpdateWithNewDecls(DC, Name, llvm::ArrayRef(lookupResults.data(), lookupResults.size()));
514 Sema &SemaR = m_Interpreter->getSema();
516 SourceLocation Loc = Tag->getLocation();
517 if (SemaR.getSourceManager().isInSystemHeader(Loc)) {
523 for (
auto ReRD: Tag->redecls()) {
525 if (ReRD->isBeingDefined())
530 if (RecordDecl* RD = dyn_cast<RecordDecl>(Tag)) {
531 ASTContext& C = SemaR.getASTContext();
532 Parser& P =
const_cast<Parser&
>(m_Interpreter->getParser());
541 C.getCanonicalTagType(RD),
547 Tag->setHasExternalLexicalStorage(
false);
563 Scope *S, clang::OptionalFileEntryRef FE) {
569 Sema &SemaR = m_Interpreter->getSema();
578 Sema::LookupNameKind kind =
R.getLookupKind();
579 if (!(kind == Sema::LookupTagName || kind == Sema::LookupOrdinaryName
580 || kind == Sema::LookupNestedNameSpecifierName
581 || kind == Sema::LookupNamespaceName))
586 bool lookupSuccess =
false;
588 Parser &P =
const_cast<Parser &
>(m_Interpreter->getParser());
595 lookupSuccess = SemaR.LookupName(
R, S);
597 if (
R.isSingleResult()) {
598 if (isa<clang::RecordDecl>(
R.getFoundDecl())) {
614 lookupSuccess = FE || SemaR.LookupName(
R, S);
620 std::string incl =
"#include \"";
621 incl += FE->getName();
623 m_Interpreter->declare(incl);
659 if (
R.isForRedeclaration())
664 const Sema::LookupNameKind LookupKind =
R.getLookupKind();
665 if (LookupKind != Sema::LookupOrdinaryName)
669 Sema &SemaR = m_Interpreter->getSema();
670 ASTContext& C = SemaR.getASTContext();
671 Preprocessor &PP = SemaR.getPreprocessor();
672 DeclContext *CurDC = SemaR.CurContext;
673 DeclarationName Name =
R.getLookupName();
676 if(!CurDC || !CurDC->isFunctionOrMethod())
681 Preprocessor::CleanupAndRestoreCacheRAII cleanupPPRAII(PP);
688#if defined(R__MUST_REVISIT)
689#if R__MUST_REVISIT(6,2)
694 if (!fgSetOfSpecials) {
695 fgSetOfSpecials =
new std::set<TObject*>;
697 ((std::set<TObject*>*)fgSetOfSpecials)->insert((
TObject*)*obj);
701 VarDecl *VD = cast_or_null<VarDecl>(utils::Lookup::Named(&SemaR, Name,
706 TObject **address = (
TObject**)m_Interpreter->getAddressOfGlobal(GD);
710 CStyleCastExpr *CStyleCast = cast<CStyleCastExpr>(VD->getInit());
711 Expr* newInit = utils::Synthesize::IntegerLiteralExpr(C, (uint64_t)obj);
712 CStyleCast->setSubExpr(newInit);
719 Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP);
723 QualType QT = C.getPointerType(C.getTypeDeclType(cast<TypeDecl>(TD)));
726 SourceLocation(), Name.getAsIdentifierInfo(), QT,
730 = utils::Synthesize::CStyleCastPtrExpr(&SemaR, QT, (uint64_t)obj);
735 cling::CompilationOptions CO;
736 CO.DeclarationExtraction = 0;
737 CO.ValuePrinting = CompilationOptions::VPDisabled;
738 CO.ResultEvaluation = 0;
739 CO.DynamicScoping = 0;
741 CO.CodeGeneration = 1;
743 cling::Transaction* T =
new cling::Transaction(CO, SemaR);
745 T->setState(cling::Transaction::kCompleted);
747 m_Interpreter->emitAllDecls(T);
749 assert(VD &&
"Cannot be null!");
766 DeclarationName Name =
R.getLookupName();
767 IdentifierInfo* II = Name.getAsIdentifierInfo();
768 SourceLocation Loc =
R.getNameLoc();
769 Sema& SemaRef =
R.getSema();
770 ASTContext& C = SemaRef.getASTContext();
771 DeclContext* TU = C.getTranslationUnitDecl();
772 assert(TU &&
"Must not be null.");
775 clang::FunctionDecl* Wrapper =
nullptr;
778 DeclContext* DCCursor =
Cursor->getEntity();
781 Wrapper = dyn_cast_or_null<FunctionDecl>(DCCursor);
783 if (utils::Analyze::IsWrapper(Wrapper)) {
799 if (
auto annot = Wrapper->getAttr<AnnotateAttr>())
800 if (annot->getAnnotation() ==
"__ResolveAtRuntime" && S->isControlScope())
803 VarDecl* Result = VarDecl::Create(C, TU, Loc, Loc, II, C.DependentTy,
815 Wrapper->addAttr(AnnotateAttr::CreateImplicit(C,
"__ResolveAtRuntime",
nullptr, 0));
819 Sema::ContextRAII pushedDC(SemaRef, TU);
830 if (
R.getLookupKind() != Sema::LookupOrdinaryName)
833 if (
R.isForRedeclaration())
839 const Transaction* T = getInterpreter()->getCurrentTransaction();
842 const cling::CompilationOptions& COpts = T->getCompilationOpts();
843 if (!COpts.DynamicScoping)
846 auto &PP =
R.getSema().PP;
850 SourceLocation LocAfterIdent = PP.getLocForEndOfToken(
R.getNameLoc());
852 PP.getRawToken(LocAfterIdent, LookAhead0,
true);
853 if (LookAhead0.is(tok::raw_identifier))
872 for (Scope* DepScope = S; DepScope; DepScope = DepScope->getParent()) {
873 if (DeclContext* Ctx =
static_cast<DeclContext*
>(DepScope->getEntity())) {
874 if (!Ctx->isDependentContext())
876 if (isa<FunctionDecl>(Ctx))
894 if (
R.isForRedeclaration())
897 if (
R.getLookupKind() != Sema::LookupOrdinaryName)
900 if (!isa<FunctionDecl>(
R.getSema().CurContext))
905 DeclContext* ScopeDC = S->getEntity();
906 if (!ScopeDC || !llvm::isa<FunctionDecl>(ScopeDC))
911 Scope* FnScope = S->getFnParent();
914 auto FD = dyn_cast_or_null<FunctionDecl>(FnScope->getEntity());
915 if (!FD || !utils::Analyze::IsWrapper(FD))
919 Sema& SemaRef =
R.getSema();
920 ASTContext& C = SemaRef.getASTContext();
921 DeclContext* DC = SemaRef.CurContext;
922 assert(DC &&
"Must not be null.");
925 Preprocessor& PP =
R.getSema().getPreprocessor();
928 if (PP.LookAhead(0).isNot(tok::equal)) {
934 DeclarationName Name =
R.getLookupName();
935 IdentifierInfo* II = Name.getAsIdentifierInfo();
936 SourceLocation Loc =
R.getNameLoc();
937 VarDecl* Result = VarDecl::Create(C, DC, Loc, Loc, II,
938 C.getAutoType(QualType(),
939 clang::AutoTypeKeyword::Auto,
945 "Cannot create VarDecl");
952 Result->addAttr(AnnotateAttr::CreateImplicit(C,
"__Auto",
nullptr, 0));
957 SemaRef.getDiagnostics().setSeverity(diag::warn_deprecated_message, diag::Severity::Warning, SourceLocation());
958 SemaRef.Diag(Loc, diag::warn_deprecated_message)
959 <<
"declaration without the 'auto' keyword" << DC << Loc << FixItHint::CreateInsertion(Loc,
"auto ");
969 Sema& SemaR = m_Interpreter->getSema();
970 cling::Transaction TPrev((cling::CompilationOptions(), SemaR));
971 TPrev.append(SemaR.getASTContext().getTranslationUnitDecl());
1010 llvm::StringRef canonicalName) {
1015 llvm::StringRef canonicalName) {
The file contains utilities which are foundational and could be used across the core component of ROO...
#define R(a, b, c, d, e, f, g, h, i)
bool TCling__LibraryLoadingFailed(const std::string &, const std::string &, bool, bool)
Lookup libraries in LD_LIBRARY_PATH and DYLD_LIBRARY_PATH with mangled_name, which is extracted by er...
void * TCling__LockCompilationDuringUserCodeExecution()
Lock the interpreter.
int TCling__LoadLibrary(const char *library)
Load a library.
void TCling__UpdateListsOnCommitted(const cling::Transaction &, Interpreter *)
void TCling__SplitAclicMode(const char *fileName, std::string &mode, std::string &args, std::string &io, std::string &fname)
void TCling__TransactionRollback(const cling::Transaction &)
const char * TCling__GetClassSharedLibs(const char *className)
int TCling__AutoParseCallback(const char *className)
Decl * TCling__GetObjectDecl(TObject *obj)
R__EXTERN int gDebug
Global variable setting the debug level. Set to 0 to disable, increase it in steps of 1 to increase t...
void TCling__GetNormalizedContext(const ROOT::TMetaUtils::TNormalizedCtxt *&)
void TCling__RestoreInterpreterMutex(void *state)
Re-apply the lock count delta that TCling__ResetInterpreterMutex() caused.
int TCling__CompileMacro(const char *fileName, const char *options)
void * TCling__ResetInterpreterMutex()
Reset the interpreter lock to the state it had before interpreter-related calls happened.
int TCling__AutoLoadCallback(const char *className)
void TCling__LibraryUnloadedRTTI(const void *dyLibHandle, llvm::StringRef canonicalName)
void TCling__PrintStackTrace()
Print a StackTrace!
int TCling__IsAutoLoadNamespaceCandidate(const clang::NamespaceDecl *name)
void TCling__UpdateListsOnUnloaded(const cling::Transaction &)
void TCling__UnlockCompilationDuringUserCodeExecution(void *state)
Unlock the interpreter.
static bool topmostDCIsFunction(Scope *S)
void TCling__InvalidateGlobal(const clang::Decl *)
void TCling__LibraryLoadedRTTI(const void *dyLibHandle, llvm::StringRef canonicalName)
TObject * TCling__GetObjectAddress(const char *Name, void *&LookupCtx)
void TCling__RestoreInterpreterMutex(void *delta)
Re-apply the lock count delta that TCling__ResetInterpreterMutex() caused.
void TCling__TransactionRollback(const cling::Transaction &T)
void TCling__InvalidateGlobal(const clang::Decl *D)
void * TCling__LockCompilationDuringUserCodeExecution()
Lock the interpreter.
void TCling__UpdateListsOnUnloaded(const cling::Transaction &T)
void TCling__GetNormalizedContext(const ROOT::TMetaUtils::TNormalizedCtxt *&normCtxt)
bool TCling__LibraryLoadingFailed(const std::string &errmessage, const std::string &libStem, bool permanent, bool resolved)
Lookup libraries in LD_LIBRARY_PATH and DYLD_LIBRARY_PATH with mangled_name, which is extracted by er...
const char * TCling__GetClassSharedLibs(const char *className, bool skipCore)
void TCling__UnlockCompilationDuringUserCodeExecution(void *)
Unlock the interpreter.
int TCling__AutoParseCallback(const char *className)
void TCling__LibraryUnloadedRTTI(const void *dyLibHandle, const char *canonicalName)
void TCling__UpdateListsOnCommitted(const cling::Transaction &T, cling::Interpreter *)
const Decl * TCling__GetObjectDecl(TObject *obj)
int TCling__CompileMacro(const char *fileName, const char *options)
void * TCling__ResetInterpreterMutex()
Reset the interpreter lock to the state it had before interpreter-related calls happened.
int TCling__AutoLoadCallback(const char *className)
void TCling__PrintStackTrace()
Print a StackTrace!
void TCling__LibraryLoadedRTTI(const void *dyLibHandle, const char *canonicalName)
TObject * TCling__GetObjectAddress(const char *Name, void *&LookupCtx)
int TCling__IsAutoLoadNamespaceCandidate(const clang::NamespaceDecl *nsDecl)
void TCling__SplitAclicMode(const char *fileName, string &mode, string &args, string &io, string &fname)
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char filename
Option_t Option_t TPoint TPoint const char mode
Int_t gDebug
Global variable setting the debug level. Set to 0 to disable, increase it in steps of 1 to increase t...
AutoloadLibraryGenerator(cling::Interpreter *interp, const TClingCallbacks &cb)
const TClingCallbacks & fCallbacks
cling::Interpreter * fInterpreter
llvm::Error tryToGenerate(llvm::orc::LookupState &LS, llvm::orc::LookupKind K, llvm::orc::JITDylib &JD, llvm::orc::JITDylibLookupFlags JDLookupFlags, const llvm::orc::SymbolLookupSet &Symbols) override
void LibraryUnloaded(const void *dyLibHandle, llvm::StringRef canonicalName) override
bool tryFindROOTSpecialInternal(clang::LookupResult &R, clang::Scope *S)
void ReturnedFromUserCode(void *stateInfo) override
bool fIsAutoParsingSuspended
bool tryResolveAtRuntimeInternal(clang::LookupResult &R, clang::Scope *S)
bool findInGlobalModuleIndex(clang::DeclarationName Name, bool loadFirstMatchOnly=true)
bool tryAutoParseInternal(llvm::StringRef Name, clang::LookupResult &R, clang::Scope *S, clang::OptionalFileEntryRef FE=std::nullopt)
void PrintStackTrace() override
bool tryInjectImplicitAutoKeyword(clang::LookupResult &R, clang::Scope *S)
bool IsAutoLoadingForJITSymbols() const
clang::NamespaceDecl * fROOTSpecialNamespace
void TransactionRollback(const cling::Transaction &T) override
void TransactionCommitted(const cling::Transaction &T) override
bool FileNotFound(llvm::StringRef FileName) override
TClingCallbacks(cling::Interpreter *interp, bool hasCodeGen)
void InclusionDirective(clang::SourceLocation, const clang::Token &, llvm::StringRef FileName, bool, clang::CharSourceRange, clang::OptionalFileEntryRef, llvm::StringRef, llvm::StringRef, const clang::Module *, bool, clang::SrcMgr::CharacteristicKind) override
llvm::DenseMap< llvm::StringRef, clang::DeclarationName > m_LoadedModuleFiles
bool IsAutoLoadingEnabled() const
void DefinitionShadowed(const clang::NamedDecl *D) override
A previous definition has been shadowed; invalidate TCling' stored data about the old (global) decl.
void * EnteringUserCode() override
bool fIsAutoLoadingRecursively
void UnlockCompilationDuringUserCodeExecution(void *StateInfo) override
bool LibraryLoadingFailed(const std::string &, const std::string &, bool, bool) override
void * LockCompilationDuringUserCodeExecution() override
bool LookupObject(clang::LookupResult &R, clang::Scope *S) override
void LibraryLoaded(const void *dyLibHandle, llvm::StringRef canonicalName) override
bool shouldResolveAtRuntime(clang::LookupResult &R, clang::Scope *S)
void TransactionUnloaded(const cling::Transaction &T) override
Mother of all ROOT objects.
bool ConvertEnvValueToBool(const std::string &value)
RooArgSet S(Args_t &&... args)
constexpr Double_t E()
Base of natural log: .
RAII used to store Parser, Sema, Preprocessor state for recursive parsing.
clang::Preprocessor::CleanupAndRestoreCacheRAII fCleanupRAII
clang::Sema::ContextAndScopeRAII fPushedDCAndS