forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 339
/
Copy pathClangExpressionParser.cpp
1591 lines (1374 loc) · 59.9 KB
/
ClangExpressionParser.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
//===-- ClangExpressionParser.cpp -----------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "clang/AST/ASTContext.h"
#include "clang/AST/ASTDiagnostic.h"
#include "clang/AST/ExternalASTSource.h"
#include "clang/AST/PrettyPrinter.h"
#include "clang/Basic/Builtins.h"
#include "clang/Basic/DarwinSDKInfo.h"
#include "clang/Basic/DiagnosticIDs.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/Version.h"
#include "clang/CodeGen/CodeGenAction.h"
#include "clang/CodeGen/ModuleBuilder.h"
#include "clang/Edit/Commit.h"
#include "clang/Edit/EditedSource.h"
#include "clang/Edit/EditsReceiver.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/CompilerInvocation.h"
#include "clang/Frontend/FrontendActions.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/Frontend/FrontendPluginRegistry.h"
#include "clang/Frontend/TextDiagnostic.h"
#include "clang/Frontend/TextDiagnosticBuffer.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Parse/ParseAST.h"
#include "clang/Rewrite/Core/Rewriter.h"
#include "clang/Rewrite/Frontend/FrontendActions.h"
#include "clang/Sema/CodeCompleteConsumer.h"
#include "clang/Sema/Sema.h"
#include "clang/Sema/SemaConsumer.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ExecutionEngine/ExecutionEngine.h"
#include "llvm/Support/CrashRecoveryContext.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/DynamicLibrary.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Signals.h"
#include "llvm/TargetParser/Host.h"
#include "ClangDiagnostic.h"
#include "ClangExpressionParser.h"
#include "ClangUserExpression.h"
#include "ASTUtils.h"
#include "ClangASTSource.h"
#include "ClangDiagnostic.h"
#include "ClangExpressionDeclMap.h"
#include "ClangExpressionHelper.h"
#include "ClangExpressionParser.h"
#include "ClangHost.h"
#include "ClangModulesDeclVendor.h"
#include "ClangPersistentVariables.h"
#include "IRDynamicChecks.h"
#include "IRForTarget.h"
#include "ModuleDependencyCollector.h"
#include "Plugins/TypeSystem/Clang/TypeSystemClang.h"
#include "lldb/Core/Debugger.h"
#include "lldb/Core/Disassembler.h"
#include "lldb/Core/Module.h"
#include "lldb/Expression/IRExecutionUnit.h"
#include "lldb/Expression/IRInterpreter.h"
#include "lldb/Host/File.h"
#include "lldb/Host/HostInfo.h"
#include "lldb/Symbol/SymbolVendor.h"
#include "lldb/Target/ExecutionContext.h"
#include "lldb/Target/ExecutionContextScope.h"
#include "lldb/Target/Language.h"
#include "lldb/Target/Process.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/ThreadPlanCallFunction.h"
#include "lldb/Utility/DataBufferHeap.h"
#include "lldb/Utility/LLDBAssert.h"
#include "lldb/Utility/LLDBLog.h"
#include "lldb/Utility/Log.h"
#include "lldb/Utility/Stream.h"
#include "lldb/Utility/StreamString.h"
#include "lldb/Utility/StringList.h"
#include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h"
#include "Plugins/Platform/MacOSX/PlatformDarwin.h"
#include "lldb/Utility/XcodeSDK.h"
#include <cctype>
#include <memory>
#include <optional>
using namespace clang;
using namespace llvm;
using namespace lldb_private;
//===----------------------------------------------------------------------===//
// Utility Methods for Clang
//===----------------------------------------------------------------------===//
class ClangExpressionParser::LLDBPreprocessorCallbacks : public PPCallbacks {
ClangModulesDeclVendor &m_decl_vendor;
ClangPersistentVariables &m_persistent_vars;
clang::SourceManager &m_source_mgr;
StreamString m_error_stream;
bool m_has_errors = false;
public:
LLDBPreprocessorCallbacks(ClangModulesDeclVendor &decl_vendor,
ClangPersistentVariables &persistent_vars,
clang::SourceManager &source_mgr)
: m_decl_vendor(decl_vendor), m_persistent_vars(persistent_vars),
m_source_mgr(source_mgr) {}
void moduleImport(SourceLocation import_location, clang::ModuleIdPath path,
const clang::Module * /*null*/) override {
// Ignore modules that are imported in the wrapper code as these are not
// loaded by the user.
llvm::StringRef filename =
m_source_mgr.getPresumedLoc(import_location).getFilename();
if (filename == ClangExpressionSourceCode::g_prefix_file_name)
return;
SourceModule module;
for (const std::pair<IdentifierInfo *, SourceLocation> &component : path)
module.path.push_back(ConstString(component.first->getName()));
StreamString error_stream;
ClangModulesDeclVendor::ModuleVector exported_modules;
if (!m_decl_vendor.AddModule(module, &exported_modules, m_error_stream))
m_has_errors = true;
for (ClangModulesDeclVendor::ModuleID module : exported_modules)
m_persistent_vars.AddHandLoadedClangModule(module);
}
bool hasErrors() { return m_has_errors; }
llvm::StringRef getErrorString() { return m_error_stream.GetString(); }
};
static void AddAllFixIts(ClangDiagnostic *diag, const clang::Diagnostic &Info) {
for (auto &fix_it : Info.getFixItHints()) {
if (fix_it.isNull())
continue;
diag->AddFixitHint(fix_it);
}
}
class ClangDiagnosticManagerAdapter : public clang::DiagnosticConsumer {
public:
ClangDiagnosticManagerAdapter(DiagnosticOptions &opts, StringRef filename)
: m_filename(filename) {
DiagnosticOptions *options = new DiagnosticOptions(opts);
options->ShowPresumedLoc = true;
options->ShowLevel = false;
m_os = std::make_shared<llvm::raw_string_ostream>(m_output);
m_passthrough =
std::make_shared<clang::TextDiagnosticPrinter>(*m_os, options);
}
void ResetManager(DiagnosticManager *manager = nullptr) {
m_manager = manager;
}
/// Returns the last error ClangDiagnostic message that the
/// DiagnosticManager received or a nullptr.
ClangDiagnostic *MaybeGetLastClangDiag() const {
if (m_manager->Diagnostics().empty())
return nullptr;
auto &diags = m_manager->Diagnostics();
for (auto it = diags.rbegin(); it != diags.rend(); it++) {
lldb_private::Diagnostic *diag = it->get();
if (ClangDiagnostic *clang_diag = dyn_cast<ClangDiagnostic>(diag)) {
if (clang_diag->GetSeverity() == lldb::eSeverityWarning)
return nullptr;
if (clang_diag->GetSeverity() == lldb::eSeverityError)
return clang_diag;
}
}
return nullptr;
}
void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
const clang::Diagnostic &Info) override {
if (!m_manager) {
// We have no DiagnosticManager before/after parsing but we still could
// receive diagnostics (e.g., by the ASTImporter failing to copy decls
// when we move the expression result ot the ScratchASTContext). Let's at
// least log these diagnostics until we find a way to properly render
// them and display them to the user.
Log *log = GetLog(LLDBLog::Expressions);
if (log) {
llvm::SmallVector<char, 32> diag_str;
Info.FormatDiagnostic(diag_str);
diag_str.push_back('\0');
const char *plain_diag = diag_str.data();
LLDB_LOG(log, "Received diagnostic outside parsing: {0}", plain_diag);
}
return;
}
// Update error/warning counters.
DiagnosticConsumer::HandleDiagnostic(DiagLevel, Info);
// Render diagnostic message to m_output.
m_output.clear();
m_passthrough->HandleDiagnostic(DiagLevel, Info);
m_os->flush();
DiagnosticDetail detail;
switch (DiagLevel) {
case DiagnosticsEngine::Level::Fatal:
case DiagnosticsEngine::Level::Error:
detail.severity = lldb::eSeverityError;
break;
case DiagnosticsEngine::Level::Warning:
detail.severity = lldb::eSeverityWarning;
break;
case DiagnosticsEngine::Level::Remark:
case DiagnosticsEngine::Level::Ignored:
detail.severity = lldb::eSeverityInfo;
break;
case DiagnosticsEngine::Level::Note:
// 'note:' diagnostics for errors and warnings can also contain Fix-Its.
// We add these Fix-Its to the last error diagnostic to make sure
// that we later have all Fix-Its related to an 'error' diagnostic when
// we apply them to the user expression.
auto *clang_diag = MaybeGetLastClangDiag();
// If we don't have a previous diagnostic there is nothing to do.
// If the previous diagnostic already has its own Fix-Its, assume that
// the 'note:' Fix-It is just an alternative way to solve the issue and
// ignore these Fix-Its.
if (!clang_diag || clang_diag->HasFixIts())
break;
// Ignore all Fix-Its that are not associated with an error.
if (clang_diag->GetSeverity() != lldb::eSeverityError)
break;
AddAllFixIts(clang_diag, Info);
break;
}
// ClangDiagnostic messages are expected to have no whitespace/newlines
// around them.
std::string stripped_output =
std::string(llvm::StringRef(m_output).trim());
// Translate the source location.
if (Info.hasSourceManager()) {
DiagnosticDetail::SourceLocation loc;
clang::SourceManager &sm = Info.getSourceManager();
const clang::SourceLocation sloc = Info.getLocation();
if (sloc.isValid()) {
const clang::FullSourceLoc fsloc(sloc, sm);
clang::PresumedLoc PLoc = fsloc.getPresumedLoc(true);
StringRef filename =
PLoc.isValid() ? PLoc.getFilename() : StringRef{};
loc.file = FileSpec(filename);
loc.line = fsloc.getSpellingLineNumber();
loc.column = fsloc.getSpellingColumnNumber();
loc.in_user_input = filename == m_filename;
loc.hidden = filename.starts_with("<lldb wrapper ");
// Find the range of the primary location.
for (const auto &range : Info.getRanges()) {
if (range.getBegin() == sloc) {
// FIXME: This is probably not handling wide characters correctly.
unsigned end_col = sm.getSpellingColumnNumber(range.getEnd());
if (end_col > loc.column)
loc.length = end_col - loc.column;
break;
}
}
detail.source_location = loc;
}
}
llvm::SmallString<0> msg;
Info.FormatDiagnostic(msg);
detail.message = msg.str();
detail.rendered = stripped_output;
auto new_diagnostic =
std::make_unique<ClangDiagnostic>(detail, Info.getID());
// Don't store away warning fixits, since the compiler doesn't have
// enough context in an expression for the warning to be useful.
// FIXME: Should we try to filter out FixIts that apply to our generated
// code, and not the user's expression?
if (detail.severity == lldb::eSeverityError)
AddAllFixIts(new_diagnostic.get(), Info);
m_manager->AddDiagnostic(std::move(new_diagnostic));
}
void BeginSourceFile(const LangOptions &LO, const Preprocessor *PP) override {
m_passthrough->BeginSourceFile(LO, PP);
}
void EndSourceFile() override { m_passthrough->EndSourceFile(); }
private:
DiagnosticManager *m_manager = nullptr;
std::shared_ptr<clang::TextDiagnosticPrinter> m_passthrough;
/// Output stream of m_passthrough.
std::shared_ptr<llvm::raw_string_ostream> m_os;
/// Output string filled by m_os.
std::string m_output;
StringRef m_filename;
};
/// Returns true if the SDK for the specified triple supports
/// builtin modules in system headers. This is used to decide
/// whether to pass -fbuiltin-headers-in-system-modules to
/// the compiler instance when compiling the `std` module.
static llvm::Expected<bool>
sdkSupportsBuiltinModules(lldb_private::Target &target) {
auto arch_spec = target.GetArchitecture();
auto const &triple = arch_spec.GetTriple();
auto module_sp = target.GetExecutableModule();
if (!module_sp)
return llvm::createStringError("Executable module not found.");
// Get SDK path that the target was compiled against.
auto platform_sp = target.GetPlatform();
if (!platform_sp)
return llvm::createStringError("No Platform plugin found on target.");
auto sdk_or_err = platform_sp->GetSDKPathFromDebugInfo(*module_sp);
if (!sdk_or_err)
return sdk_or_err.takeError();
// Use the SDK path from debug-info to find a local matching SDK directory.
auto sdk_path_or_err =
HostInfo::GetSDKRoot(HostInfo::SDKOptions{std::move(sdk_or_err->first)});
if (!sdk_path_or_err)
return sdk_path_or_err.takeError();
auto VFS = FileSystem::Instance().GetVirtualFileSystem();
if (!VFS)
return llvm::createStringError("No virtual filesystem available.");
// Extract SDK version from the /path/to/some.sdk/SDKSettings.json
auto parsed_or_err = clang::parseDarwinSDKInfo(*VFS, *sdk_path_or_err);
if (!parsed_or_err)
return parsed_or_err.takeError();
auto maybe_sdk = *parsed_or_err;
if (!maybe_sdk)
return llvm::createStringError("Couldn't find Darwin SDK info.");
return XcodeSDK::SDKSupportsBuiltinModules(triple, maybe_sdk->getVersion());
}
static void SetupModuleHeaderPaths(CompilerInstance *compiler,
std::vector<std::string> include_directories,
lldb::TargetSP target_sp) {
Log *log = GetLog(LLDBLog::Expressions);
HeaderSearchOptions &search_opts = compiler->getHeaderSearchOpts();
for (const std::string &dir : include_directories) {
search_opts.AddPath(dir, frontend::System, false, true);
LLDB_LOG(log, "Added user include dir: {0}", dir);
}
llvm::SmallString<128> module_cache;
const auto &props = ModuleList::GetGlobalModuleListProperties();
props.GetClangModulesCachePath().GetPath(module_cache);
search_opts.ModuleCachePath = std::string(module_cache.str());
LLDB_LOG(log, "Using module cache path: {0}", module_cache.c_str());
search_opts.ResourceDir = GetClangResourceDir().GetPath();
search_opts.ImplicitModuleMaps = true;
}
/// Iff the given identifier is a C++ keyword, remove it from the
/// identifier table (i.e., make the token a normal identifier).
static void RemoveCppKeyword(IdentifierTable &idents, llvm::StringRef token) {
// FIXME: 'using' is used by LLDB for local variables, so we can't remove
// this keyword without breaking this functionality.
if (token == "using")
return;
// GCC's '__null' is used by LLDB to define NULL/Nil/nil.
if (token == "__null")
return;
LangOptions cpp_lang_opts;
cpp_lang_opts.CPlusPlus = true;
cpp_lang_opts.CPlusPlus11 = true;
cpp_lang_opts.CPlusPlus20 = true;
clang::IdentifierInfo &ii = idents.get(token);
// The identifier has to be a C++-exclusive keyword. if not, then there is
// nothing to do.
if (!ii.isCPlusPlusKeyword(cpp_lang_opts))
return;
// If the token is already an identifier, then there is nothing to do.
if (ii.getTokenID() == clang::tok::identifier)
return;
// Otherwise the token is a C++ keyword, so turn it back into a normal
// identifier.
ii.revertTokenIDToIdentifier();
}
/// Remove all C++ keywords from the given identifier table.
static void RemoveAllCppKeywords(IdentifierTable &idents) {
#define KEYWORD(NAME, FLAGS) RemoveCppKeyword(idents, llvm::StringRef(#NAME));
#include "clang/Basic/TokenKinds.def"
}
/// Configures Clang diagnostics for the expression parser.
static void SetupDefaultClangDiagnostics(CompilerInstance &compiler) {
// List of Clang warning groups that are not useful when parsing expressions.
const std::vector<const char *> groupsToIgnore = {
"unused-value",
"odr",
"unused-getter-return-value",
};
for (const char *group : groupsToIgnore) {
compiler.getDiagnostics().setSeverityForGroup(
clang::diag::Flavor::WarningOrError, group,
clang::diag::Severity::Ignored, SourceLocation());
}
}
/// Returns a string representing current ABI.
///
/// \param[in] target_arch
/// The target architecture.
///
/// \return
/// A string representing target ABI for the current architecture.
static std::string GetClangTargetABI(const ArchSpec &target_arch) {
std::string abi;
if (target_arch.IsMIPS()) {
switch (target_arch.GetFlags() & ArchSpec::eMIPSABI_mask) {
case ArchSpec::eMIPSABI_N64:
abi = "n64";
break;
case ArchSpec::eMIPSABI_N32:
abi = "n32";
break;
case ArchSpec::eMIPSABI_O32:
abi = "o32";
break;
default:
break;
}
}
return abi;
}
static void SetupTargetOpts(CompilerInstance &compiler,
lldb_private::Target const &target) {
Log *log = GetLog(LLDBLog::Expressions);
ArchSpec target_arch = target.GetArchitecture();
const auto target_machine = target_arch.GetMachine();
if (target_arch.IsValid()) {
std::string triple = target_arch.GetTriple().str();
compiler.getTargetOpts().Triple = triple;
LLDB_LOGF(log, "Using %s as the target triple",
compiler.getTargetOpts().Triple.c_str());
} else {
// If we get here we don't have a valid target and just have to guess.
// Sometimes this will be ok to just use the host target triple (when we
// evaluate say "2+3", but other expressions like breakpoint conditions and
// other things that _are_ target specific really shouldn't just be using
// the host triple. In such a case the language runtime should expose an
// overridden options set (3), below.
compiler.getTargetOpts().Triple = llvm::sys::getDefaultTargetTriple();
LLDB_LOGF(log, "Using default target triple of %s",
compiler.getTargetOpts().Triple.c_str());
}
// Now add some special fixes for known architectures: Any arm32 iOS
// environment, but not on arm64
if (compiler.getTargetOpts().Triple.find("arm64") == std::string::npos &&
compiler.getTargetOpts().Triple.find("arm") != std::string::npos &&
compiler.getTargetOpts().Triple.find("ios") != std::string::npos) {
compiler.getTargetOpts().ABI = "apcs-gnu";
}
// Supported subsets of x86
if (target_machine == llvm::Triple::x86 ||
target_machine == llvm::Triple::x86_64) {
compiler.getTargetOpts().FeaturesAsWritten.push_back("+sse");
compiler.getTargetOpts().FeaturesAsWritten.push_back("+sse2");
}
// Set the target CPU to generate code for. This will be empty for any CPU
// that doesn't really need to make a special
// CPU string.
compiler.getTargetOpts().CPU = target_arch.GetClangTargetCPU();
// Set the target ABI
if (std::string abi = GetClangTargetABI(target_arch); !abi.empty())
compiler.getTargetOpts().ABI = std::move(abi);
}
static void SetupLangOpts(CompilerInstance &compiler,
ExecutionContextScope &exe_scope,
const Expression &expr) {
Log *log = GetLog(LLDBLog::Expressions);
// If the expression is being evaluated in the context of an existing stack
// frame, we introspect to see if the language runtime is available.
lldb::StackFrameSP frame_sp = exe_scope.CalculateStackFrame();
lldb::ProcessSP process_sp = exe_scope.CalculateProcess();
// Defaults to lldb::eLanguageTypeUnknown.
lldb::LanguageType frame_lang = expr.Language().AsLanguageType();
// Make sure the user hasn't provided a preferred execution language with
// `expression --language X -- ...`
if (frame_sp && frame_lang == lldb::eLanguageTypeUnknown)
frame_lang = frame_sp->GetLanguage().AsLanguageType();
if (process_sp && frame_lang != lldb::eLanguageTypeUnknown) {
LLDB_LOGF(log, "Frame has language of type %s",
lldb_private::Language::GetNameForLanguageType(frame_lang));
}
lldb::LanguageType language = expr.Language().AsLanguageType();
LangOptions &lang_opts = compiler.getLangOpts();
// FIXME: should this switch on frame_lang?
switch (language) {
case lldb::eLanguageTypeC:
case lldb::eLanguageTypeC89:
case lldb::eLanguageTypeC99:
case lldb::eLanguageTypeC11:
// FIXME: the following language option is a temporary workaround,
// to "ask for C, get C++."
// For now, the expression parser must use C++ anytime the language is a C
// family language, because the expression parser uses features of C++ to
// capture values.
lang_opts.CPlusPlus = true;
break;
case lldb::eLanguageTypeObjC:
lang_opts.ObjC = true;
// FIXME: the following language option is a temporary workaround,
// to "ask for ObjC, get ObjC++" (see comment above).
lang_opts.CPlusPlus = true;
// Clang now sets as default C++14 as the default standard (with
// GNU extensions), so we do the same here to avoid mismatches that
// cause compiler error when evaluating expressions (e.g. nullptr not found
// as it's a C++11 feature). Currently lldb evaluates C++14 as C++11 (see
// two lines below) so we decide to be consistent with that, but this could
// be re-evaluated in the future.
lang_opts.CPlusPlus11 = true;
break;
case lldb::eLanguageTypeC_plus_plus_20:
lang_opts.CPlusPlus20 = true;
[[fallthrough]];
case lldb::eLanguageTypeC_plus_plus_17:
// FIXME: add a separate case for CPlusPlus14. Currently folded into C++17
// because C++14 is the default standard for Clang but enabling CPlusPlus14
// expression evaluatino doesn't pass the test-suite cleanly.
lang_opts.CPlusPlus14 = true;
lang_opts.CPlusPlus17 = true;
[[fallthrough]];
case lldb::eLanguageTypeC_plus_plus:
case lldb::eLanguageTypeC_plus_plus_11:
case lldb::eLanguageTypeC_plus_plus_14:
lang_opts.CPlusPlus11 = true;
compiler.getHeaderSearchOpts().UseLibcxx = true;
[[fallthrough]];
case lldb::eLanguageTypeC_plus_plus_03:
lang_opts.CPlusPlus = true;
if (process_sp
// We're stopped in a frame without debug-info. The user probably
// intends to make global queries (which should include Objective-C).
&& !(frame_sp && frame_sp->HasDebugInformation()))
lang_opts.ObjC =
process_sp->GetLanguageRuntime(lldb::eLanguageTypeObjC) != nullptr;
break;
case lldb::eLanguageTypeObjC_plus_plus:
case lldb::eLanguageTypeUnknown:
default:
lang_opts.ObjC = true;
lang_opts.CPlusPlus = true;
lang_opts.CPlusPlus11 = true;
compiler.getHeaderSearchOpts().UseLibcxx = true;
break;
}
lang_opts.Bool = true;
lang_opts.WChar = true;
lang_opts.Blocks = true;
lang_opts.DebuggerSupport =
true; // Features specifically for debugger clients
if (expr.DesiredResultType() == Expression::eResultTypeId)
lang_opts.DebuggerCastResultToId = true;
lang_opts.CharIsSigned =
ArchSpec(compiler.getTargetOpts().Triple.c_str()).CharIsSignedByDefault();
// Spell checking is a nice feature, but it ends up completing a lot of types
// that we didn't strictly speaking need to complete. As a result, we spend a
// long time parsing and importing debug information.
lang_opts.SpellChecking = false;
if (process_sp && lang_opts.ObjC) {
if (auto *runtime = ObjCLanguageRuntime::Get(*process_sp)) {
switch (runtime->GetRuntimeVersion()) {
case ObjCLanguageRuntime::ObjCRuntimeVersions::eAppleObjC_V2:
lang_opts.ObjCRuntime.set(ObjCRuntime::MacOSX, VersionTuple(10, 7));
break;
case ObjCLanguageRuntime::ObjCRuntimeVersions::eObjC_VersionUnknown:
case ObjCLanguageRuntime::ObjCRuntimeVersions::eAppleObjC_V1:
lang_opts.ObjCRuntime.set(ObjCRuntime::FragileMacOSX,
VersionTuple(10, 7));
break;
case ObjCLanguageRuntime::ObjCRuntimeVersions::eGNUstep_libobjc2:
lang_opts.ObjCRuntime.set(ObjCRuntime::GNUstep, VersionTuple(2, 0));
break;
}
if (runtime->HasNewLiteralsAndIndexing())
lang_opts.DebuggerObjCLiteral = true;
}
}
lang_opts.ThreadsafeStatics = false;
lang_opts.AccessControl = false; // Debuggers get universal access
lang_opts.DollarIdents = true; // $ indicates a persistent variable name
// We enable all builtin functions beside the builtins from libc/libm (e.g.
// 'fopen'). Those libc functions are already correctly handled by LLDB, and
// additionally enabling them as expandable builtins is breaking Clang.
lang_opts.NoBuiltin = true;
}
static void SetupImportStdModuleLangOpts(CompilerInstance &compiler,
lldb_private::Target &target) {
Log *log = GetLog(LLDBLog::Expressions);
LangOptions &lang_opts = compiler.getLangOpts();
lang_opts.Modules = true;
// We want to implicitly build modules.
lang_opts.ImplicitModules = true;
// To automatically import all submodules when we import 'std'.
lang_opts.ModulesLocalVisibility = false;
// We use the @import statements, so we need this:
// FIXME: We could use the modules-ts, but that currently doesn't work.
lang_opts.ObjC = true;
// Options we need to parse libc++ code successfully.
// FIXME: We should ask the driver for the appropriate default flags.
lang_opts.GNUMode = true;
lang_opts.GNUKeywords = true;
lang_opts.CPlusPlus11 = true;
if (auto supported_or_err = sdkSupportsBuiltinModules(target))
lang_opts.BuiltinHeadersInSystemModules = !*supported_or_err;
else
LLDB_LOG_ERROR(log, supported_or_err.takeError(),
"Failed to determine BuiltinHeadersInSystemModules when "
"setting up import-std-module: {0}");
// The Darwin libc expects this macro to be set.
lang_opts.GNUCVersion = 40201;
}
//===----------------------------------------------------------------------===//
// Implementation of ClangExpressionParser
//===----------------------------------------------------------------------===//
ClangExpressionParser::ClangExpressionParser(
ExecutionContextScope *exe_scope, Expression &expr,
bool generate_debug_info, std::vector<std::string> include_directories,
std::string filename)
: ExpressionParser(exe_scope, expr, generate_debug_info), m_compiler(),
m_pp_callbacks(nullptr),
m_include_directories(std::move(include_directories)),
m_filename(std::move(filename)) {
Log *log = GetLog(LLDBLog::Expressions);
// We can't compile expressions without a target. So if the exe_scope is
// null or doesn't have a target, then we just need to get out of here. I'll
// lldbassert and not make any of the compiler objects since
// I can't return errors directly from the constructor. Further calls will
// check if the compiler was made and
// bag out if it wasn't.
if (!exe_scope) {
lldbassert(exe_scope &&
"Can't make an expression parser with a null scope.");
return;
}
lldb::TargetSP target_sp;
target_sp = exe_scope->CalculateTarget();
if (!target_sp) {
lldbassert(target_sp.get() &&
"Can't make an expression parser with a null target.");
return;
}
// 1. Create a new compiler instance.
m_compiler = std::make_unique<CompilerInstance>();
// Make sure clang uses the same VFS as LLDB.
m_compiler->createFileManager(FileSystem::Instance().GetVirtualFileSystem());
// 2. Configure the compiler with a set of default options that are
// appropriate for most situations.
SetupTargetOpts(*m_compiler, *target_sp);
// 3. Create and install the target on the compiler.
m_compiler->createDiagnostics();
// Limit the number of error diagnostics we emit.
// A value of 0 means no limit for both LLDB and Clang.
m_compiler->getDiagnostics().setErrorLimit(target_sp->GetExprErrorLimit());
if (auto *target_info = TargetInfo::CreateTargetInfo(
m_compiler->getDiagnostics(),
m_compiler->getInvocation().TargetOpts)) {
if (log) {
LLDB_LOGF(log, "Target datalayout string: '%s'",
target_info->getDataLayoutString());
LLDB_LOGF(log, "Target ABI: '%s'", target_info->getABI().str().c_str());
LLDB_LOGF(log, "Target vector alignment: %d",
target_info->getMaxVectorAlign());
}
m_compiler->setTarget(target_info);
} else {
if (log)
LLDB_LOGF(log, "Failed to create TargetInfo for '%s'",
m_compiler->getTargetOpts().Triple.c_str());
lldbassert(false && "Failed to create TargetInfo.");
}
// 4. Set language options.
SetupLangOpts(*m_compiler, *exe_scope, expr);
auto *clang_expr = dyn_cast<ClangUserExpression>(&m_expr);
if (clang_expr && clang_expr->DidImportCxxModules()) {
LLDB_LOG(log, "Adding lang options for importing C++ modules");
SetupImportStdModuleLangOpts(*m_compiler, *target_sp);
SetupModuleHeaderPaths(m_compiler.get(), m_include_directories, target_sp);
}
// Set CodeGen options
m_compiler->getCodeGenOpts().EmitDeclMetadata = true;
m_compiler->getCodeGenOpts().InstrumentFunctions = false;
m_compiler->getCodeGenOpts().setFramePointer(
CodeGenOptions::FramePointerKind::All);
if (generate_debug_info)
m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::FullDebugInfo);
else
m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::NoDebugInfo);
// Disable some warnings.
SetupDefaultClangDiagnostics(*m_compiler);
// Inform the target of the language options
//
// FIXME: We shouldn't need to do this, the target should be immutable once
// created. This complexity should be lifted elsewhere.
m_compiler->getTarget().adjust(m_compiler->getDiagnostics(),
m_compiler->getLangOpts());
// 5. Set up the diagnostic buffer for reporting errors
auto diag_mgr = new ClangDiagnosticManagerAdapter(
m_compiler->getDiagnostics().getDiagnosticOptions(),
clang_expr ? clang_expr->GetFilename() : StringRef());
m_compiler->getDiagnostics().setClient(diag_mgr);
// 6. Set up the source management objects inside the compiler
m_compiler->createFileManager();
if (!m_compiler->hasSourceManager())
m_compiler->createSourceManager(m_compiler->getFileManager());
m_compiler->createPreprocessor(TU_Complete);
switch (expr.Language().AsLanguageType()) {
case lldb::eLanguageTypeC:
case lldb::eLanguageTypeC89:
case lldb::eLanguageTypeC99:
case lldb::eLanguageTypeC11:
case lldb::eLanguageTypeObjC:
// This is not a C++ expression but we enabled C++ as explained above.
// Remove all C++ keywords from the PP so that the user can still use
// variables that have C++ keywords as names (e.g. 'int template;').
RemoveAllCppKeywords(m_compiler->getPreprocessor().getIdentifierTable());
break;
default:
break;
}
if (auto *clang_persistent_vars = llvm::cast<ClangPersistentVariables>(
target_sp->GetPersistentExpressionStateForLanguage(
lldb::eLanguageTypeC))) {
if (std::shared_ptr<ClangModulesDeclVendor> decl_vendor =
clang_persistent_vars->GetClangModulesDeclVendor()) {
std::unique_ptr<PPCallbacks> pp_callbacks(
new LLDBPreprocessorCallbacks(*decl_vendor, *clang_persistent_vars,
m_compiler->getSourceManager()));
m_pp_callbacks =
static_cast<LLDBPreprocessorCallbacks *>(pp_callbacks.get());
m_compiler->getPreprocessor().addPPCallbacks(std::move(pp_callbacks));
}
}
// 7. Most of this we get from the CompilerInstance, but we also want to give
// the context an ExternalASTSource.
auto &PP = m_compiler->getPreprocessor();
auto &builtin_context = PP.getBuiltinInfo();
builtin_context.initializeBuiltins(PP.getIdentifierTable(),
m_compiler->getLangOpts());
m_compiler->createASTContext();
clang::ASTContext &ast_context = m_compiler->getASTContext();
m_ast_context = std::make_shared<TypeSystemClang>(
"Expression ASTContext for '" + m_filename + "'", ast_context);
std::string module_name("$__lldb_module");
m_llvm_context = std::make_unique<LLVMContext>();
m_code_generator.reset(CreateLLVMCodeGen(
m_compiler->getDiagnostics(), module_name,
&m_compiler->getVirtualFileSystem(), m_compiler->getHeaderSearchOpts(),
m_compiler->getPreprocessorOpts(), m_compiler->getCodeGenOpts(),
*m_llvm_context));
}
ClangExpressionParser::~ClangExpressionParser() = default;
namespace {
/// \class CodeComplete
///
/// A code completion consumer for the clang Sema that is responsible for
/// creating the completion suggestions when a user requests completion
/// of an incomplete `expr` invocation.
class CodeComplete : public CodeCompleteConsumer {
CodeCompletionTUInfo m_info;
std::string m_expr;
unsigned m_position = 0;
/// The printing policy we use when printing declarations for our completion
/// descriptions.
clang::PrintingPolicy m_desc_policy;
struct CompletionWithPriority {
CompletionResult::Completion completion;
/// See CodeCompletionResult::Priority;
unsigned Priority;
/// Establishes a deterministic order in a list of CompletionWithPriority.
/// The order returned here is the order in which the completions are
/// displayed to the user.
bool operator<(const CompletionWithPriority &o) const {
// High priority results should come first.
if (Priority != o.Priority)
return Priority > o.Priority;
// Identical priority, so just make sure it's a deterministic order.
return completion.GetUniqueKey() < o.completion.GetUniqueKey();
}
};
/// The stored completions.
/// Warning: These are in a non-deterministic order until they are sorted
/// and returned back to the caller.
std::vector<CompletionWithPriority> m_completions;
/// Returns true if the given character can be used in an identifier.
/// This also returns true for numbers because for completion we usually
/// just iterate backwards over iterators.
///
/// Note: lldb uses '$' in its internal identifiers, so we also allow this.
static bool IsIdChar(char c) {
return c == '_' || std::isalnum(c) || c == '$';
}
/// Returns true if the given character is used to separate arguments
/// in the command line of lldb.
static bool IsTokenSeparator(char c) { return c == ' ' || c == '\t'; }
/// Drops all tokens in front of the expression that are unrelated for
/// the completion of the cmd line. 'unrelated' means here that the token
/// is not interested for the lldb completion API result.
StringRef dropUnrelatedFrontTokens(StringRef cmd) const {
if (cmd.empty())
return cmd;
// If we are at the start of a word, then all tokens are unrelated to
// the current completion logic.
if (IsTokenSeparator(cmd.back()))
return StringRef();
// Remove all previous tokens from the string as they are unrelated
// to completing the current token.
StringRef to_remove = cmd;
while (!to_remove.empty() && !IsTokenSeparator(to_remove.back())) {
to_remove = to_remove.drop_back();
}
cmd = cmd.drop_front(to_remove.size());
return cmd;
}
/// Removes the last identifier token from the given cmd line.
StringRef removeLastToken(StringRef cmd) const {
while (!cmd.empty() && IsIdChar(cmd.back())) {
cmd = cmd.drop_back();
}
return cmd;
}
/// Attempts to merge the given completion from the given position into the
/// existing command. Returns the completion string that can be returned to
/// the lldb completion API.
std::string mergeCompletion(StringRef existing, unsigned pos,
StringRef completion) const {
StringRef existing_command = existing.substr(0, pos);
// We rewrite the last token with the completion, so let's drop that
// token from the command.
existing_command = removeLastToken(existing_command);
// We also should remove all previous tokens from the command as they
// would otherwise be added to the completion that already has the
// completion.
existing_command = dropUnrelatedFrontTokens(existing_command);
return existing_command.str() + completion.str();
}
public:
/// Constructs a CodeComplete consumer that can be attached to a Sema.
///
/// \param[out] expr
/// The whole expression string that we are currently parsing. This
/// string needs to be equal to the input the user typed, and NOT the
/// final code that Clang is parsing.
/// \param[out] position
/// The character position of the user cursor in the `expr` parameter.
///
CodeComplete(clang::LangOptions ops, std::string expr, unsigned position)
: CodeCompleteConsumer(CodeCompleteOptions()),
m_info(std::make_shared<GlobalCodeCompletionAllocator>()), m_expr(expr),
m_position(position), m_desc_policy(ops) {
// Ensure that the printing policy is producing a description that is as
// short as possible.
m_desc_policy.SuppressScope = true;
m_desc_policy.SuppressTagKeyword = true;
m_desc_policy.FullyQualifiedName = false;
m_desc_policy.TerseOutput = true;
m_desc_policy.IncludeNewlines = false;
m_desc_policy.UseVoidForZeroParams = false;
m_desc_policy.Bool = true;
}
/// \name Code-completion filtering
/// Check if the result should be filtered out.
bool isResultFilteredOut(StringRef Filter,
CodeCompletionResult Result) override {
// This code is mostly copied from CodeCompleteConsumer.
switch (Result.Kind) {
case CodeCompletionResult::RK_Declaration:
return !(
Result.Declaration->getIdentifier() &&
Result.Declaration->getIdentifier()->getName().starts_with(Filter));
case CodeCompletionResult::RK_Keyword:
return !StringRef(Result.Keyword).starts_with(Filter);
case CodeCompletionResult::RK_Macro:
return !Result.Macro->getName().starts_with(Filter);
case CodeCompletionResult::RK_Pattern:
return !StringRef(Result.Pattern->getAsString()).starts_with(Filter);
}
// If we trigger this assert or the above switch yields a warning, then
// CodeCompletionResult has been enhanced with more kinds of completion
// results. Expand the switch above in this case.
assert(false && "Unknown completion result type?");
// If we reach this, then we should just ignore whatever kind of unknown
// result we got back. We probably can't turn it into any kind of useful
// completion suggestion with the existing code.
return true;
}
private:
/// Generate the completion strings for the given CodeCompletionResult.
/// Note that this function has to process results that could come in
/// non-deterministic order, so this function should have no side effects.
/// To make this easier to enforce, this function and all its parameters