-
Notifications
You must be signed in to change notification settings - Fork 311
Expand file tree
/
Copy pathInterpreter.cpp
More file actions
1635 lines (1391 loc) · 58.9 KB
/
Interpreter.cpp
File metadata and controls
1635 lines (1391 loc) · 58.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author: Lukasz Janyst <ljanyst@cern.ch>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "cling/Interpreter/Interpreter.h"
#include "cling/Utils/Paths.h"
#ifdef LLVM_ON_WIN32
#include "cling/Utils/Platform.h"
#endif
#include "ClingUtils.h"
#include "DynamicLookup.h"
#include "ExternalInterpreterSource.h"
#include "ForwardDeclPrinter.h"
#include "IncrementalExecutor.h"
#include "IncrementalParser.h"
#include "MultiplexInterpreterCallbacks.h"
#include "TransactionUnloader.h"
#include "cling/Interpreter/AutoloadCallback.h"
#include "cling/Interpreter/CIFactory.h"
#include "cling/Interpreter/ClangInternalState.h"
#include "cling/Interpreter/ClingCodeCompleteConsumer.h"
#include "cling/Interpreter/CompilationOptions.h"
#include "cling/Interpreter/DynamicExprInfo.h"
#include "cling/Interpreter/DynamicLibraryManager.h"
#include "cling/Interpreter/LookupHelper.h"
#include "cling/Interpreter/Transaction.h"
#include "cling/Interpreter/Value.h"
#include "cling/Utils/AST.h"
#include "cling/Utils/Casting.h"
#include "cling/Utils/Output.h"
#include "cling/Utils/SourceNormalization.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/GlobalDecl.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/CodeGen/ModuleBuilder.h"
#include "clang/Frontend/ASTConsumers.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/Utils.h"
#include "clang/Lex/ExternalPreprocessorSource.h"
#include "clang/FrontendTool/Utils.h"
#include "clang/Lex/HeaderSearch.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Parse/Parser.h"
#include "clang/Sema/Sema.h"
#include "clang/Sema/SemaDiagnostic.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/Path.h"
#include <string>
#include <vector>
using namespace clang;
namespace {
// Forward cxa_atexit for global d'tors.
static int local_cxa_atexit(void (*func) (void*), void* arg,
cling::Interpreter* Interp) {
Interp->AddAtExitFunc(func, arg);
return 0;
}
static cling::Interpreter::ExecutionResult
ConvertExecutionResult(cling::IncrementalExecutor::ExecutionResult ExeRes) {
switch (ExeRes) {
case cling::IncrementalExecutor::kExeSuccess:
return cling::Interpreter::kExeSuccess;
case cling::IncrementalExecutor::kExeFunctionNotCompiled:
return cling::Interpreter::kExeFunctionNotCompiled;
case cling::IncrementalExecutor::kExeUnresolvedSymbols:
return cling::Interpreter::kExeUnresolvedSymbols;
default: break;
}
return cling::Interpreter::kExeSuccess;
}
static bool isPracticallyEmptyModule(const llvm::Module* M) {
return M->empty() && M->global_empty() && M->alias_empty();
}
} // unnamed namespace
namespace cling {
Interpreter::PushTransactionRAII::PushTransactionRAII(const Interpreter* i)
: m_Interpreter(i) {
CompilationOptions CO = m_Interpreter->makeDefaultCompilationOpts();
CO.ResultEvaluation = 0;
CO.DynamicScoping = 0;
m_Transaction = m_Interpreter->m_IncrParser->beginTransaction(CO);
}
Interpreter::PushTransactionRAII::~PushTransactionRAII() {
pop();
}
void Interpreter::PushTransactionRAII::pop() const {
IncrementalParser::ParseResultTransaction PRT
= m_Interpreter->m_IncrParser->endTransaction(m_Transaction);
if (PRT.getPointer()) {
assert(PRT.getPointer()==m_Transaction && "Ended different transaction?");
m_Interpreter->m_IncrParser->commitTransaction(PRT);
}
}
Interpreter::StateDebuggerRAII::StateDebuggerRAII(const Interpreter* i)
: m_Interpreter(i) {
if (m_Interpreter->isPrintingDebug()) {
const CompilerInstance& CI = *m_Interpreter->getCI();
CodeGenerator* CG = i->m_IncrParser->getCodeGenerator();
// The ClangInternalState constructor can provoke deserialization,
// we need a transaction.
PushTransactionRAII pushedT(i);
m_State.reset(new ClangInternalState(CI.getASTContext(),
CI.getPreprocessor(),
CG ? CG->GetModule() : 0,
CG,
"aName"));
}
}
Interpreter::StateDebuggerRAII::~StateDebuggerRAII() {
if (m_State) {
// The ClangInternalState destructor can provoke deserialization,
// we need a transaction.
PushTransactionRAII pushedT(m_Interpreter);
m_State->compare("aName", m_Interpreter->m_Opts.Verbose());
m_State.reset();
}
}
const Parser& Interpreter::getParser() const {
return *m_IncrParser->getParser();
}
Parser& Interpreter::getParser() {
return *m_IncrParser->getParser();
}
clang::SourceLocation Interpreter::getNextAvailableLoc() const {
return m_IncrParser->getLastMemoryBufferEndLoc().getLocWithOffset(1);
}
bool Interpreter::isInSyntaxOnlyMode() const {
return getCI()->getFrontendOpts().ProgramAction
== clang::frontend::ParseSyntaxOnly;
}
bool Interpreter::isValid() const {
// Should we also check m_IncrParser->getFirstTransaction() ?
// not much can be done without it (its the initializing transaction)
return m_IncrParser && m_IncrParser->isValid() &&
m_DyLibManager && m_LookupHelper &&
(isInSyntaxOnlyMode() || m_Executor);
}
namespace internal { void symbol_requester(); }
const char* Interpreter::getVersion() {
return ClingStringify(CLING_VERSION);
}
static bool handleSimpleOptions(const InvocationOptions& Opts) {
if (Opts.ShowVersion) {
cling::log() << Interpreter::getVersion() << '\n';
}
if (Opts.Help) {
Opts.PrintHelp();
}
return Opts.ShowVersion || Opts.Help;
}
Interpreter::Interpreter(int argc, const char* const *argv,
const char* llvmdir /*= 0*/, bool noRuntime,
const Interpreter* parentInterp) :
m_Opts(argc, argv),
m_UniqueCounter(parentInterp ? parentInterp->m_UniqueCounter + 1 : 0),
m_PrintDebug(false), m_DynamicLookupDeclared(false),
m_DynamicLookupEnabled(false), m_RawInputEnabled(false),
m_OptLevel(parentInterp ? parentInterp->m_OptLevel : -1) {
if (handleSimpleOptions(m_Opts))
return;
m_LLVMContext.reset(new llvm::LLVMContext);
m_DyLibManager.reset(new DynamicLibraryManager(getOptions()));
m_IncrParser.reset(new IncrementalParser(this, llvmdir));
if (!m_IncrParser->isValid(false))
return;
// Initialize the opt level to what CodeGenOpts says.
if (m_OptLevel == -1)
m_OptLevel = getCI()->getCodeGenOpts().OptimizationLevel;
Sema& SemaRef = getSema();
Preprocessor& PP = SemaRef.getPreprocessor();
// Enable incremental processing, which prevents the preprocessor destroying
// the lexer on EOF token.
PP.enableIncrementalProcessing();
m_LookupHelper.reset(new LookupHelper(new Parser(PP, SemaRef,
/*SkipFunctionBodies*/false,
/*isTemp*/true), this));
if (!m_LookupHelper)
return;
if (!isInSyntaxOnlyMode()) {
m_Executor.reset(new IncrementalExecutor(SemaRef.Diags, *getCI()));
if (!m_Executor)
return;
}
// Tell the diagnostic client that we are entering file parsing mode.
DiagnosticConsumer& DClient = getCI()->getDiagnosticClient();
DClient.BeginSourceFile(getCI()->getLangOpts(), &PP);
llvm::SmallVector<IncrementalParser::ParseResultTransaction, 2>
IncrParserTransactions;
if (!m_IncrParser->Initialize(IncrParserTransactions, parentInterp)) {
// Initialization is not going well, but we still have to commit what
// we've been given. Don't clear the DiagnosticsConsumer so the caller
// can inspect any errors that have been generated.
for (auto&& I: IncrParserTransactions)
m_IncrParser->commitTransaction(I, false);
return;
}
llvm::SmallVector<llvm::StringRef, 6> Syms;
Initialize(noRuntime || m_Opts.NoRuntime, isInSyntaxOnlyMode(), Syms);
// Commit the transactions, now that gCling is set up. It is needed for
// static initialization in these transactions through local_cxa_atexit().
for (auto&& I: IncrParserTransactions)
m_IncrParser->commitTransaction(I);
// Now that the transactions have been commited, force symbol emission
// and overrides.
if (!isInSyntaxOnlyMode()) {
if (const Transaction* T = getLastTransaction()) {
if (llvm::Module* M = T->getModule()) {
for (const llvm::StringRef& Sym : Syms) {
const llvm::GlobalValue* GV = M->getNamedValue(Sym);
#if defined(__GLIBCXX__) && !defined(__APPLE__)
// libstdc++ mangles at_quick_exit on Linux when g++ < 5
if (!GV && Sym.equals("at_quick_exit"))
GV = M->getNamedValue("_Z13at_quick_exitPFvvE");
#endif
if (GV) {
if (void* Addr = m_Executor->getPointerToGlobalFromJIT(*GV))
m_Executor->addSymbol(Sym.str().c_str(), Addr, true);
else
cling::errs() << Sym << " not defined\n";
} else
cling::errs() << Sym << " not in Module!\n";
}
}
}
}
// Disable suggestions for ROOT
bool showSuggestions = !llvm::StringRef(ClingStringify(CLING_VERSION)).startswith("ROOT");
// We need InterpreterCallbacks only if it is a parent Interpreter.
if (!parentInterp) {
std::unique_ptr<InterpreterCallbacks>
AutoLoadCB(new AutoloadCallback(this, showSuggestions));
setCallbacks(std::move(AutoLoadCB));
}
m_IncrParser->SetTransformers(parentInterp);
if (!m_LLVMContext) {
// Never true, but don't tell the compiler.
// Force symbols needed by runtime to be included in binaries.
// Prevents stripping the symbol due to dead-code optimization.
internal::symbol_requester();
}
}
///\brief Constructor for the child Interpreter.
/// Passing the parent Interpreter as an argument.
///
Interpreter::Interpreter(const Interpreter &parentInterpreter, int argc,
const char* const *argv,
const char* llvmdir /*= 0*/, bool noRuntime) :
Interpreter(argc, argv, llvmdir, noRuntime, &parentInterpreter) {
// Do the "setup" of the connection between this interpreter and
// its parent interpreter.
if (CompilerInstance* CI = getCIOrNull()) {
// The "bridge" between the interpreters.
ExternalInterpreterSource *myExternalSource =
new ExternalInterpreterSource(&parentInterpreter, this);
llvm::IntrusiveRefCntPtr <ExternalASTSource>
astContextExternalSource(myExternalSource);
CI->getASTContext().setExternalSource(astContextExternalSource);
// Inform the Translation Unit Decl of I2 that it has to search somewhere
// else to find the declarations.
CI->getASTContext().getTranslationUnitDecl()->setHasExternalVisibleStorage(true);
// Give my IncrementalExecutor a pointer to the Incremental executor of the
// parent Interpreter.
m_Executor->setExternalIncrementalExecutor(parentInterpreter.m_Executor.get());
}
}
Interpreter::~Interpreter() {
// Do this first so m_StoredStates will be ignored if Interpreter::unload
// is called later on.
for (size_t i = 0, e = m_StoredStates.size(); i != e; ++i)
delete m_StoredStates[i];
m_StoredStates.clear();
if (m_Executor)
m_Executor->shuttingDown();
if (CompilerInstance* CI = getCIOrNull())
CI->getDiagnostics().getClient()->EndSourceFile();
// LookupHelper's ~Parser needs the PP from IncrParser's CI, so do this
// first:
m_LookupHelper.reset();
// We want to keep the callback alive during the shutdown of Sema, CodeGen
// and the ASTContext. For that to happen we shut down the IncrementalParser
// explicitly, before the implicit destruction (through the unique_ptr) of
// the callbacks.
m_IncrParser.reset(0);
}
Transaction* Interpreter::Initialize(bool NoRuntime, bool SyntaxOnly,
llvm::SmallVectorImpl<llvm::StringRef>& Globals) {
largestream Strm;
const clang::LangOptions& LangOpts = getCI()->getLangOpts();
const void* ThisP = static_cast<void*>(this);
// PCH/PCM-generation defines syntax-only. If we include definitions,
// loading the PCH/PCM will make the runtime barf about dupe definitions.
bool EmitDefinitions = !SyntaxOnly;
// FIXME: gCling should be const so assignemnt is a compile time error.
// Currently the name mangling is coming up wrong for the const version
// (on OS X at least, so probably Linux too) and the JIT thinks the symbol
// is undefined in a child Interpreter. And speaking of children, should
// gCling actually be thisCling, so a child Interpreter can only access
// itself? One could use a macro (simillar to __dso_handle) to block
// assignemnt and get around the mangling issue.
const char* Linkage = LangOpts.CPlusPlus ? "extern \"C\"" : "";
if (!NoRuntime) {
if (LangOpts.CPlusPlus) {
Strm << "#include \"cling/Interpreter/RuntimeUniverse.h\"\n";
if (EmitDefinitions)
Strm << "namespace cling { class Interpreter; namespace runtime { "
"Interpreter* gCling=(Interpreter*)" << ThisP << ";}}\n";
} else {
Strm << "#include \"cling/Interpreter/CValuePrinter.h\"\n"
<< "void* gCling";
if (EmitDefinitions)
Strm << "=(void*)" << ThisP;
Strm << ";\n";
}
}
// Intercept all atexit calls, as the Interpreter and functions will be long
// gone when the -native- versions invoke them.
#if defined(__GLIBCXX__) && !defined(__APPLE__)
const char* LinkageCxx = "extern \"C++\"";
const char* Attr = LangOpts.CPlusPlus ? " throw () " : "";
const char* cxa_atexit_is_noexcept = LangOpts.CPlusPlus ? " noexcept" : "";
#else
const char* LinkageCxx = Linkage;
const char* Attr = "";
const char* cxa_atexit_is_noexcept = "";
#endif
// While __dso_handle is still overriden in the JIT below,
// #define __dso_handle is used to mitigate the following problems:
// 1. Type of __dso_handle is void* making assignemnt to it legal
// 2. Making it void* const in cling would mean possible type mismatch
// 3. Cannot override void* __dso_handle in child Interpreter
// 4. On Unix where the symbol actually exists, __dso_handle will be
// linked into the code before the JIT can say otherwise, so:
// [cling] __dso_handle // codegened __dso_handle always printed
// [cling] __cxa_atexit(f, 0, __dso_handle) // seg-fault
// 5. Code that actually uses __dso_handle will fail as a declaration is
// needed which is not possible with the macro.
// 6. Assuming 4 is sorted out in user code, calling __cxa_atexit through
// atexit below isn't linking to the __dso_handle symbol.
// Use __cxa_atexit to intercept all of the following routines
Strm << Linkage << " int __cxa_atexit(void (*f)(void*), void*, void*) "
<< cxa_atexit_is_noexcept << ";\n";
if (EmitDefinitions)
Strm << "#define __dso_handle ((void*)" << ThisP << ")\n";
// C atexit, std::atexit
Strm << Linkage << " int atexit(void(*f)()) " << Attr;
if (EmitDefinitions)
Strm << " { return __cxa_atexit((void(*)(void*))f, 0, __dso_handle); }\n";
else
Strm << ";\n";
Globals.push_back("atexit");
// C++ 11 at_quick_exit, std::at_quick_exit
if (LangOpts.CPlusPlus && LangOpts.CPlusPlus11) {
Strm << LinkageCxx << " int at_quick_exit(void(*f)()) " << Attr;
if (EmitDefinitions)
Strm
<< " { return __cxa_atexit((void(*)(void*))f, 0, __dso_handle); }\n";
else
Strm << ";\n";
Globals.push_back("at_quick_exit");
}
#if defined(LLVM_ON_WIN32)
// Windows specific: _onexit, _onexit_m, __dllonexit
#if !defined(_M_CEE)
const char* Spec = "__cdecl";
#else
const char* Spec = "__clrcall";
#endif
Strm << Linkage << " " << Spec << " int (*__dllonexit("
<< "int (" << Spec << " *f)(void**, void**), void**, void**))"
"(void**, void**)";
if (EmitDefinitions)
Strm << " { __cxa_atexit((void(*)(void*))f, 0, __dso_handle);"
" return f; }\n";
else
Strm << ";\n";
Globals.push_back("__dllonexit");
#if !defined(_M_CEE_PURE)
Strm << Linkage << " " << Spec << " int (*_onexit("
<< "int (" << Spec << " *f)()))()";
if (EmitDefinitions)
Strm << " { __cxa_atexit((void(*)(void*))f, 0, __dso_handle);"
" return f; }\n";
else
Strm << ";\n";
Globals.push_back("_onexit");
#endif
#endif
if (!SyntaxOnly) {
// Override the native symbols now, before anything can be emitted.
m_Executor->addSymbol("__cxa_atexit",
utils::FunctionToVoidPtr(&local_cxa_atexit), true);
// __dso_handle is inserted for the link phase, as macro is useless then
m_Executor->addSymbol("__dso_handle", this, true);
#ifdef CLING_WIN_SEH_EXCEPTIONS
// Windows C++ SEH handler
m_Executor->addSymbol("_CxxThrowException",
utils::FunctionToVoidPtr(&platform::ClingRaiseSEHException), true);
#endif
}
if (m_Opts.Verbose())
cling::errs() << Strm.str();
Transaction *T;
declare(Strm.str(), &T);
return T;
}
void Interpreter::AddIncludePaths(llvm::StringRef PathStr, const char* Delm) {
CompilerInstance* CI = getCI();
HeaderSearchOptions& HOpts = CI->getHeaderSearchOpts();
// Save the current number of entries
size_t Idx = HOpts.UserEntries.size();
utils::AddIncludePaths(PathStr, HOpts, Delm);
Preprocessor& PP = CI->getPreprocessor();
SourceManager& SM = PP.getSourceManager();
FileManager& FM = SM.getFileManager();
HeaderSearch& HSearch = PP.getHeaderSearchInfo();
const bool isFramework = false;
// Add all the new entries into Preprocessor
for (const size_t N = HOpts.UserEntries.size(); Idx < N; ++Idx) {
const HeaderSearchOptions::Entry& E = HOpts.UserEntries[Idx];
if (const clang::DirectoryEntry *DE = FM.getDirectory(E.Path)) {
HSearch.AddSearchPath(DirectoryLookup(DE, SrcMgr::C_User, isFramework),
E.Group == frontend::Angled);
}
}
}
void Interpreter::AddIncludePath(llvm::StringRef PathsStr) {
return AddIncludePaths(PathsStr, nullptr);
}
void Interpreter::DumpIncludePath(llvm::raw_ostream* S) {
utils::DumpIncludePaths(getCI()->getHeaderSearchOpts(), S ? *S : cling::outs(),
true /*withSystem*/, true /*withFlags*/);
}
// FIXME: Add stream argument and move DumpIncludePath path here.
void Interpreter::dump(llvm::StringRef what, llvm::StringRef filter) {
llvm::raw_ostream &where = cling::log();
if (what.equals("asttree")) {
std::unique_ptr<clang::ASTConsumer> printer =
clang::CreateASTDumper(filter, true /*DumpDecls*/,
false /*Deserialize*/,
false /*DumpLookups*/);
printer->HandleTranslationUnit(getSema().getASTContext());
} else if (what.equals("ast"))
getSema().getASTContext().PrintStats();
else if (what.equals("decl"))
ClangInternalState::printLookupTables(where, getSema().getASTContext());
else if (what.equals("undo"))
m_IncrParser->printTransactionStructure();
}
void Interpreter::storeInterpreterState(const std::string& name) const {
// This may induce deserialization
PushTransactionRAII RAII(this);
CodeGenerator* CG = m_IncrParser->getCodeGenerator();
ClangInternalState* state
= new ClangInternalState(getCI()->getASTContext(),
getCI()->getPreprocessor(),
getLastTransaction()->getModule(),
CG, name);
m_StoredStates.push_back(state);
}
void Interpreter::compareInterpreterState(const std::string &Name) const {
const auto Itr = std::find_if(
m_StoredStates.begin(), m_StoredStates.end(),
[&Name](const ClangInternalState *S) { return S->getName() == Name; });
if (Itr == m_StoredStates.end()) {
cling::errs() << "The store point name " << Name
<< " does not exist."
"Unbalanced store / compare\n";
return;
}
// This may induce deserialization
PushTransactionRAII RAII(this);
(*Itr)->compare(Name, m_Opts.Verbose());
}
void Interpreter::printIncludedFiles(llvm::raw_ostream& Out) const {
ClangInternalState::printIncludedFiles(Out, getCI()->getSourceManager());
}
void Interpreter::GetIncludePaths(llvm::SmallVectorImpl<std::string>& incpaths,
bool withSystem, bool withFlags) {
utils::CopyIncludePaths(getCI()->getHeaderSearchOpts(), incpaths,
withSystem, withFlags);
}
CompilerInstance* Interpreter::getCI() const {
return m_IncrParser->getCI();
}
CompilerInstance* Interpreter::getCIOrNull() const {
return m_IncrParser ? m_IncrParser->getCI() : nullptr;
}
Sema& Interpreter::getSema() const {
return getCI()->getSema();
}
DiagnosticsEngine& Interpreter::getDiagnostics() const {
return getCI()->getDiagnostics();
}
CompilationOptions Interpreter::makeDefaultCompilationOpts() const {
CompilationOptions CO;
CO.DeclarationExtraction = 0;
CO.ValuePrinting = CompilationOptions::VPDisabled;
CO.CodeGeneration = m_IncrParser->hasCodeGenerator();
CO.DynamicScoping = isDynamicLookupEnabled();
CO.Debug = isPrintingDebug();
CO.IgnorePromptDiags = !isRawInputEnabled();
CO.CheckPointerValidity = !isRawInputEnabled();
CO.OptLevel = getDefaultOptLevel();
return CO;
}
const MacroInfo* Interpreter::getMacro(llvm::StringRef Macro) const {
clang::Preprocessor& PP = getCI()->getPreprocessor();
if (IdentifierInfo* II = PP.getIdentifierInfo(Macro)) {
// If the information about this identifier is out of date, update it from
// the external source.
// FIXME: getIdentifierInfo will probably do this for us once we update
// clang. If so, please remove this manual update.
if (II->isOutOfDate())
PP.getExternalSource()->updateOutOfDateIdentifier(*II);
MacroDefinition MDef = PP.getMacroDefinition(II);
MacroInfo* MI = MDef.getMacroInfo();
return MI;
}
return nullptr;
}
std::string Interpreter::getMacroValue(llvm::StringRef Macro,
const char* Trim) const {
std::string Value;
if (const MacroInfo* MI = getMacro(Macro)) {
for (const clang::Token& Tok : MI->tokens()) {
llvm::SmallString<64> Buffer;
Macro = getCI()->getPreprocessor().getSpelling(Tok, Buffer);
if (!Value.empty())
Value += " ";
Value += Trim ? Macro.trim(Trim).str() : Macro.str();
}
}
return Value;
}
///\brief Maybe transform the input line to implement cint command line
/// semantics (declarations are global) and compile to produce a module.
///
Interpreter::CompilationResult
Interpreter::process(const std::string& input, Value* V /* = 0 */,
Transaction** T /* = 0 */,
bool disableValuePrinting /* = false*/) {
std::string wrapReadySource = input;
size_t wrapPoint = std::string::npos;
if (!isRawInputEnabled())
wrapPoint = utils::getWrapPoint(wrapReadySource, getCI()->getLangOpts());
if (isRawInputEnabled() || wrapPoint == std::string::npos) {
CompilationOptions CO = makeDefaultCompilationOpts();
CO.DeclarationExtraction = 0;
CO.ValuePrinting = 0;
CO.ResultEvaluation = 0;
return DeclareInternal(input, CO, T);
}
CompilationOptions CO = makeDefaultCompilationOpts();
CO.DeclarationExtraction = 1;
CO.ValuePrinting = disableValuePrinting ? CompilationOptions::VPDisabled
: CompilationOptions::VPAuto;
CO.ResultEvaluation = (bool)V;
// CO.IgnorePromptDiags = 1; done by EvaluateInternal().
CO.CheckPointerValidity = 1;
if (EvaluateInternal(wrapReadySource, CO, V, T, wrapPoint)
== Interpreter::kFailure) {
return Interpreter::kFailure;
}
return Interpreter::kSuccess;
}
Interpreter::CompilationResult
Interpreter::parse(const std::string& input, Transaction** T /*=0*/) const {
CompilationOptions CO = makeDefaultCompilationOpts();
CO.CodeGeneration = 0;
CO.DeclarationExtraction = 0;
CO.ValuePrinting = 0;
CO.ResultEvaluation = 0;
return DeclareInternal(input, CO, T);
}
Interpreter::CompilationResult
Interpreter::loadModuleForHeader(const std::string& headerFile) {
Preprocessor& PP = getCI()->getPreprocessor();
//Copied from clang's PPDirectives.cpp
bool isAngled = false;
// Clang doc says:
// "LookupFrom is set when this is a \#include_next directive, it specifies
// the file to start searching from."
const DirectoryLookup* FromDir = 0;
const FileEntry* FromFile = 0;
const DirectoryLookup* CurDir = 0;
ModuleMap::KnownHeader suggestedModule;
// PP::LookupFile uses it to issue 'nice' diagnostic
SourceLocation fileNameLoc;
PP.LookupFile(fileNameLoc, headerFile, isAngled, FromDir, FromFile, CurDir,
/*SearchPath*/0, /*RelativePath*/ 0, &suggestedModule,
0 /*IsMapped*/,
/*SkipCache*/false, /*OpenFile*/ false, /*CacheFail*/ false);
if (!suggestedModule)
return Interpreter::kFailure;
// Copied from PPDirectives.cpp
SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> path;
for (Module *mod = suggestedModule.getModule(); mod; mod = mod->Parent) {
IdentifierInfo* II
= &getSema().getPreprocessor().getIdentifierTable().get(mod->Name);
path.push_back(std::make_pair(II, fileNameLoc));
}
std::reverse(path.begin(), path.end());
// Pretend that the module came from an inclusion directive, so that clang
// will create an implicit import declaration to capture it in the AST.
bool isInclude = true;
SourceLocation includeLoc;
if (getCI()->loadModule(includeLoc, path, Module::AllVisible, isInclude)) {
// After module load we need to "force" Sema to generate the code for
// things like dynamic classes.
getSema().ActOnEndOfTranslationUnit();
return Interpreter::kSuccess;
}
return Interpreter::kFailure;
}
Interpreter::CompilationResult
Interpreter::parseForModule(const std::string& input) {
CompilationOptions CO = makeDefaultCompilationOpts();
CO.CodeGenerationForModule = 1;
CO.DeclarationExtraction = 0;
CO.ValuePrinting = 0;
CO.ResultEvaluation = 0;
// When doing parseForModule avoid warning about the user code
// being loaded ... we probably might as well extend this to
// ALL warnings ... but this will suffice for now (working
// around a real bug in QT :().
DiagnosticsEngine& Diag = getDiagnostics();
Diag.setSeverity(clang::diag::warn_field_is_uninit,
clang::diag::Severity::Ignored, SourceLocation());
CompilationResult Result = DeclareInternal(input, CO);
Diag.setSeverity(clang::diag::warn_field_is_uninit,
clang::diag::Severity::Warning, SourceLocation());
return Result;
}
Interpreter::CompilationResult
Interpreter::CodeCompleteInternal(const std::string& input, unsigned offset) {
CompilationOptions CO = makeDefaultCompilationOpts();
CO.DeclarationExtraction = 0;
CO.ValuePrinting = 0;
CO.ResultEvaluation = 0;
CO.CheckPointerValidity = 0;
std::string wrapped = input;
size_t wrapPos = utils::getWrapPoint(wrapped, getCI()->getLangOpts());
const std::string& Src = WrapInput(wrapped, wrapped, wrapPos);
CO.CodeCompletionOffset = offset + wrapPos;
StateDebuggerRAII stateDebugger(this);
// This triggers the FileEntry to be created and the completion
// point to be set in clang.
m_IncrParser->Compile(Src, CO);
return kSuccess;
}
Interpreter::CompilationResult
Interpreter::declare(const std::string& input, Transaction** T/*=0 */) {
CompilationOptions CO = makeDefaultCompilationOpts();
CO.DeclarationExtraction = 0;
CO.ValuePrinting = 0;
CO.ResultEvaluation = 0;
CO.CheckPointerValidity = 0;
return DeclareInternal(input, CO, T);
}
Interpreter::CompilationResult
Interpreter::evaluate(const std::string& input, Value& V) {
// Here we might want to enforce further restrictions like: Only one
// ExprStmt can be evaluated and etc. Such enforcement cannot happen in the
// worker, because it is used from various places, where there is no such
// rule
CompilationOptions CO = makeDefaultCompilationOpts();
CO.DeclarationExtraction = 0;
CO.ValuePrinting = 0;
CO.ResultEvaluation = 1;
return EvaluateInternal(input, CO, &V);
}
Interpreter::CompilationResult
Interpreter::codeComplete(const std::string& line, size_t& cursor,
std::vector<std::string>& completions) const {
const char * const argV = "cling";
std::string resourceDir = this->getCI()->getHeaderSearchOpts().ResourceDir;
// Remove the extra 3 directory names "/lib/clang/3.9.0"
StringRef parentResourceDir = llvm::sys::path::parent_path(
llvm::sys::path::parent_path(
llvm::sys::path::parent_path(resourceDir)));
std::string llvmDir = parentResourceDir.str();
Interpreter childInterpreter(*this, 1, &argV, llvmDir.c_str());
if (!childInterpreter.isValid())
return kFailure;
auto childCI = childInterpreter.getCI();
clang::Sema &childSemaRef = childCI->getSema();
// Create the CodeCompleteConsumer with InterpreterCallbacks
// from the parent interpreter and set the consumer for the child
// interpreter.
ClingCodeCompleteConsumer* consumer = new ClingCodeCompleteConsumer(
getCI()->getFrontendOpts().CodeCompleteOpts, completions);
// Child interpreter CI will own consumer!
childCI->setCodeCompletionConsumer(consumer);
childSemaRef.CodeCompleter = consumer;
// Ignore diagnostics when we tab complete.
// This is because we get redefinition errors due to the import of the decls.
clang::IgnoringDiagConsumer* ignoringDiagConsumer =
new clang::IgnoringDiagConsumer();
childSemaRef.getDiagnostics().setClient(ignoringDiagConsumer, true);
DiagnosticsEngine& parentDiagnostics = this->getCI()->getSema().getDiagnostics();
std::unique_ptr<DiagnosticConsumer> ownerDiagConsumer =
parentDiagnostics.takeClient();
auto clientDiagConsumer = parentDiagnostics.getClient();
parentDiagnostics.setClient(ignoringDiagConsumer, /*owns*/ false);
// The child will desirialize decls from *this. We need a transaction RAII.
PushTransactionRAII RAII(this);
// Triger the code completion.
childInterpreter.CodeCompleteInternal(line, cursor);
// Restore the original diagnostics client for parent interpreter.
parentDiagnostics.setClient(clientDiagConsumer,
ownerDiagConsumer.release() != nullptr);
parentDiagnostics.Reset(/*soft=*/true);
return kSuccess;
}
Interpreter::CompilationResult
Interpreter::echo(const std::string& input, Value* V /* = 0 */) {
CompilationOptions CO = makeDefaultCompilationOpts();
CO.DeclarationExtraction = 0;
CO.ValuePrinting = CompilationOptions::VPEnabled;
CO.ResultEvaluation = (bool)V;
return EvaluateInternal(input, CO, V);
}
Interpreter::CompilationResult
Interpreter::execute(const std::string& input) {
CompilationOptions CO = makeDefaultCompilationOpts();
CO.DeclarationExtraction = 0;
CO.ValuePrinting = 0;
CO.ResultEvaluation = 0;
CO.DynamicScoping = 0;
return EvaluateInternal(input, CO);
}
Interpreter::CompilationResult Interpreter::emitAllDecls(Transaction* T) {
assert(!isInSyntaxOnlyMode() && "No CodeGenerator?");
m_IncrParser->emitTransaction(T);
m_IncrParser->addTransaction(T);
T->setState(Transaction::kCollecting);
auto PRT = m_IncrParser->endTransaction(T);
m_IncrParser->commitTransaction(PRT);
if ((T = PRT.getPointer()))
if (executeTransaction(*T))
return Interpreter::kSuccess;
return Interpreter::kFailure;
}
static void makeUniqueName(llvm::raw_ostream &Strm, unsigned long long ID) {
Strm << utils::Synthesize::UniquePrefix << ID;
}
static std::string makeUniqueWrapper(unsigned long long ID) {
cling::ostrstream Strm;
Strm << "void ";
makeUniqueName(Strm, ID);
Strm << "(void* vpClingValue) {\n ";
return Strm.str();
}
void Interpreter::createUniqueName(std::string &Out) {
llvm::raw_string_ostream Strm(Out);
makeUniqueName(Strm, m_UniqueCounter++);
}
bool Interpreter::isUniqueName(llvm::StringRef name) {
return name.startswith(utils::Synthesize::UniquePrefix);
}
clang::SourceLocation Interpreter::getSourceLocation(bool skipWrapper) const {
const Transaction* T = getLatestTransaction();
if (!T)
return SourceLocation();
const SourceManager &SM = getCI()->getSourceManager();
if (skipWrapper) {
return T->getSourceStart(SM).getLocWithOffset(
makeUniqueWrapper(m_UniqueCounter).size());
}
return T->getSourceStart(SM);
}
const std::string& Interpreter::WrapInput(const std::string& Input,
std::string& Output,
size_t& WrapPoint) const {
// If wrapPoint is > length of input, nothing is wrapped!
if (WrapPoint < Input.size()) {
const std::string Header = makeUniqueWrapper(m_UniqueCounter++);
// Suppport Input and Output begin the same string
std::string Wrapper = Input.substr(WrapPoint);
Wrapper.insert(0, Header);
Wrapper.append("\n;\n}");
Wrapper.insert(0, Input.substr(0, WrapPoint));
Wrapper.swap(Output);
WrapPoint += Header.size();
return Output;
}
// in-case std::string::npos was passed
WrapPoint = 0;
return Input;
}
Interpreter::ExecutionResult
Interpreter::RunFunction(const FunctionDecl* FD, Value* res /*=0*/) {
if (getDiagnostics().hasErrorOccurred())
return kExeCompilationError;
if (isInSyntaxOnlyMode()) {
return kExeNoCodeGen;
}
if (!FD)
return kExeUnkownFunction;
std::string mangledNameIfNeeded;
utils::Analyze::maybeMangleDeclName(FD, mangledNameIfNeeded);
IncrementalExecutor::ExecutionResult ExeRes =
m_Executor->executeWrapper(mangledNameIfNeeded, res);
return ConvertExecutionResult(ExeRes);
}
const FunctionDecl* Interpreter::DeclareCFunction(StringRef name,
StringRef code,
bool withAccessControl) {
/*
In CallFunc we currently always (intentionally and somewhat necessarily)
always fully specify member function template, however this can lead to
an ambiguity with a class template. For example in
roottest/cling/functionTemplate we get:
input_line_171:3:15: warning: lookup of 'set' in member access expression
is ambiguous; using member of 't'
((t*)obj)->set<int>(*(int*)args[0]);
^
roottest/cling/functionTemplate/t.h:19:9: note: lookup in the object type
't' refers here
void set(T targ) {
^
/usr/include/c++/4.4.5/bits/stl_set.h:87:11: note: lookup from the
current scope refers here
class set
^
This is an intention warning implemented in clang, see
http://llvm.org/viewvc/llvm-project?view=revision&revision=105518
which 'should have been' an error:
C++ [basic.lookup.classref] requires this to be an error, but,
because it's hard to work around, Clang downgrades it to a warning as
an extension.</p>
// C++98 [basic.lookup.classref]p1:
// In a class member access expression (5.2.5), if the . or -> token is
// immediately followed by an identifier followed by a <, the identifier
// must be looked up to determine whether the < is the beginning of a
// template argument list (14.2) or a less-than operator. The identifier
// is first looked up in the class of the object expression. If the
// identifier is not found, it is then looked up in the context of the
// entire postfix-expression and shall name a class or function template. If
// the lookup in the class of the object expression finds a template, the
// name is also looked up in the context of the entire postfix-expression
// and
// -- if the name is not found, the name found in the class of the
// object expression is used, otherwise
// -- if the name is found in the context of the entire postfix-expression
// and does not name a class template, the name found in the class of the
// object expression is used, otherwise
// -- if the name found is a class template, it must refer to the same