Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
TClingCallbacks.cxx
Go to the documentation of this file.
1// @(#)root/core/meta:$Id$
2// Author: Vassil Vassilev 7/10/2012
3
4/*************************************************************************
5 * Copyright (C) 1995-2012, Rene Brun and Fons Rademakers. *
6 * All rights reserved. *
7 * *
8 * For the licensing terms see $ROOTSYS/LICENSE. *
9 * For the list of contributors see $ROOTSYS/README/CREDITS. *
10 *************************************************************************/
11
12#include "TClingCallbacks.h"
13
14#include <DllImport.h> // for R__EXTERN
16
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"
22
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"
38
39#include "llvm/ExecutionEngine/Orc/AbsoluteSymbols.h"
40#include "llvm/ExecutionEngine/Orc/Core.h"
41
42#include "llvm/Support/Error.h"
43#include "llvm/Support/FileSystem.h"
44#include "llvm/Support/Path.h"
45#include "llvm/Support/Process.h"
46
47#include "TClingUtils.h"
48#include "ClingRAII.h"
49
50#include <optional>
51
52using namespace clang;
53using namespace cling;
54using namespace ROOT::Internal;
55
57class TObject;
58
59// Functions used to forward calls from code compiled with no-rtti to code
60// compiled with rtti.
61extern "C" {
62 void TCling__UpdateListsOnCommitted(const cling::Transaction&, Interpreter*);
63 void TCling__UpdateListsOnUnloaded(const cling::Transaction&);
64 void TCling__InvalidateGlobal(const clang::Decl*);
65 void TCling__TransactionRollback(const cling::Transaction&);
67 TObject* TCling__GetObjectAddress(const char *Name, void *&LookupCtx);
69 int TCling__AutoLoadCallback(const char* className);
70 int TCling__AutoParseCallback(const char* className);
71 const char* TCling__GetClassSharedLibs(const char* className);
72 int TCling__IsAutoLoadNamespaceCandidate(const clang::NamespaceDecl* name);
73 int TCling__CompileMacro(const char *fileName, const char *options);
74 void TCling__SplitAclicMode(const char* fileName, std::string &mode,
75 std::string &args, std::string &io, std::string &fname);
76 int TCling__LoadLibrary(const char *library);
77 bool TCling__LibraryLoadingFailed(const std::string&, const std::string&, bool, bool);
79 llvm::StringRef canonicalName);
81 llvm::StringRef canonicalName);
84 void TCling__RestoreInterpreterMutex(void *state);
87}
88
91 cling::Interpreter *fInterpreter;
92public:
95
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
99 {
100 // The IsAutoLoadingEnabled() gate keeps speculative lookups (e.g. querying
101 // the address of a global that is not loaded) from triggering a costly scan
102 // of all libraries. But that gate is also flipped off by the class-autoloading
103 // suspension in TCling::Declare, which merely wants parsing to behave like a
104 // plain compiler - it must not stop us from autoloading a library whose
105 // symbols the emitted static-initializer code genuinely needs to run. Declare
106 // signals that case via IsAutoLoadingForJITSymbols(). See #16601.
107 if (!fCallbacks.IsAutoLoadingEnabled() && !fCallbacks.IsAutoLoadingForJITSymbols())
108 return llvm::Error::success();
109
110 // If we get here, the symbols have not been found in the current process,
111 // so no need to check that again. Instead search for the library that
112 // provides the symbol and create one MaterializationUnit per library to
113 // actually load it if needed.
114 std::unordered_map<std::string, llvm::orc::SymbolNameVector> found;
115
116 // TODO: Do we need to take gInterpreterMutex?
117 // R__LOCKGUARD(gInterpreterMutex);
118
119 for (auto &&KV : Symbols) {
120 llvm::orc::SymbolStringPtr name = KV.first;
121
122 const cling::DynamicLibraryManager &DLM = *fInterpreter->getDynamicLibraryManager();
123
124 std::string libName = DLM.searchLibrariesForSymbol((*name).str(),
125 /*searchSystem=*/true);
126
127 // libNew overrides memory management functions; must never autoload that.
128 assert(libName.find("/libNew.") == std::string::npos && "We must not autoload libNew!");
129
130 // libCling symbols are intentionally hidden from the process, and libCling must not be
131 // dlopened. Instead, symbols must be resolved by specifically querying the dynlib handle of
132 // libCling, which by definition is loaded - else we could not call this code. The handle
133 // is made available as argument to `CreateInterpreter`.
134 assert(libName.find("/libCling.") == std::string::npos && "Must not autoload libCling!");
135
136 if (!libName.empty())
137 found[libName].push_back(name);
138 }
139
140 llvm::orc::SymbolMap loadedSymbols;
141 for (const auto &KV : found) {
142 // Try to load the library which should provide the symbol definition.
143 // TODO: Should this interface with the DynamicLibraryManager directly?
144 if (TCling__LoadLibrary(KV.first.c_str()) < 0) {
145 ROOT::TMetaUtils::Error("AutoloadLibraryMU", "Failed to load library %s", KV.first.c_str());
146 }
147
148 for (const auto &symbol : KV.second) {
149 std::string symbolStr = (*symbol).str();
151
152 void *addr = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(nameForDlsym);
153 if (addr) {
154 loadedSymbols[symbol] = {llvm::orc::ExecutorAddr::fromPtr(addr), llvm::JITSymbolFlags::Exported};
155 }
156 }
157 }
158
159 if (!loadedSymbols.empty()) {
160 return JD.define(absoluteSymbols(std::move(loadedSymbols)));
161 }
162
163 return llvm::Error::success();
164 }
165};
166
167TClingCallbacks::TClingCallbacks(cling::Interpreter *interp, bool hasCodeGen) : InterpreterCallbacks(interp)
168{
169 if (hasCodeGen) {
170 Transaction* T = nullptr;
171 m_Interpreter->declare("namespace __ROOT_SpecialObjects{}", &T);
172 fROOTSpecialNamespace = dyn_cast<NamespaceDecl>(T->getFirstDecl().getSingleDecl());
173
174 interp->addGenerator(std::make_unique<AutoloadLibraryGenerator>(interp, *this));
175 }
176}
177
178//pin the vtable here
180
181void TClingCallbacks::InclusionDirective(clang::SourceLocation sLoc/*HashLoc*/,
182 const clang::Token &/*IncludeTok*/,
183 llvm::StringRef FileName,
184 bool /*IsAngled*/,
185 clang::CharSourceRange /*FilenameRange*/,
186 clang::OptionalFileEntryRef FE,
187 llvm::StringRef /*SearchPath*/,
188 llvm::StringRef /*RelativePath*/,
189 const clang::Module * Imported,
190 bool ModuleImported,
191 clang::SrcMgr::CharacteristicKind FileType) {
192 // We found a module. Do not try to do anything else.
193 Sema &SemaR = m_Interpreter->getSema();
194 if (Imported) {
195 // FIXME: We should make the module visible at that point.
196 if (!SemaR.isModuleVisible(Imported))
197 ROOT::TMetaUtils::Info("TClingCallbacks::InclusionDirective",
198 "Module %s resolved but not visible!", Imported->Name.c_str());
199 else
200 return;
201 }
202
203 // Method called via Callbacks->InclusionDirective()
204 // in Preprocessor::HandleIncludeDirective(), invoked whenever an
205 // inclusion directive has been processed, and allowing us to try
206 // to autoload libraries using their header file name.
207 // Two strategies are tried:
208 // 1) The header name is looked for in the list of autoload keys
209 // 2) Heurists are applied to the header name to distill a classname.
210 // For example try to autoload TGClient (libGui) when seeing #include "TGClient.h"
211 // or TH1F in presence of TH1F.h.
212 // Strategy 2) is tried only if 1) fails.
213
214 bool isHeaderFile = FileName.ends_with(".h") || FileName.ends_with(".hxx") || FileName.ends_with(".hpp");
216 return;
217
218 std::string localString(FileName.str());
219
220 DeclarationName Name = &SemaR.getASTContext().Idents.get(localString.c_str());
221 LookupResult RHeader(SemaR, Name, sLoc, Sema::LookupOrdinaryName);
222
224}
225
226// TCling__LibraryLoadingFailed is a function in TCling which handles errmessage
227bool TClingCallbacks::LibraryLoadingFailed(const std::string& errmessage, const std::string& libStem,
228 bool permanent, bool resolved) {
230}
231
232// Preprocessor callbacks used to handle special cases like for example:
233// #include "myMacro.C+"
234//
235bool TClingCallbacks::FileNotFound(llvm::StringRef FileName) {
236 // Method called via Callbacks->FileNotFound(Filename)
237 // in Preprocessor::HandleIncludeDirective(), initially allowing to
238 // change the include path, and allowing us to compile code via ACLiC
239 // when specifying #include "myfile.C+", and suppressing the preprocessor
240 // error message:
241 // input_line_23:1:10: fatal error: 'myfile.C+' file not found
242
243 Preprocessor& PP = m_Interpreter->getCI()->getPreprocessor();
244
245 // remove any trailing "\n
246 std::string filename(FileName.str().substr(0,FileName.str().find_last_of('"')));
247 std::string fname, mode, arguments, io;
248 // extract the filename and ACliC mode
249 TCling__SplitAclicMode(filename.c_str(), mode, arguments, io, fname);
250 if (mode.length() > 0) {
251 if (llvm::sys::fs::exists(fname)) {
252 // format the CompileMacro() option string
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";
257
258 // Save state of the preprocessor
259 Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP);
260 Parser& P = const_cast<Parser&>(m_Interpreter->getParser());
261 // We parsed 'include' token. Store it.
262 clang::Parser::ParserCurTokRestoreRAII fSavedCurToken(P);
263 // We provide our own way of handling the entire #include "file.c+"
264 // After we have saved the token reset the current one to
265 // something which is safe (semi colon usually means empty decl)
266 Token& Tok = const_cast<Token&>(P.getCurToken());
267 Tok.setKind(tok::semi);
268 // We can't PushDeclContext, because we go up and the routine that pops
269 // the DeclContext assumes that we drill down always.
270 // We have to be on the global context. At that point we are in a
271 // wrapper function so the parent context must be the global.
272 // This is needed to solve potential issues when using #include "myFile.C+"
273 // after a scope declaration like:
274 // void Check(TObject* obj) {
275 // if (obj) cout << "Found the referenced object\n";
276 // else cout << "Error: Could not find the referenced object\n";
277 // }
278 // #include "A.C+"
279 Sema& SemaR = m_Interpreter->getSema();
280 ASTContext& C = SemaR.getASTContext();
281 Sema::ContextAndScopeRAII pushedDCAndS(SemaR, C.getTranslationUnitDecl(),
282 SemaR.TUScope);
283 int retcode = TCling__CompileMacro(fname.c_str(), options.c_str());
284 if (retcode) {
285 // compilation was successful, tell the preprocess to silently
286 // skip the file
287 return true;
288 }
289 }
290 }
291 return false;
292}
293
294
295static bool topmostDCIsFunction(Scope* S) {
296 if (!S)
297 return false;
298
299 DeclContext* DC = S->getEntity();
300 // For DeclContext-less scopes like if (dyn_expr) {}
301 // Find the DC enclosing S.
302 while (!DC) {
303 S = S->getParent();
304 DC = S->getEntity();
305 }
306
307 // DynamicLookup only happens inside topmost functions:
308 clang::DeclContext* MaybeTU = DC;
310 DC = MaybeTU;
311 MaybeTU = MaybeTU->getParent();
312 }
313 return isa<FunctionDecl>(DC);
314}
315
316// On a failed lookup we have to try to more things before issuing an error.
317// The symbol might need to be loaded by ROOT's AutoLoading mechanism or
318// it might be a ROOT special object.
319//
320// Try those first and if still failing issue the diagnostics.
321//
322// returns true when a declaration is found and no error should be emitted.
323//
326 // init error or rootcling
327 return false;
328 }
329
330 // Don't do any extra work if an error that is not still recovered occurred.
331 if (m_Interpreter->getSema().getDiagnostics().hasErrorOccurred())
332 return false;
333
334 if (tryAutoParseInternal(R.getLookupName().getAsString(), R, S))
335 return true; // happiness.
336
337 // The remaining lookup routines only work on global scope functions
338 // ("macros"), not in classes, namespaces etc - anything that looks like
339 // it has seen any trace of software development.
340 if (!topmostDCIsFunction(S))
341 return false;
342
343 // If the autoload wasn't successful try ROOT specials.
345 return true;
346
347 // For backward-compatibility with CINT we must support stmts like:
348 // x = 4; y = new MyClass();
349 // I.e we should "inject" a C++11 auto keyword in front of "x" and "y"
350 // This has to have higher precedence than the dynamic scopes. It is claimed
351 // that if one assigns to a name and the lookup of that name fails if *must*
352 // auto keyword must be injected and the stmt evaluation must not be delayed
353 // until runtime.
354 // For now supported only at the prompt.
356 return true;
357 }
358
360 return false;
361
362 // Finally try to resolve this name as a dynamic name, i.e delay its
363 // resolution for runtime.
365}
366
368{
369 std::optional<std::string> envUseGMI = llvm::sys::Process::GetEnv("ROOT_USE_GMI");
370 if (envUseGMI.has_value())
372 return false;
373
374 const CompilerInstance *CI = m_Interpreter->getCI();
375 const LangOptions &LangOpts = CI->getPreprocessor().getLangOpts();
376
377 if (!LangOpts.Modules)
378 return false;
379
380 // We are currently building a module, we should not import .
381 if (LangOpts.isCompilingModule())
382 return false;
383
384 if (fIsCodeGening)
385 return false;
386
387 // We are currently instantiating one (or more) templates. At that point,
388 // all Decls are present in the AST (with possibly deserialization pending),
389 // and we should not load more modules which could find an implicit template
390 // instantiation that is lazily loaded.
391 Sema &SemaR = m_Interpreter->getSema();
392 if (SemaR.InstantiatingSpecializations.size() > 0)
393 return false;
394
395 GlobalModuleIndex *Index = CI->getASTReader()->getGlobalIndex();
396 if (!Index)
397 return false;
398
399 // FIXME: We should load only the first available and rely on other callbacks
400 // such as RequireCompleteType and LookupUnqualified to load all.
401 GlobalModuleIndex::FileNameHitSet FoundModules;
402
403 // Find the modules that reference the identifier.
404 // Note that this only finds top-level modules.
405 if (Index->lookupIdentifier(Name.getAsString(), FoundModules)) {
406 for (llvm::StringRef FileName : FoundModules) {
407 StringRef ModuleName = llvm::sys::path::stem(FileName);
408
409 // Skip to the first not-yet-loaded module.
410 if (m_LoadedModuleFiles.count(FileName)) {
411 if (gDebug > 2)
412 llvm::errs() << "Module '" << ModuleName << "' already loaded"
413 << " for '" << Name.getAsString() << "'\n";
414 continue;
415 }
416
417 fIsLoadingModule = true;
418 if (gDebug > 2)
419 llvm::errs() << "Loading '" << ModuleName << "' on demand"
420 << " for '" << Name.getAsString() << "'\n";
421
422 m_Interpreter->loadModule(ModuleName.str());
423 fIsLoadingModule = false;
424 m_LoadedModuleFiles[FileName] = Name;
426 break;
427 }
428 return true;
429 }
430 return false;
431}
432
435 // init error or rootcling
436 return false;
437 }
438
440 return false;
441
443 return false;
444
445 if (Name.getNameKind() != DeclarationName::Identifier)
446 return false;
447
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)) {
452 // This declaration comes from a system module, we do not want to try
453 // autoparsing it and find instantiations in our ROOT modules.
454 return false;
455 }
456
457 // Get the 'lookup' decl context.
458 // We need to cast away the constness because we will lookup items of this
459 // namespace/DeclContext
461
462 // When GMI is mixed with rootmaps, we might have a name for two different
463 // entities provided by the two systems. In that case check if the rootmaps
464 // registered the enclosing namespace as a rootmap name resolution namespace
465 // and only if that was not the case use the information in the GMI.
467 // After loading modules, we must update the redeclaration chains.
468 return findInGlobalModuleIndex(Name, /*loadFirstMatchOnly*/ false) && D->getMostRecentDecl();
469 }
470
471 const DeclContext* primaryDC = NSD->getPrimaryContext();
472 if (primaryDC != DC)
473 return false;
474
475 LookupResult R(SemaR, Name, SourceLocation(), Sema::LookupOrdinaryName);
476 R.suppressDiagnostics();
477 // We need the qualified name for TCling to find the right library.
478 std::string qualName
479 = NSD->getQualifiedNameAsString() + "::" + Name.getAsString();
480
481
482 // We want to avoid qualified lookups, because they are expensive and
483 // difficult to construct. This is why we *artificially* push a scope and
484 // a decl context, where Sema should do the lookup.
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);
488
489 if (tryAutoParseInternal(qualName, R, SemaR.getCurScope())) {
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()));
494 return true;
495 }
496 return false;
497}
498
499bool TClingCallbacks::LookupObject(clang::TagDecl* Tag) {
501 // init error or rootcling
502 return false;
503 }
504
506 return false;
507
508 // Clang needs Tag's complete definition. Can we parse it?
510
511 // if (findInGlobalModuleIndex(Tag->getDeclName(), /*loadFirstMatchOnly*/false))
512 // return true;
513
514 Sema &SemaR = m_Interpreter->getSema();
515
516 SourceLocation Loc = Tag->getLocation();
517 if (SemaR.getSourceManager().isInSystemHeader(Loc)) {
518 // This declaration comes from a system module, we do not want to try
519 // autoparsing it and find instantiations in our ROOT modules.
520 return false;
521 }
522
523 for (auto ReRD: Tag->redecls()) {
524 // Don't autoparse a TagDecl while we are parsing its definition!
525 if (ReRD->isBeingDefined())
526 return false;
527 }
528
529
531 ASTContext& C = SemaR.getASTContext();
532 Parser& P = const_cast<Parser&>(m_Interpreter->getParser());
533
535
536 // Use the Normalized name for the autoload
537 std::string Name;
541 C.getCanonicalTagType(RD),
543 *tNormCtxt);
544 // Autoparse implies autoload
545 if (TCling__AutoParseCallback(Name.c_str())) {
546 // We have read it; remember that.
547 Tag->setHasExternalLexicalStorage(false);
548 return true;
549 }
550 }
551 return false;
552}
553
554
555// The symbol might be defined in the ROOT class AutoLoading map so we have to
556// try to autoload it first and do secondary lookup to try to find it.
557//
558// returns true when a declaration is found and no error should be emitted.
559// If FileEntry, this is a reacting on a #include and Name is the included
560// filename.
561//
563 Scope *S, clang::OptionalFileEntryRef FE) {
565 // init error or rootcling
566 return false;
567 }
568
569 Sema &SemaR = m_Interpreter->getSema();
570
571 // Try to autoload first if AutoLoading is enabled
572 if (IsAutoLoadingEnabled()) {
573 // Avoid tail chasing.
575 return false;
576
577 // We should try autoload only for special lookup failures.
578 Sema::LookupNameKind kind = R.getLookupKind();
579 if (!(kind == Sema::LookupTagName || kind == Sema::LookupOrdinaryName
580 || kind == Sema::LookupNestedNameSpecifierName
581 || kind == Sema::LookupNamespaceName))
582 return false;
583
585
586 bool lookupSuccess = false;
587 // Save state of the PP
588 Parser &P = const_cast<Parser &>(m_Interpreter->getParser());
589
591
592 // First see whether we have a fwd decl of this name.
593 // We shall only do that if lookup makes sense for it (!FE).
594 if (!FE) {
595 lookupSuccess = SemaR.LookupName(R, S);
596 if (lookupSuccess) {
597 if (R.isSingleResult()) {
598 if (isa<clang::RecordDecl>(R.getFoundDecl())) {
599 // Good enough; RequireCompleteType() will tell us if we
600 // need to auto parse.
601 // But we might need to auto-load.
602 TCling__AutoLoadCallback(Name.data());
604 return true;
605 }
606 }
607 }
608 }
609
610 if (TCling__AutoParseCallback(Name.str().c_str())) {
611 // Shouldn't we pop more?
612 raii.fPushedDCAndS.pop();
613 raii.fCleanupRAII.pop();
614 lookupSuccess = FE || SemaR.LookupName(R, S);
615 } else if (FE && TCling__GetClassSharedLibs(Name.str().c_str())) {
616 // We are "autoparsing" a header, and the header was not parsed.
617 // But its library is known - so we do know about that header.
618 // Do the parsing explicitly here, while recursive AutoLoading is
619 // disabled.
620 std::string incl = "#include \"";
621 incl += FE->getName();
622 incl += '"';
623 m_Interpreter->declare(incl);
624 }
625
627
628 if (lookupSuccess)
629 return true;
630 }
631
632 return false;
633}
634
635// If cling cannot find a name it should ask ROOT before it issues an error.
636// If ROOT knows the name then it has to create a new variable with that name
637// and type in dedicated for that namespace (eg. __ROOT_SpecialObjects).
638// For example if the interpreter is looking for h in h-Draw(), this routine
639// will create
640// namespace __ROOT_SpecialObjects {
641// THist* h = (THist*) the_address;
642// }
643//
644// Later if h is called again it again won't be found by the standart lookup
645// because it is in our hidden namespace (nobody should do using namespace
646// __ROOT_SpecialObjects). It caches the variable declarations and their
647// last address. If the newly found decl with the same name (h) has different
648// address than the cached one it goes directly at the address and updates it.
649//
650// returns true when declaration is found and no error should be emitted.
651//
654 // init error or rootcling
655 return false;
656 }
657
658 // User must be able to redefine the names that come from a file.
659 if (R.isForRedeclaration())
660 return false;
661 // If there is a result abort.
662 if (!R.empty())
663 return false;
664 const Sema::LookupNameKind LookupKind = R.getLookupKind();
665 if (LookupKind != Sema::LookupOrdinaryName)
666 return false;
667
668
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();
674
675 // Make sure that the failed lookup comes from a function body.
676 if(!CurDC || !CurDC->isFunctionOrMethod())
677 return false;
678
679 // Save state of the PP, because TCling__GetObjectAddress may induce nested
680 // lookup.
681 Preprocessor::CleanupAndRestoreCacheRAII cleanupPPRAII(PP);
682 TObject *obj = TCling__GetObjectAddress(Name.getAsString().c_str(),
684 cleanupPPRAII.pop(); // force restoring the cache
685
686 if (obj) {
687
688#if defined(R__MUST_REVISIT)
689#if R__MUST_REVISIT(6,2)
690 // Register the address in TCling::fgSetOfSpecials
691 // to speed-up the execution of TCling::RecursiveRemove when
692 // the object is not a special.
693 // See http://root.cern.ch/viewvc/trunk/core/meta/src/TCint.cxx?view=log#rev18109
694 if (!fgSetOfSpecials) {
695 fgSetOfSpecials = new std::set<TObject*>;
696 }
697 ((std::set<TObject*>*)fgSetOfSpecials)->insert((TObject*)*obj);
698#endif
699#endif
700
701 VarDecl *VD = cast_or_null<VarDecl>(utils::Lookup::Named(&SemaR, Name,
703 if (VD) {
704 //TODO: Check for same types.
706 TObject **address = (TObject**)m_Interpreter->getAddressOfGlobal(GD);
707 // Since code was generated already we cannot rely on the initializer
708 // of the decl in the AST, however we will update that init so that it
709 // will be easier while debugging.
711 Expr* newInit = utils::Synthesize::IntegerLiteralExpr(C, (uint64_t)obj);
712 CStyleCast->setSubExpr(newInit);
713
714 // The actual update happens here, directly in memory.
715 *address = obj;
716 }
717 else {
718 // Save state of the PP
719 Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP);
720
721 const Decl *TD = TCling__GetObjectDecl(obj);
722 // We will declare the variable as pointer.
723 QualType QT = C.getPointerType(C.getTypeDeclType(cast<TypeDecl>(TD)));
724
725 VD = VarDecl::Create(C, fROOTSpecialNamespace, SourceLocation(),
726 SourceLocation(), Name.getAsIdentifierInfo(), QT,
727 /*TypeSourceInfo*/nullptr, SC_None);
728 // Build an initializer
729 Expr* Init
730 = utils::Synthesize::CStyleCastPtrExpr(&SemaR, QT, (uint64_t)obj);
731 // Register the decl in our hidden special namespace
732 VD->setInit(Init);
733 fROOTSpecialNamespace->addDecl(VD);
734
735 cling::CompilationOptions CO;
736 CO.DeclarationExtraction = 0;
737 CO.ValuePrinting = CompilationOptions::VPDisabled;
738 CO.ResultEvaluation = 0;
739 CO.DynamicScoping = 0;
740 CO.Debug = 0;
741 CO.CodeGeneration = 1;
742
743 cling::Transaction* T = new cling::Transaction(CO, SemaR);
744 T->append(VD);
745 T->setState(cling::Transaction::kCompleted);
746
747 m_Interpreter->emitAllDecls(T);
748 }
749 assert(VD && "Cannot be null!");
750 R.addDecl(VD);
751 return true;
752 }
753
754 return false;
755}
756
759 // init error or rootcling
760 return false;
761 }
762
763 if (!shouldResolveAtRuntime(R, S))
764 return false;
765
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.");
773
774 // DynamicLookup only happens inside wrapper functions:
775 clang::FunctionDecl* Wrapper = nullptr;
776 Scope* Cursor = S;
777 do {
778 DeclContext* DCCursor = Cursor->getEntity();
779 if (DCCursor == TU)
780 return false;
782 if (Wrapper) {
783 if (utils::Analyze::IsWrapper(Wrapper)) {
784 break;
785 } else {
786 // Can't have a function inside the wrapper:
787 return false;
788 }
789 }
790 } while ((Cursor = Cursor->getParent()));
791
792 if (!Wrapper) {
793 // The parent of S wasn't the TU?!
794 return false;
795 }
796
797 // Prevent redundant declarations for control statements (e.g., for, if, while)
798 // that have already been annotated.
799 if (auto annot = Wrapper->getAttr<AnnotateAttr>())
800 if (annot->getAnnotation() == "__ResolveAtRuntime" && S->isControlScope())
801 return false;
802
803 VarDecl* Result = VarDecl::Create(C, TU, Loc, Loc, II, C.DependentTy,
804 /*TypeSourceInfo*/nullptr, SC_None);
805
806 if (!Result) {
807 // We cannot handle the situation. Give up
808 return false;
809 }
810
811 // Annotate the decl to give a hint in cling. FIXME: Current implementation
812 // is a gross hack, because TClingCallbacks shouldn't know about
813 // EvaluateTSynthesizer at all!
814
815 Wrapper->addAttr(AnnotateAttr::CreateImplicit(C, "__ResolveAtRuntime", nullptr, 0));
816
817 // Here we have the scope but we cannot do Sema::PushDeclContext, because
818 // on pop it will try to go one level up, which we don't want.
819 Sema::ContextRAII pushedDC(SemaRef, TU);
820 R.addDecl(Result);
821 //SemaRef.PushOnScopeChains(Result, SemaRef.TUScope, /*Add to ctx*/true);
822 // Say that we can handle the situation. Clang should try to recover
823 return true;
824}
825
827 if (m_IsRuntime)
828 return false;
829
830 if (R.getLookupKind() != Sema::LookupOrdinaryName)
831 return false;
832
833 if (R.isForRedeclaration())
834 return false;
835
836 if (!R.empty())
837 return false;
838
839 const Transaction* T = getInterpreter()->getCurrentTransaction();
840 if (!T)
841 return false;
842 const cling::CompilationOptions& COpts = T->getCompilationOpts();
843 if (!COpts.DynamicScoping)
844 return false;
845
846 auto &PP = R.getSema().PP;
847 // In `foo bar`, `foo` is certainly a type name and must not be resolved. We
848 // cannot rely on `PP.LookAhead(0)` as the parser might have already consumed
849 // some tokens.
850 SourceLocation LocAfterIdent = PP.getLocForEndOfToken(R.getNameLoc());
852 PP.getRawToken(LocAfterIdent, LookAhead0, /*IgnoreWhiteSpace=*/true);
853 if (LookAhead0.is(tok::raw_identifier))
854 return false;
855
856 // FIXME: Figure out better way to handle:
857 // C++ [basic.lookup.classref]p1:
858 // In a class member access expression (5.2.5), if the . or -> token is
859 // immediately followed by an identifier followed by a <, the
860 // identifier must be looked up to determine whether the < is the
861 // beginning of a template argument list (14.2) or a less-than operator.
862 // The identifier is first looked up in the class of the object
863 // expression. If the identifier is not found, it is then looked up in
864 // the context of the entire postfix-expression and shall name a class
865 // or function template.
866 //
867 // We want to ignore object(.|->)member<template>
868 //if (R.getSema().PP.LookAhead(0).getKind() == tok::less)
869 // TODO: check for . or -> in the cached token stream
870 // return false;
871
872 for (Scope* DepScope = S; DepScope; DepScope = DepScope->getParent()) {
873 if (DeclContext* Ctx = static_cast<DeclContext*>(DepScope->getEntity())) {
874 if (!Ctx->isDependentContext())
875 // For now we support only the prompt.
877 return true;
878 }
879 }
880
881 return false;
882}
883
886 // init error or rootcling
887 return false;
888 }
889
890 // Should be disabled with the dynamic scopes.
891 if (m_IsRuntime)
892 return false;
893
894 if (R.isForRedeclaration())
895 return false;
896
897 if (R.getLookupKind() != Sema::LookupOrdinaryName)
898 return false;
899
900 if (!isa<FunctionDecl>(R.getSema().CurContext))
901 return false;
902
903 {
904 // ROOT-8538: only top-most (function-level) scope is supported.
905 DeclContext* ScopeDC = S->getEntity();
906 if (!ScopeDC || !llvm::isa<FunctionDecl>(ScopeDC))
907 return false;
908
909 // Make sure that the failed lookup comes the prompt. Currently, we
910 // support only the prompt.
911 Scope* FnScope = S->getFnParent();
912 if (!FnScope)
913 return false;
914 auto FD = dyn_cast_or_null<FunctionDecl>(FnScope->getEntity());
915 if (!FD || !utils::Analyze::IsWrapper(FD))
916 return false;
917 }
918
919 Sema& SemaRef = R.getSema();
920 ASTContext& C = SemaRef.getASTContext();
921 DeclContext* DC = SemaRef.CurContext;
922 assert(DC && "Must not be null.");
923
924
925 Preprocessor& PP = R.getSema().getPreprocessor();
926 //Preprocessor::CleanupAndRestoreCacheRAII cleanupRAII(PP);
927 //PP.EnableBacktrackAtThisPos();
928 if (PP.LookAhead(0).isNot(tok::equal)) {
929 //PP.Backtrack();
930 return false;
931 }
932 //PP.CommitBacktrackedTokens();
933 //cleanupRAII.pop();
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,
940 /*IsDependent*/false),
941 /*TypeSourceInfo*/nullptr, SC_None);
942
943 if (!Result) {
944 ROOT::TMetaUtils::Error("TClingCallbacks::tryInjectImplicitAutoKeyword",
945 "Cannot create VarDecl");
946 return false;
947 }
948
949 // Annotate the decl to give a hint in cling.
950 // FIXME: We should move this in cling, when we implement turning it on
951 // and off.
952 Result->addAttr(AnnotateAttr::CreateImplicit(C, "__Auto", nullptr, 0));
953
954 R.addDecl(Result);
955
956 // Raise a warning when trying to use implicit auto injection feature.
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 ");
960
961 // Say that we can handle the situation. Clang should try to recover
962 return true;
963}
964
966 // Replay existing decls from the AST.
967 if (fFirstRun) {
968 // Before setting up the callbacks register what cling have seen during init.
969 Sema& SemaR = m_Interpreter->getSema();
970 cling::Transaction TPrev((cling::CompilationOptions(), SemaR));
971 TPrev.append(SemaR.getASTContext().getTranslationUnitDecl());
973
974 fFirstRun = false;
975 }
976}
977
978// The callback is used to update the list of globals in ROOT.
979//
986
987// The callback is used to update the list of globals in ROOT.
988//
990 if (T.empty())
991 return;
992
994}
995
996// The callback is used to clear the autoparsing caches.
997//
999 if (T.empty())
1000 return;
1001
1003}
1004
1005void TClingCallbacks::DefinitionShadowed(const clang::NamedDecl *D) {
1007}
1008
1013
1018
1022
1024{
1025 // We can safely assume that if the lock exist already when we are in Cling code,
1026 // then the lock has (or should been taken) already. Any action (that caused callers
1027 // to take the lock) is halted during ProcessLine. So it is fair to unlock it.
1029}
1030
1035
1040
#define R__EXTERN
Definition DllImport.h:26
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)
Definition RSha256.hxx:110
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...
Definition TCling.cxx:368
void * TCling__LockCompilationDuringUserCodeExecution()
Lock the interpreter.
Definition TCling.cxx:385
int TCling__LoadLibrary(const char *library)
Load a library.
Definition TCling.cxx:349
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)
Definition TCling.cxx:668
void TCling__TransactionRollback(const cling::Transaction &)
Definition TCling.cxx:596
const char * TCling__GetClassSharedLibs(const char *className)
int TCling__AutoParseCallback(const char *className)
Definition TCling.cxx:645
Decl * TCling__GetObjectDecl(TObject *obj)
Definition TCling.cxx:621
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 *&)
Definition TCling.cxx:574
void TCling__RestoreInterpreterMutex(void *state)
Re-apply the lock count delta that TCling__ResetInterpreterMutex() caused.
Definition TCling.cxx:358
int TCling__CompileMacro(const char *fileName, const char *options)
Definition TCling.cxx:661
void * TCling__ResetInterpreterMutex()
Reset the interpreter lock to the state it had before interpreter-related calls happened.
Definition TCling.cxx:377
int TCling__AutoLoadCallback(const char *className)
Definition TCling.cxx:640
void TCling__LibraryUnloadedRTTI(const void *dyLibHandle, llvm::StringRef canonicalName)
void TCling__PrintStackTrace()
Print a StackTrace!
Definition TCling.cxx:342
int TCling__IsAutoLoadNamespaceCandidate(const clang::NamespaceDecl *name)
Definition TCling.cxx:656
void TCling__UpdateListsOnUnloaded(const cling::Transaction &)
Definition TCling.cxx:586
void TCling__UnlockCompilationDuringUserCodeExecution(void *state)
Unlock the interpreter.
Definition TCling.cxx:396
static bool topmostDCIsFunction(Scope *S)
void TCling__InvalidateGlobal(const clang::Decl *)
Definition TCling.cxx:591
void TCling__LibraryLoadedRTTI(const void *dyLibHandle, llvm::StringRef canonicalName)
TObject * TCling__GetObjectAddress(const char *Name, void *&LookupCtx)
Definition TCling.cxx:617
void TCling__RestoreInterpreterMutex(void *delta)
Re-apply the lock count delta that TCling__ResetInterpreterMutex() caused.
Definition TCling.cxx:358
void TCling__TransactionRollback(const cling::Transaction &T)
Definition TCling.cxx:596
void TCling__InvalidateGlobal(const clang::Decl *D)
Definition TCling.cxx:591
void * TCling__LockCompilationDuringUserCodeExecution()
Lock the interpreter.
Definition TCling.cxx:385
void TCling__UpdateListsOnUnloaded(const cling::Transaction &T)
Definition TCling.cxx:586
void TCling__GetNormalizedContext(const ROOT::TMetaUtils::TNormalizedCtxt *&normCtxt)
Definition TCling.cxx:574
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...
Definition TCling.cxx:368
const char * TCling__GetClassSharedLibs(const char *className, bool skipCore)
Definition TCling.cxx:650
void TCling__UnlockCompilationDuringUserCodeExecution(void *)
Unlock the interpreter.
Definition TCling.cxx:396
int TCling__AutoParseCallback(const char *className)
Definition TCling.cxx:645
void TCling__LibraryUnloadedRTTI(const void *dyLibHandle, const char *canonicalName)
Definition TCling.cxx:610
void TCling__UpdateListsOnCommitted(const cling::Transaction &T, cling::Interpreter *)
Definition TCling.cxx:581
const Decl * TCling__GetObjectDecl(TObject *obj)
Definition TCling.cxx:621
int TCling__CompileMacro(const char *fileName, const char *options)
Definition TCling.cxx:661
void * TCling__ResetInterpreterMutex()
Reset the interpreter lock to the state it had before interpreter-related calls happened.
Definition TCling.cxx:377
int TCling__AutoLoadCallback(const char *className)
Definition TCling.cxx:640
void TCling__PrintStackTrace()
Print a StackTrace!
Definition TCling.cxx:342
void TCling__LibraryLoadedRTTI(const void *dyLibHandle, const char *canonicalName)
Definition TCling.cxx:600
TObject * TCling__GetObjectAddress(const char *Name, void *&LookupCtx)
Definition TCling.cxx:617
int TCling__IsAutoLoadNamespaceCandidate(const clang::NamespaceDecl *nsDecl)
Definition TCling.cxx:656
void TCling__SplitAclicMode(const char *fileName, string &mode, string &args, string &io, string &fname)
Definition TCling.cxx:668
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
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
char name[80]
Definition TGX11.cxx:148
XID Cursor
Definition TGX11.h:36
Int_t gDebug
Global variable setting the debug level. Set to 0 to disable, increase it in steps of 1 to increase t...
Definition TROOT.cxx:792
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 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)
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
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.
Definition TObject.h:42
#define I(x, y, z)
bool ConvertEnvValueToBool(const std::string &value)
void Error(const char *location, const char *fmt,...)
void Info(const char *location, const char *fmt,...)
void GetNormalizedName(std::string &norm_name, const clang::QualType &type, const cling::Interpreter &interpreter, const TNormalizedCtxt &normCtxt)
Return the type name normalized for ROOT, keeping only the ROOT opaque typedef (Double32_t,...
static std::string DemangleNameForDlsym(const std::string &name)
RooArgSet S(Args_t &&... args)
Definition RooArgSet.h:200
constexpr Double_t E()
Base of natural log: .
Definition TMath.h:96
const char * Name
Definition TXMLSetup.cxx:66
RAII used to store Parser, Sema, Preprocessor state for recursive parsing.
Definition ClingRAII.h:22