/
Interpreter.cpp
1829 lines (1561 loc) · 66.4 KB
/
Interpreter.cpp
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 "EnterUserCodeRAII.h"
#include "ExternalInterpreterSource.h"
#include "ForwardDeclPrinter.h"
#include "IncrementalCUDADeviceCompiler.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/Exception.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/Lex/HeaderSearch.h"
#include "clang/Lex/HeaderSearchOptions.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 <sstream>
#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() : nullptr, 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->getNextAvailableUniqueSourceLoc();
}
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;
}
static void setupCallbacks(Interpreter& Interp,
const Interpreter* parentInterp) {
// We need InterpreterCallbacks only if it is a parent Interpreter.
if (parentInterp) return;
// Disable suggestions for ROOT
bool showSuggestions =
!llvm::StringRef(ClingStringify(CLING_VERSION)).startswith("ROOT");
std::unique_ptr<InterpreterCallbacks> AutoLoadCB(
new AutoloadCallback(&Interp, showSuggestions));
Interp.setCallbacks(std::move(AutoLoadCB));
}
Interpreter::Interpreter(int argc, const char* const *argv,
const char* llvmdir /*= 0*/,
const ModuleFileExtensions& moduleExtensions,
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_RedefinitionAllowed(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, moduleExtensions));
if (!m_IncrParser->isValid(false))
return;
// Initialize the opt level to what CodeGenOpts says.
if (m_OptLevel == -1)
setDefaultOptLevel(getCI()->getCodeGenOpts().OptimizationLevel);
if (!isInSyntaxOnlyMode() && m_Opts.CompilerOpts.CUDAHost) {
// Create temporary folder for all files, which the CUDA device compiler
// will generate.
llvm::SmallString<256> TmpPath;
llvm::StringRef sep = llvm::sys::path::get_separator().data();
llvm::sys::path::system_temp_directory(false, TmpPath);
TmpPath.append(sep.data());
TmpPath.append("cling-%%%%");
TmpPath.append(sep.data());
llvm::SmallString<256> TmpFolder;
llvm::sys::fs::createUniqueFile(TmpPath.c_str(), TmpFolder);
llvm::sys::fs::create_directory(TmpFolder);
// The CUDA fatbin file is the connection beetween the CUDA device
// compiler and the CodeGen of cling. The file will every time reused.
if (getCI()->getCodeGenOpts().CudaGpuBinaryFileNames.empty())
getCI()->getCodeGenOpts().CudaGpuBinaryFileNames.push_back(
std::string(TmpFolder.c_str()) + "cling.fatbin");
m_CUDACompiler.reset(new IncrementalCUDADeviceCompiler(
TmpFolder.c_str(), m_OptLevel, m_Opts, *(getCI())));
}
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;
}
bool usingCxxModules = getSema().getLangOpts().Modules;
if (usingCxxModules) {
// Explicitly create the modulemanager now. If we would create it later
// implicitly then it would just overwrite our callbacks we set below.
m_IncrParser->getCI()->createModuleManager();
// When using C++ modules, we setup the callbacks now that we have them
// ready before we parse code for the first time. Without C++ modules
// we can't setup the calls now because the clang PCH currently just
// overwrites it in the Initialize method and we have no simple way to
// initialize them earlier. We handle the non-modules case below.
setupCallbacks(*this, parentInterp);
}
if(m_Opts.CompilerOpts.CUDAHost){
if(m_DyLibManager->loadLibrary("libcudart.so", true) ==
cling::DynamicLibraryManager::LoadLibResult::kLoadLibNotFound){
llvm::errs() << "Error: libcudart.so not found!\n" <<
"Please add the cuda lib path to LD_LIBRARY_PATH or set it via -L argument.\n";
}
}
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;
}
// When not using C++ modules, we now have a PCH and we can safely setup
// our callbacks without fearing that they get overwritten by clang code.
// The modules setup is handled above.
if (!usingCxxModules) {
setupCallbacks(*this, parentInterp);
}
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() && !m_Opts.CompilerOpts.CUDADevice) {
if (const Transaction* T = getLastTransaction()) {
if (auto M = T->getModule()) {
for (const llvm::StringRef& Sym : Syms) {
const llvm::GlobalValue* GV = M->getNamedValue(Sym);
#if defined(__linux__)
// 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";
}
}
}
}
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*/,
const ModuleFileExtensions& moduleExtensions/*={}*/,
bool noRuntime /*= true*/) :
Interpreter(argc, argv, llvmdir, moduleExtensions, 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();
// LookupHelper's ~Parser needs the PP from IncrParser's CI, so do this
// first:
m_LookupHelper.reset();
ShutDown();
// 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) {
// The Initialize() function is called twice in CUDA mode. The first time
// the host interpreter is initialized and the second time the device
// interpreter is initialized. Without this if statement, a redefinition
// error would occur because process(), declare(), and parse() are designed
// to process the code in the host and device interpreter when called by the
// host interpreter instance. This means that first the Initialize()
// function of the host interpreter is called and the initialization code is
// processed in the host and device interpreter. It then calls the
// Initialize() function of the device interpreter and throws an error
// because the code was already processed in the host Initialize() function.
//
// declare() is only used to generate a valid Transaction object
if (m_Opts.CompilerOpts.CUDADevice) {
Transaction* T;
declare("", &T);
return T;
}
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(__linux__)
const char* LinkageCxx = "extern \"C++\"";
const char* Attr = LangOpts.CPlusPlus ? " throw () " : "";
#else
const char* LinkageCxx = Linkage;
const char* Attr = "";
#endif
#if defined(__GLIBCXX__)
const char* cxa_atexit_is_noexcept = LangOpts.CPlusPlus ? " noexcept" : "";
#else
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 _MSC_VER
// According to the PE Format spec, in "The .tls Section"
// (http://www.microsoft.com/whdc/system/platform/firmware/PECOFF.mspx):
// 2. When a thread is created, the loader communicates the address
// of the thread's TLS array by placing the address of the thread
// environment block (TEB) in the FS register. A pointer to the TLS
// array is at the offset of 0x2C from the beginning of TEB. This
// behavior is Intel x86-specific.
static const unsigned long _tls_array = 0x2C;
m_Executor->addSymbol("_tls_array", (void *)&_tls_array, true);
#endif
#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::ShutDown() {
// Model the shutdown actions done in FrontendAction::EndSourceFile
if (CompilerInstance* CI = getCIOrNull()) {
CI->getDiagnostics().getClient()->EndSourceFile();
if (CI->hasPreprocessor())
CI->getPreprocessor().EndSourceFile();
bool DisableFree = CI->getFrontendOpts().DisableFree;
if (DisableFree) {
CI->resetAndLeakSema();
CI->resetAndLeakASTContext();
BuryPointer(CI->takeASTConsumer().get());
} else {
CI->setSema(nullptr);
CI->setASTContext(nullptr);
CI->setASTConsumer(nullptr);
}
if (CI->getFrontendOpts().ShowStats) {
llvm::errs() << "\nSTATISTICS \n";
CI->getPreprocessor().PrintStats();
CI->getPreprocessor().getIdentifierTable().PrintStats();
CI->getPreprocessor().getHeaderSearchInfo().PrintStats();
CI->getSourceManager().PrintStats();
llvm::errs() << "\n";
}
// Cleanup the output streams, and erase the output files if instructed by
// the FrontendAction.
bool shouldEraseOutputFiles = CI->getDiagnostics().hasErrorOccurred();
CI->clearOutputFiles(/*EraseFiles=*/shouldEraseOutputFiles);
LangOptions& LO = CI->getLangOpts();
if (!LO.getCompilingModule() != clang::LangOptions::CMK_None) {
if (DisableFree) {
CI->resetAndLeakPreprocessor();
CI->resetAndLeakSourceManager();
CI->resetAndLeakFileManager();
} else {
CI->setPreprocessor(nullptr);
CI->setSourceManager(nullptr);
CI->setFileManager(nullptr);
}
}
LO.setCompilingModule(clang::LangOptions::CMK_None);
}
}
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);
}
}
if (m_CUDACompiler)
m_CUDACompiler->getPTXInterpreter()->AddIncludePaths(PathStr, Delm);
}
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();
// `.stats decl' and `.stats asttree FILTER' cause deserialization; force transaction
PushTransactionRAII RAII(this);
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().get(), 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());
}
namespace valuePrinterInternal {
void declarePrintValue(Interpreter &Interp);
}
std::string Interpreter::toString(const char* type, void* obj) {
LockCompilationDuringUserCodeExecutionRAII LCDUCER(*this);
cling::valuePrinterInternal::declarePrintValue(*this);
std::string buf, ret;
llvm::raw_string_ostream ss(buf);
ss << "*((std::string*)" << &ret << ") = cling::printValue((" << type << "*)"
<< obj << ");";
CompilationResult result = process(ss.str().c_str());
if (result != cling::Interpreter::kSuccess)
llvm::errs() << "Error in Interpreter::toString: the input " << ss.str()
<< " cannot be evaluated";
return ret;
}
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.EnableShadowing = 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*/) {
if (!isInSyntaxOnlyMode() && m_Opts.CompilerOpts.CUDAHost)
m_CUDACompiler->process(input);
std::string wrapReadySource = input;
size_t wrapPoint = std::string::npos;
if (!isRawInputEnabled())
wrapPoint = utils::getWrapPoint(wrapReadySource, getCI()->getLangOpts());
CompilationOptions CO = makeDefaultCompilationOpts();
CO.EnableShadowing = m_RedefinitionAllowed && !isRawInputEnabled();
if (isRawInputEnabled() || wrapPoint == std::string::npos) {
CO.DeclarationExtraction = 0;
CO.ValuePrinting = 0;
CO.ResultEvaluation = 0;
return DeclareInternal(input, CO, T);
}
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 {
if (!isInSyntaxOnlyMode() && m_Opts.CompilerOpts.CUDAHost)
m_CUDACompiler->parse(input);
CompilationOptions CO = makeDefaultCompilationOpts();
CO.CodeGeneration = 0;
CO.DeclarationExtraction = 0;
CO.ValuePrinting = 0;
CO.ResultEvaluation = 0;
return DeclareInternal(input, CO, T);
}
///\returns true if the module was loaded.
bool Interpreter::loadModule(const std::string& moduleName,
bool complain /*= true*/) {
assert(getCI()->getLangOpts().Modules
&& "Function only relevant when C++ modules are turned on!");
Preprocessor& PP = getCI()->getPreprocessor();
HeaderSearch &HS = PP.getHeaderSearchInfo();
if (Module *M = HS.lookupModule(moduleName, /*AllowSearch*/true,
/*AllowExtraSearch*/ true))
return loadModule(M, complain);
if (complain)
llvm::errs() << "Module " << moduleName << " not found.\n";
return false;
}
bool Interpreter::loadModule(clang::Module* M, bool complain /* = true*/) {
assert(getCI()->getLangOpts().Modules
&& "Function only relevant when C++ modules are turned on!");
assert(M && "Module missing");
if (getSema().isModuleVisible(M))
return true;
// We cannot use #pragma clang module import because the on-demand modules
// may load a module in the middle of a function body for example. In this
// case this triggers an error:
// fatal error: import of module '...' appears within function '...'
//
// if (declare("#pragma clang module import \"" + M->Name + "\"") ==
// kSuccess)
// return true;
// FIXME: What about importing submodules such as std.blah. This disables
// this functionality.
Preprocessor& PP = getCI()->getPreprocessor();
IdentifierInfo* II = PP.getIdentifierInfo(M->Name);
SourceLocation ValidLoc = getNextAvailableLoc();
bool success =
!getSema().ActOnModuleImport(ValidLoc, ValidLoc,
std::make_pair(II, ValidLoc)).isInvalid();
if (success) {
// Also make the module visible in the preprocessor to export its macros.
PP.makeModuleVisible(M, ValidLoc);
return success;
}
if (complain) {
if (M->IsSystem)
llvm::errs() << "Failed to load module " << M->Name << "\n";
else
llvm::outs() << "Failed to load module " << M->Name << "\n";
}
return false;
}
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 */) {
if (!isInSyntaxOnlyMode() && m_Opts.CompilerOpts.CUDAHost)
m_CUDACompiler->declare(input);
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;
CO.CheckPointerValidity = 0;
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