LLDB mainline
ClangExpressionParser.cpp
Go to the documentation of this file.
1//===-- ClangExpressionParser.cpp -----------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "clang/AST/ASTContext.h"
10#include "clang/AST/ASTDiagnostic.h"
11#include "clang/AST/ExternalASTSource.h"
12#include "clang/AST/PrettyPrinter.h"
13#include "clang/Basic/Builtins.h"
14#include "clang/Basic/DarwinSDKInfo.h"
15#include "clang/Basic/DiagnosticFrontend.h"
16#include "clang/Basic/DiagnosticIDs.h"
17#include "clang/Basic/IdentifierTable.h"
18#include "clang/Basic/SourceLocation.h"
19#include "clang/Basic/TargetInfo.h"
20#include "clang/Basic/Version.h"
21#include "clang/CodeGen/CodeGenAction.h"
22#include "clang/CodeGen/ModuleBuilder.h"
23#include "clang/Edit/Commit.h"
24#include "clang/Edit/EditedSource.h"
25#include "clang/Edit/EditsReceiver.h"
26#include "clang/Frontend/CompilerInstance.h"
27#include "clang/Frontend/CompilerInvocation.h"
28#include "clang/Frontend/FrontendActions.h"
29#include "clang/Frontend/FrontendPluginRegistry.h"
30#include "clang/Frontend/TextDiagnostic.h"
31#include "clang/Frontend/TextDiagnosticBuffer.h"
32#include "clang/Frontend/TextDiagnosticPrinter.h"
33#include "clang/Lex/Lexer.h"
34#include "clang/Lex/Preprocessor.h"
35#include "clang/Parse/ParseAST.h"
36#include "clang/Rewrite/Core/Rewriter.h"
37#include "clang/Rewrite/Frontend/FrontendActions.h"
38#include "clang/Sema/CodeCompleteConsumer.h"
39#include "clang/Sema/Sema.h"
40#include "clang/Sema/SemaConsumer.h"
41
42#include "llvm/ADT/StringRef.h"
43#include "llvm/ExecutionEngine/ExecutionEngine.h"
44#include "llvm/Support/CrashRecoveryContext.h"
45#include "llvm/Support/Debug.h"
46#include "llvm/Support/Error.h"
47#include "llvm/Support/FileSystem.h"
48#include "llvm/Support/TargetSelect.h"
49#include "llvm/TargetParser/Triple.h"
50
51#include "llvm/IR/LLVMContext.h"
52#include "llvm/IR/Module.h"
53#include "llvm/Support/DynamicLibrary.h"
54#include "llvm/Support/ErrorHandling.h"
55#include "llvm/Support/MemoryBuffer.h"
56#include "llvm/Support/Signals.h"
57#include "llvm/TargetParser/Host.h"
58
59#include "ClangDiagnostic.h"
61#include "ClangUserExpression.h"
62
63#include "ASTUtils.h"
64#include "ClangASTSource.h"
67#include "ClangHost.h"
70#include "IRDynamicChecks.h"
71#include "IRForTarget.h"
73
75#include "lldb/Core/Debugger.h"
77#include "lldb/Core/Module.h"
81#include "lldb/Host/File.h"
82#include "lldb/Host/HostInfo.h"
87#include "lldb/Target/Process.h"
88#include "lldb/Target/Target.h"
93#include "lldb/Utility/Log.h"
94#include "lldb/Utility/Stream.h"
97
100
101#include <cctype>
102#include <memory>
103#include <optional>
104
105using namespace clang;
106using namespace llvm;
107using namespace lldb_private;
108
109//===----------------------------------------------------------------------===//
110// Utility Methods for Clang
111//===----------------------------------------------------------------------===//
112
116 clang::SourceManager &m_source_mgr;
117 /// Accumulates error messages across all moduleImport calls.
119 bool m_has_errors = false;
120
121public:
123 ClangPersistentVariables &persistent_vars,
124 clang::SourceManager &source_mgr)
125 : m_decl_vendor(decl_vendor), m_persistent_vars(persistent_vars),
126 m_source_mgr(source_mgr) {}
127
128 void moduleImport(SourceLocation import_location, clang::ModuleIdPath path,
129 const clang::Module * /*null*/) override {
130 // Ignore modules that are imported in the wrapper code as these are not
131 // loaded by the user.
132 llvm::StringRef filename =
133 m_source_mgr.getPresumedLoc(import_location).getFilename();
135 return;
136
137 SourceModule module;
138
139 for (const IdentifierLoc &component : path)
140 module.path.push_back(
141 ConstString(component.getIdentifierInfo()->getName()));
142
144 if (auto err = m_decl_vendor.AddModule(module, &exported_modules)) {
145 m_has_errors = true;
146 m_error_stream.PutCString(llvm::toString(std::move(err)));
147 m_error_stream.PutChar('\n');
148 }
149
150 for (ClangModulesDeclVendor::ModuleID module : exported_modules)
151 m_persistent_vars.AddHandLoadedClangModule(module);
152 }
153
154 bool hasErrors() { return m_has_errors; }
155
156 llvm::StringRef getErrorString() { return m_error_stream.GetString(); }
157};
158
159static void AddAllFixIts(ClangDiagnostic *diag, const clang::Diagnostic &Info) {
160 for (auto &fix_it : Info.getFixItHints()) {
161 if (fix_it.isNull())
162 continue;
163 diag->AddFixitHint(fix_it);
164 }
165}
166
167class ClangDiagnosticManagerAdapter : public clang::DiagnosticConsumer {
168public:
169 ClangDiagnosticManagerAdapter(DiagnosticOptions &opts, StringRef filename)
170 : m_options(opts), m_filename(filename) {
171 m_options.ShowPresumedLoc = true;
172 m_options.ShowLevel = false;
173 m_os = std::make_unique<llvm::raw_string_ostream>(m_output);
175 std::make_unique<clang::TextDiagnosticPrinter>(*m_os, m_options);
176 }
177
178 void ResetManager(DiagnosticManager *manager = nullptr) {
179 m_manager = manager;
180 }
181
182 /// Returns the last error ClangDiagnostic message that the
183 /// DiagnosticManager received or a nullptr.
185 if (m_manager->Diagnostics().empty())
186 return nullptr;
187 auto &diags = m_manager->Diagnostics();
188 for (auto it = diags.rbegin(); it != diags.rend(); it++) {
189 lldb_private::Diagnostic *diag = it->get();
190 if (ClangDiagnostic *clang_diag = dyn_cast<ClangDiagnostic>(diag)) {
191 if (clang_diag->GetSeverity() == lldb::eSeverityWarning)
192 return nullptr;
193 if (clang_diag->GetSeverity() == lldb::eSeverityError)
194 return clang_diag;
195 }
196 }
197 return nullptr;
198 }
199
200 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
201 const clang::Diagnostic &Info) override {
202 if (!m_manager) {
203 // We have no DiagnosticManager before/after parsing but we still could
204 // receive diagnostics (e.g., by the ASTImporter failing to copy decls
205 // when we move the expression result ot the ScratchASTContext). Let's at
206 // least log these diagnostics until we find a way to properly render
207 // them and display them to the user.
209 if (log) {
210 llvm::SmallVector<char, 32> diag_str;
211 Info.FormatDiagnostic(diag_str);
212 diag_str.push_back('\0');
213 const char *plain_diag = diag_str.data();
214 LLDB_LOG(log, "Received diagnostic outside parsing: {0}", plain_diag);
215 }
216 return;
217 }
218
219 // Update error/warning counters.
220 DiagnosticConsumer::HandleDiagnostic(DiagLevel, Info);
221
222 // Render diagnostic message to m_output.
223 m_output.clear();
224 m_passthrough->HandleDiagnostic(DiagLevel, Info);
225
227 switch (DiagLevel) {
228 case DiagnosticsEngine::Level::Fatal:
229 case DiagnosticsEngine::Level::Error:
230 detail.severity = lldb::eSeverityError;
231 break;
232 case DiagnosticsEngine::Level::Warning:
234 break;
235 case DiagnosticsEngine::Level::Remark:
236 case DiagnosticsEngine::Level::Ignored:
237 detail.severity = lldb::eSeverityInfo;
238 break;
239 case DiagnosticsEngine::Level::Note:
240 // 'note:' diagnostics for errors and warnings can also contain Fix-Its.
241 // We add these Fix-Its to the last error diagnostic to make sure
242 // that we later have all Fix-Its related to an 'error' diagnostic when
243 // we apply them to the user expression.
244 auto *clang_diag = MaybeGetLastClangDiag();
245 // If we don't have a previous diagnostic there is nothing to do.
246 // If the previous diagnostic already has its own Fix-Its, assume that
247 // the 'note:' Fix-It is just an alternative way to solve the issue and
248 // ignore these Fix-Its.
249 if (!clang_diag || clang_diag->HasFixIts())
250 break;
251 // Ignore all Fix-Its that are not associated with an error.
252 if (clang_diag->GetSeverity() != lldb::eSeverityError)
253 break;
254 AddAllFixIts(clang_diag, Info);
255 break;
256 }
257 // ClangDiagnostic messages are expected to have no whitespace/newlines
258 // around them.
259 std::string stripped_output =
260 std::string(llvm::StringRef(m_output).trim());
261
262 // Translate the source location.
263 if (Info.hasSourceManager()) {
265 clang::SourceManager &sm = Info.getSourceManager();
266 const clang::SourceLocation sloc = Info.getLocation();
267 if (sloc.isValid()) {
268 const clang::FullSourceLoc fsloc(sloc, sm);
269 clang::PresumedLoc PLoc = fsloc.getPresumedLoc(true);
270 StringRef filename =
271 PLoc.isValid() ? PLoc.getFilename() : StringRef{};
272 loc.file = FileSpec(filename);
273 loc.line = fsloc.getSpellingLineNumber();
274 loc.column = fsloc.getSpellingColumnNumber();
275 loc.in_user_input = filename == m_filename;
276 loc.hidden = filename.starts_with("<lldb wrapper ");
277
278 // Find the range of the primary location.
279 for (const auto &range : Info.getRanges()) {
280 if (range.getBegin() != sloc)
281 continue;
282 SourceLocation end = range.getEnd();
283 if (range.isTokenRange())
284 end = clang::Lexer::getLocForEndOfToken(end, 0, sm, m_lang_opts);
285 // FIXME: This is probably not handling wide characters correctly.
286 unsigned end_col = sm.getSpellingColumnNumber(end);
287 // Ignore ranges that span multiple lines.
288 if (end_col != sm.getSpellingLineNumber(sloc))
289 break;
290 if (end_col > loc.column)
291 loc.length = end_col - loc.column;
292 break;
293 }
294 detail.source_location = loc;
295 }
296 }
297 llvm::SmallString<0> msg;
298 Info.FormatDiagnostic(msg);
299 detail.message = msg.str();
300 detail.rendered = stripped_output;
301 auto new_diagnostic =
302 std::make_unique<ClangDiagnostic>(detail, Info.getID());
303
304 // Don't store away warning fixits, since the compiler doesn't have
305 // enough context in an expression for the warning to be useful.
306 // FIXME: Should we try to filter out FixIts that apply to our generated
307 // code, and not the user's expression?
308 if (detail.severity == lldb::eSeverityError)
309 AddAllFixIts(new_diagnostic.get(), Info);
310
311 m_manager->AddDiagnostic(std::move(new_diagnostic));
312 }
313
314 void BeginSourceFile(const LangOptions &LO, const Preprocessor *PP) override {
315 m_lang_opts = LO;
316 m_passthrough->BeginSourceFile(LO, PP);
317 }
318
319 void EndSourceFile() override { m_passthrough->EndSourceFile(); }
320
321private:
323 DiagnosticOptions m_options;
324 LangOptions m_lang_opts;
325 /// Output string filled by m_os.
326 std::string m_output;
327 /// Output stream of m_passthrough.
328 std::unique_ptr<llvm::raw_string_ostream> m_os;
329 std::unique_ptr<clang::TextDiagnosticPrinter> m_passthrough;
330 StringRef m_filename;
331};
332
333static void SetupModuleHeaderPaths(CompilerInstance *compiler,
334 std::vector<std::string> include_directories,
335 lldb::TargetSP target_sp) {
337
338 HeaderSearchOptions &search_opts = compiler->getHeaderSearchOpts();
339
340 for (const std::string &dir : include_directories) {
341 search_opts.AddPath(dir, frontend::System, false, true);
342 LLDB_LOG(log, "Added user include dir: {0}", dir);
343 }
344
345 llvm::SmallString<128> module_cache;
346 const auto &props = ModuleList::GetGlobalModuleListProperties();
347 props.GetClangModulesCachePath().GetPath(module_cache);
348 search_opts.ModuleCachePath = std::string(module_cache.str());
349 LLDB_LOG(log, "Using module cache path: {0}", module_cache.c_str());
350
351 search_opts.ResourceDir = GetClangResourceDir().GetPath();
352
353 search_opts.ImplicitModuleMaps = true;
354}
355
356/// Iff the given identifier is a C++ keyword, remove it from the
357/// identifier table (i.e., make the token a normal identifier).
358static void RemoveCppKeyword(IdentifierTable &idents, llvm::StringRef token) {
359 // FIXME: 'using' is used by LLDB for local variables, so we can't remove
360 // this keyword without breaking this functionality.
361 if (token == "using")
362 return;
363 // GCC's '__null' is used by LLDB to define NULL/Nil/nil.
364 if (token == "__null")
365 return;
366
367 LangOptions cpp_lang_opts;
368 cpp_lang_opts.CPlusPlus = true;
369 cpp_lang_opts.CPlusPlus11 = true;
370 cpp_lang_opts.CPlusPlus20 = true;
371
372 clang::IdentifierInfo &ii = idents.get(token);
373 // The identifier has to be a C++-exclusive keyword. if not, then there is
374 // nothing to do.
375 if (!ii.isCPlusPlusKeyword(cpp_lang_opts))
376 return;
377 // If the token is already an identifier, then there is nothing to do.
378 if (ii.getTokenID() == clang::tok::identifier)
379 return;
380 // Otherwise the token is a C++ keyword, so turn it back into a normal
381 // identifier.
382 ii.revertTokenIDToIdentifier();
383}
384
385/// Remove all C++ keywords from the given identifier table.
386static void RemoveAllCppKeywords(IdentifierTable &idents) {
387#define KEYWORD(NAME, FLAGS) RemoveCppKeyword(idents, llvm::StringRef(#NAME));
388#include "clang/Basic/TokenKinds.def"
389}
390
391/// Configures Clang diagnostics for the expression parser.
392static void SetupDefaultClangDiagnostics(CompilerInstance &compiler) {
393 // List of Clang warning groups that are not useful when parsing expressions.
394 const std::vector<const char *> groupsToIgnore = {
395 "unused-value",
396 "odr",
397 "unused-getter-return-value",
398 };
399 for (const char *group : groupsToIgnore) {
400 compiler.getDiagnostics().setSeverityForGroup(
401 clang::diag::Flavor::WarningOrError, group,
402 clang::diag::Severity::Ignored, SourceLocation());
403 }
404}
405
406/// Returns a string representing current ABI.
407///
408/// \param[in] target_arch
409/// The target architecture.
410///
411/// \return
412/// A string representing target ABI for the current architecture.
413static std::string GetClangTargetABI(const ArchSpec &target_arch) {
414 if (target_arch.IsMIPS()) {
415 switch (target_arch.GetFlags() & ArchSpec::eMIPSABI_mask) {
417 return "n64";
419 return "n32";
421 return "o32";
422 default:
423 return {};
424 }
425 }
426
427 if (target_arch.GetTriple().isRISCV64()) {
428 switch (target_arch.GetFlags() & ArchSpec::eRISCV_float_abi_mask) {
430 return "lp64";
432 return "lp64f";
434 return "lp64d";
436 return "lp64q";
437 default:
438 return {};
439 }
440 }
441
442 if (target_arch.GetTriple().isRISCV32()) {
443 switch (target_arch.GetFlags() & ArchSpec::eRISCV_float_abi_mask) {
445 return "ilp32";
447 return "ilp32f";
449 return "ilp32d";
451 return "ilp32e";
452 default:
453 return {};
454 }
455 }
456
457 if (target_arch.GetTriple().isLoongArch64()) {
458 switch (target_arch.GetFlags() & ArchSpec::eLoongArch_abi_mask) {
460 return "lp64s";
462 return "lp64f";
464 return "lp64d";
465 default:
466 return {};
467 }
468 }
469
470 return {};
471}
472
473static void SetupTargetOpts(CompilerInstance &compiler,
474 lldb_private::Target const &target) {
476 ArchSpec target_arch = target.GetArchitecture();
477
478 const auto target_machine = target_arch.GetMachine();
479 if (target_arch.IsValid()) {
480 std::string triple = target_arch.GetTriple().str();
481 compiler.getTargetOpts().Triple = triple;
482 LLDB_LOGF(log, "Using %s as the target triple",
483 compiler.getTargetOpts().Triple.c_str());
484 } else {
485 // If we get here we don't have a valid target and just have to guess.
486 // Sometimes this will be ok to just use the host target triple (when we
487 // evaluate say "2+3", but other expressions like breakpoint conditions and
488 // other things that _are_ target specific really shouldn't just be using
489 // the host triple. In such a case the language runtime should expose an
490 // overridden options set (3), below.
491 compiler.getTargetOpts().Triple = llvm::sys::getDefaultTargetTriple();
492 LLDB_LOGF(log, "Using default target triple of %s",
493 compiler.getTargetOpts().Triple.c_str());
494 }
495 // Now add some special fixes for known architectures: Any arm32 iOS
496 // environment, but not on arm64
497 if (compiler.getTargetOpts().Triple.find("arm64") == std::string::npos &&
498 compiler.getTargetOpts().Triple.find("arm") != std::string::npos &&
499 compiler.getTargetOpts().Triple.find("ios") != std::string::npos) {
500 compiler.getTargetOpts().ABI = "apcs-gnu";
501 }
502 // Supported subsets of x86
503 if (target_machine == llvm::Triple::x86 ||
504 target_machine == llvm::Triple::x86_64) {
505 compiler.getTargetOpts().FeaturesAsWritten.push_back("+sse");
506 compiler.getTargetOpts().FeaturesAsWritten.push_back("+sse2");
507 }
508
509 // Set the target CPU to generate code for. This will be empty for any CPU
510 // that doesn't really need to make a special
511 // CPU string.
512 compiler.getTargetOpts().CPU = target_arch.GetClangTargetCPU();
513
514 // Set the target ABI
515 if (std::string abi = GetClangTargetABI(target_arch); !abi.empty())
516 compiler.getTargetOpts().ABI = std::move(abi);
517
518 if ((target_machine == llvm::Triple::riscv64 &&
519 compiler.getTargetOpts().ABI == "lp64f") ||
520 (target_machine == llvm::Triple::riscv32 &&
521 compiler.getTargetOpts().ABI == "ilp32f"))
522 compiler.getTargetOpts().FeaturesAsWritten.emplace_back("+f");
523
524 if ((target_machine == llvm::Triple::riscv64 &&
525 compiler.getTargetOpts().ABI == "lp64d") ||
526 (target_machine == llvm::Triple::riscv32 &&
527 compiler.getTargetOpts().ABI == "ilp32d"))
528 compiler.getTargetOpts().FeaturesAsWritten.emplace_back("+d");
529
530 if ((target_machine == llvm::Triple::loongarch64 &&
531 compiler.getTargetOpts().ABI == "lp64f"))
532 compiler.getTargetOpts().FeaturesAsWritten.emplace_back("+f");
533
534 if ((target_machine == llvm::Triple::loongarch64 &&
535 compiler.getTargetOpts().ABI == "lp64d"))
536 compiler.getTargetOpts().FeaturesAsWritten.emplace_back("+d");
537}
538
539static void SetupLangOpts(CompilerInstance &compiler,
540 ExecutionContextScope &exe_scope,
541 const Expression &expr,
542 DiagnosticManager &diagnostic_manager) {
544
545 // If the expression is being evaluated in the context of an existing stack
546 // frame, we introspect to see if the language runtime is available.
547
548 lldb::StackFrameSP frame_sp = exe_scope.CalculateStackFrame();
549 lldb::ProcessSP process_sp = exe_scope.CalculateProcess();
550
551 lldb::LanguageType language = expr.Language().AsLanguageType();
552
553 if (process_sp)
554 LLDB_LOG(
555 log,
556 "Frame has language of type {0}\nPicked {1} for expression evaluation.",
558 frame_sp ? frame_sp->GetLanguage().AsLanguageType()
561
562 lldb::LanguageType language_for_note = language;
563 std::string language_fallback_reason;
564
565 LangOptions &lang_opts = compiler.getLangOpts();
566
567 switch (language) {
572 // FIXME: the following language option is a temporary workaround,
573 // to "ask for C, get C++."
574 // For now, the expression parser must use C++ anytime the language is a C
575 // family language, because the expression parser uses features of C++ to
576 // capture values.
577 lang_opts.CPlusPlus = true;
578
579 language_for_note = lldb::eLanguageTypeC_plus_plus;
580 language_fallback_reason =
581 "Expression evaluation in pure C not supported. ";
582 break;
584 lang_opts.ObjC = true;
585 // FIXME: the following language option is a temporary workaround,
586 // to "ask for ObjC, get ObjC++" (see comment above).
587 lang_opts.CPlusPlus = true;
588
589 language_for_note = lldb::eLanguageTypeObjC_plus_plus;
590 language_fallback_reason =
591 "Expression evaluation in pure Objective-C not supported. ";
592
593 // Clang now sets as default C++14 as the default standard (with
594 // GNU extensions), so we do the same here to avoid mismatches that
595 // cause compiler error when evaluating expressions (e.g. nullptr not found
596 // as it's a C++11 feature). Currently lldb evaluates C++14 as C++11 (see
597 // two lines below) so we decide to be consistent with that, but this could
598 // be re-evaluated in the future.
599 lang_opts.CPlusPlus11 = true;
600 break;
602 lang_opts.CPlusPlus20 = true;
603 [[fallthrough]];
605 // FIXME: add a separate case for CPlusPlus14. Currently folded into C++17
606 // because C++14 is the default standard for Clang but enabling CPlusPlus14
607 // expression evaluatino doesn't pass the test-suite cleanly.
608 lang_opts.CPlusPlus14 = true;
609 lang_opts.CPlusPlus17 = true;
610 [[fallthrough]];
614 lang_opts.CPlusPlus11 = true;
615 compiler.getHeaderSearchOpts().UseLibcxx = true;
616 [[fallthrough]];
618 lang_opts.CPlusPlus = true;
619 if (process_sp
620 // We're stopped in a frame without debug-info. The user probably
621 // intends to make global queries (which should include Objective-C).
622 && !(frame_sp && frame_sp->HasDebugInformation())) {
623 lang_opts.ObjC =
624 process_sp->GetLanguageRuntime(lldb::eLanguageTypeObjC) != nullptr;
625 if (lang_opts.ObjC) {
626 language_for_note = lldb::eLanguageTypeObjC_plus_plus;
627 language_fallback_reason = "Possibly stopped inside system library, so "
628 "speculatively enabled Objective-C. ";
629 }
630 }
631 } break;
634 default:
635 lang_opts.ObjC = true;
636 lang_opts.CPlusPlus = true;
637 lang_opts.CPlusPlus11 = true;
638 compiler.getHeaderSearchOpts().UseLibcxx = true;
639
640 language_for_note = lldb::eLanguageTypeObjC_plus_plus;
641 if (language != language_for_note) {
642 if (language != lldb::eLanguageTypeUnknown)
643 language_fallback_reason = llvm::formatv(
644 "Expression evaluation in {0} not supported. ",
646
647 language_fallback_reason +=
648 llvm::formatv("Falling back to default language. ");
649 }
650 break;
651 }
652
653 // The cases above enable Objective-C speculatively; undo that for targets
654 // whose object file format can't support it.
656 ArchSpec(compiler.getTargetOpts().Triple)))
657 lang_opts.ObjC = false;
658
659 diagnostic_manager.AddDiagnostic(
660 llvm::formatv("{0}Ran expression as '{1}'.", language_fallback_reason,
662 language_for_note))
663 .str(),
665
666 lang_opts.Bool = true;
667 lang_opts.WChar = true;
668 lang_opts.Blocks = true;
669 lang_opts.DebuggerSupport =
670 true; // Features specifically for debugger clients
672 lang_opts.DebuggerCastResultToId = true;
673
674 lang_opts.CharIsSigned =
675 ArchSpec(compiler.getTargetOpts().Triple.c_str()).CharIsSignedByDefault();
676
677 // Spell checking is a nice feature, but it ends up completing a lot of types
678 // that we didn't strictly speaking need to complete. As a result, we spend a
679 // long time parsing and importing debug information.
680 lang_opts.SpellChecking = false;
681
682 if (process_sp && lang_opts.ObjC) {
683 if (auto *runtime = ObjCLanguageRuntime::Get(*process_sp)) {
684 switch (runtime->GetRuntimeVersion()) {
686 lang_opts.ObjCRuntime.set(ObjCRuntime::MacOSX, VersionTuple(10, 7));
687 break;
690 lang_opts.ObjCRuntime.set(ObjCRuntime::FragileMacOSX,
691 VersionTuple(10, 7));
692 break;
694 lang_opts.ObjCRuntime.set(ObjCRuntime::GNUstep, VersionTuple(2, 0));
695 break;
696 }
697
698 if (runtime->HasNewLiteralsAndIndexing())
699 lang_opts.DebuggerObjCLiteral = true;
700 }
701 }
702
703 lang_opts.ThreadsafeStatics = false;
704 lang_opts.AccessControl = false; // Debuggers get universal access
705 lang_opts.DollarIdents = true; // $ indicates a persistent variable name
706 // We enable all builtin functions beside the builtins from libc/libm (e.g.
707 // 'fopen'). Those libc functions are already correctly handled by LLDB, and
708 // additionally enabling them as expandable builtins is breaking Clang.
709 lang_opts.NoBuiltin = true;
710}
711
712static void SetupImportStdModuleLangOpts(CompilerInstance &compiler,
713 lldb_private::Target &target) {
714 LangOptions &lang_opts = compiler.getLangOpts();
715 lang_opts.Modules = true;
716 // We want to implicitly build modules.
717 lang_opts.ImplicitModules = true;
718 // To automatically import all submodules when we import 'std'.
719 lang_opts.ModulesLocalVisibility = false;
720
721 // We use the @import statements, so we need this:
722 // FIXME: We could use the modules-ts, but that currently doesn't work.
723 lang_opts.ObjC = true;
724
725 // Options we need to parse libc++ code successfully.
726 // FIXME: We should ask the driver for the appropriate default flags.
727 lang_opts.GNUMode = true;
728 lang_opts.GNUKeywords = true;
729 lang_opts.CPlusPlus11 = true;
730
731 lang_opts.BuiltinHeadersInSystemModules = false;
732
733 // The Darwin libc expects this macro to be set.
734 lang_opts.GNUCVersion = 40201;
735}
736
737//===----------------------------------------------------------------------===//
738// Implementation of ClangExpressionParser
739//===----------------------------------------------------------------------===//
740
741static void SetPointerAuthOptionsForArm64e(LangOptions &lang_opts) {
742 lang_opts.PointerAuthIntrinsics = true;
743 lang_opts.PointerAuthCalls = true;
744 lang_opts.PointerAuthReturns = true;
745 lang_opts.PointerAuthAuthTraps = true;
746 lang_opts.PointerAuthIndirectGotos = true;
747 lang_opts.PointerAuthVTPtrAddressDiscrimination = true;
748 lang_opts.PointerAuthVTPtrTypeDiscrimination = true;
749 lang_opts.PointerAuthObjcIsa = true;
750 lang_opts.PointerAuthObjcClassROPointers = true;
751 lang_opts.PointerAuthObjcInterfaceSel = true;
752}
753
755 ExecutionContextScope *exe_scope, Expression &expr,
756 bool generate_debug_info, DiagnosticManager &diagnostic_manager,
757 std::vector<std::string> include_directories, std::string filename,
758 bool force_disable_ptrauth_codegen)
759 : ExpressionParser(exe_scope, expr, generate_debug_info), m_compiler(),
760 m_pp_callbacks(nullptr),
761 m_include_directories(std::move(include_directories)),
762 m_filename(std::move(filename)) {
764
765 // We can't compile expressions without a target. So if the exe_scope is
766 // null or doesn't have a target, then we just need to get out of here. I'll
767 // lldbassert and not make any of the compiler objects since
768 // I can't return errors directly from the constructor. Further calls will
769 // check if the compiler was made and
770 // bag out if it wasn't.
771
772 if (!exe_scope) {
773 lldbassert(exe_scope &&
774 "Can't make an expression parser with a null scope.");
775 return;
776 }
777
778 lldb::TargetSP target_sp;
779 target_sp = exe_scope->CalculateTarget();
780 if (!target_sp) {
781 lldbassert(target_sp.get() &&
782 "Can't make an expression parser with a null target.");
783 return;
784 }
785
786 // 1. Create a new compiler instance.
787 m_compiler = std::make_unique<CompilerInstance>();
788
789 // Make sure clang uses the same VFS as LLDB.
790 m_compiler->setVirtualFileSystem(
791 FileSystem::Instance().GetVirtualFileSystem());
792
793 // 2. Configure the compiler with a set of default options that are
794 // appropriate for most situations.
795 SetupTargetOpts(*m_compiler, *target_sp);
796
797 // 3. Create and install the target on the compiler.
798 m_compiler->createDiagnostics();
799 // Limit the number of error diagnostics we emit.
800 // A value of 0 means no limit for both LLDB and Clang.
801 m_compiler->getDiagnostics().setErrorLimit(target_sp->GetExprErrorLimit());
802
803 if (auto *target_info = TargetInfo::CreateTargetInfo(
804 m_compiler->getDiagnostics(),
805 m_compiler->getInvocation().getTargetOpts())) {
806 LLDB_LOGF(log, "Target datalayout string: '%s'",
807 target_info->getDataLayoutString());
808 LLDB_LOGF(log, "Target ABI: '%s'", target_info->getABI().str().c_str());
809 LLDB_LOGF(log, "Target vector alignment: %d",
810 target_info->getMaxVectorAlign());
811 m_compiler->setTarget(target_info);
812 } else {
813 LLDB_LOGF(log, "Failed to create TargetInfo for '%s'",
814 m_compiler->getTargetOpts().Triple.c_str());
815
816 lldbassert(false && "Failed to create TargetInfo.");
817 }
818
819 // 4. Set language options.
820 SetupLangOpts(*m_compiler, *exe_scope, expr, diagnostic_manager);
821
822 const llvm::Triple triple = target_sp->GetArchitecture().GetTriple();
823 const bool enable_ptrauth =
824 triple.isArm64e() && !force_disable_ptrauth_codegen;
825 if (enable_ptrauth)
827
828 auto *clang_expr = dyn_cast<ClangUserExpression>(&m_expr);
829 if (clang_expr && clang_expr->DidImportCxxModules()) {
830 LLDB_LOG(log, "Adding lang options for importing C++ modules");
833 }
834
835 // Set CodeGen options
836 m_compiler->getCodeGenOpts().EmitDeclMetadata = true;
837 m_compiler->getCodeGenOpts().InstrumentFunctions = false;
838 m_compiler->getCodeGenOpts().setFramePointer(
839 CodeGenOptions::FramePointerKind::All);
840 if (generate_debug_info)
841 m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::FullDebugInfo);
842 else
843 m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::NoDebugInfo);
844
845 if (enable_ptrauth) {
846 PointerAuthOptions &ptrauth_opts = m_compiler->getCodeGenOpts().PointerAuth;
847 clang::CompilerInvocation::setDefaultPointerAuthOptions(
848 ptrauth_opts, m_compiler->getLangOpts(), triple);
849 }
850
851 // Disable some warnings.
853
854 // Inform the target of the language options
855 //
856 // FIXME: We shouldn't need to do this, the target should be immutable once
857 // created. This complexity should be lifted elsewhere.
858 m_compiler->getTarget().adjust(m_compiler->getDiagnostics(),
859 m_compiler->getLangOpts(),
860 /*AuxTarget=*/nullptr);
861
862 // 5. Set up the diagnostic buffer for reporting errors
863 auto diag_mgr = new ClangDiagnosticManagerAdapter(
864 m_compiler->getDiagnostics().getDiagnosticOptions(),
865 clang_expr ? clang_expr->GetFilename() : StringRef());
866 m_compiler->getDiagnostics().setClient(diag_mgr);
867
868 // 6. Set up the source management objects inside the compiler
869 m_compiler->createFileManager();
870 if (!m_compiler->hasSourceManager())
871 m_compiler->createSourceManager();
872 m_compiler->createPreprocessor(TU_Complete);
873
874 switch (expr.Language().AsLanguageType()) {
880 // This is not a C++ expression but we enabled C++ as explained above.
881 // Remove all C++ keywords from the PP so that the user can still use
882 // variables that have C++ keywords as names (e.g. 'int template;').
883 RemoveAllCppKeywords(m_compiler->getPreprocessor().getIdentifierTable());
884 break;
885 default:
886 break;
887 }
888
889 if (auto *clang_persistent_vars = llvm::cast<ClangPersistentVariables>(
890 target_sp->GetPersistentExpressionStateForLanguage(
892 if (std::shared_ptr<ClangModulesDeclVendor> decl_vendor =
893 clang_persistent_vars->GetClangModulesDeclVendor()) {
894 std::unique_ptr<PPCallbacks> pp_callbacks(
895 new LLDBPreprocessorCallbacks(*decl_vendor, *clang_persistent_vars,
896 m_compiler->getSourceManager()));
898 static_cast<LLDBPreprocessorCallbacks *>(pp_callbacks.get());
899 m_compiler->getPreprocessor().addPPCallbacks(std::move(pp_callbacks));
900 }
901 }
902
903 // 7. Most of this we get from the CompilerInstance, but we also want to give
904 // the context an ExternalASTSource.
905
906 auto &PP = m_compiler->getPreprocessor();
907 auto &builtin_context = PP.getBuiltinInfo();
908 builtin_context.initializeBuiltins(PP.getIdentifierTable(),
909 m_compiler->getLangOpts());
910
911 m_compiler->createASTContext();
912 clang::ASTContext &ast_context = m_compiler->getASTContext();
913
914 m_ast_context = std::make_shared<TypeSystemClang>(
915 "Expression ASTContext for '" + m_filename + "'", ast_context);
916
917 std::string module_name("$__lldb_module");
918
919 m_llvm_context = std::make_unique<LLVMContext>();
921 CreateLLVMCodeGen(*m_compiler, module_name, *m_llvm_context);
922}
923
925
926namespace {
927
928/// \class CodeComplete
929///
930/// A code completion consumer for the clang Sema that is responsible for
931/// creating the completion suggestions when a user requests completion
932/// of an incomplete `expr` invocation.
933class CodeComplete : public CodeCompleteConsumer {
934 CodeCompletionTUInfo m_info;
935
936 std::string m_expr;
937 unsigned m_position = 0;
938 /// The printing policy we use when printing declarations for our completion
939 /// descriptions.
940 clang::PrintingPolicy m_desc_policy;
941
942 struct CompletionWithPriority {
944 /// See CodeCompletionResult::Priority;
945 unsigned Priority;
946
947 /// Establishes a deterministic order in a list of CompletionWithPriority.
948 /// The order returned here is the order in which the completions are
949 /// displayed to the user.
950 bool operator<(const CompletionWithPriority &o) const {
951 // High priority results should come first.
952 if (Priority != o.Priority)
953 return Priority > o.Priority;
954
955 // Identical priority, so just make sure it's a deterministic order.
956 return completion.GetUniqueKey() < o.completion.GetUniqueKey();
957 }
958 };
959
960 /// The stored completions.
961 /// Warning: These are in a non-deterministic order until they are sorted
962 /// and returned back to the caller.
963 std::vector<CompletionWithPriority> m_completions;
964
965 /// Returns true if the given character can be used in an identifier.
966 /// This also returns true for numbers because for completion we usually
967 /// just iterate backwards over iterators.
968 ///
969 /// Note: lldb uses '$' in its internal identifiers, so we also allow this.
970 static bool IsIdChar(char c) {
971 return c == '_' || std::isalnum(c) || c == '$';
972 }
973
974 /// Returns true if the given character is used to separate arguments
975 /// in the command line of lldb.
976 static bool IsTokenSeparator(char c) { return c == ' ' || c == '\t'; }
977
978 /// Drops all tokens in front of the expression that are unrelated for
979 /// the completion of the cmd line. 'unrelated' means here that the token
980 /// is not interested for the lldb completion API result.
981 StringRef dropUnrelatedFrontTokens(StringRef cmd) const {
982 if (cmd.empty())
983 return cmd;
984
985 // If we are at the start of a word, then all tokens are unrelated to
986 // the current completion logic.
987 if (IsTokenSeparator(cmd.back()))
988 return StringRef();
989
990 // Remove all previous tokens from the string as they are unrelated
991 // to completing the current token.
992 StringRef to_remove = cmd;
993 while (!to_remove.empty() && !IsTokenSeparator(to_remove.back())) {
994 to_remove = to_remove.drop_back();
995 }
996 cmd = cmd.drop_front(to_remove.size());
997
998 return cmd;
999 }
1000
1001 /// Removes the last identifier token from the given cmd line.
1002 StringRef removeLastToken(StringRef cmd) const {
1003 while (!cmd.empty() && IsIdChar(cmd.back())) {
1004 cmd = cmd.drop_back();
1005 }
1006 return cmd;
1007 }
1008
1009 /// Attempts to merge the given completion from the given position into the
1010 /// existing command. Returns the completion string that can be returned to
1011 /// the lldb completion API.
1012 std::string mergeCompletion(StringRef existing, unsigned pos,
1013 StringRef completion) const {
1014 StringRef existing_command = existing.substr(0, pos);
1015 // We rewrite the last token with the completion, so let's drop that
1016 // token from the command.
1017 existing_command = removeLastToken(existing_command);
1018 // We also should remove all previous tokens from the command as they
1019 // would otherwise be added to the completion that already has the
1020 // completion.
1021 existing_command = dropUnrelatedFrontTokens(existing_command);
1022 return existing_command.str() + completion.str();
1023 }
1024
1025public:
1026 /// Constructs a CodeComplete consumer that can be attached to a Sema.
1027 ///
1028 /// \param[out] expr
1029 /// The whole expression string that we are currently parsing. This
1030 /// string needs to be equal to the input the user typed, and NOT the
1031 /// final code that Clang is parsing.
1032 /// \param[out] position
1033 /// The character position of the user cursor in the `expr` parameter.
1034 ///
1035 CodeComplete(clang::LangOptions ops, std::string expr, unsigned position)
1036 : CodeCompleteConsumer(CodeCompleteOptions()),
1037 m_info(std::make_shared<GlobalCodeCompletionAllocator>()), m_expr(expr),
1038 m_position(position), m_desc_policy(ops) {
1039
1040 // Ensure that the printing policy is producing a description that is as
1041 // short as possible.
1042 m_desc_policy.SuppressScope = true;
1043 m_desc_policy.SuppressTagKeyword = true;
1044 m_desc_policy.FullyQualifiedName = false;
1045 m_desc_policy.TerseOutput = true;
1046 m_desc_policy.IncludeNewlines = false;
1047 m_desc_policy.UseVoidForZeroParams = false;
1048 m_desc_policy.Bool = true;
1049 }
1050
1051 /// \name Code-completion filtering
1052 /// Check if the result should be filtered out.
1053 bool isResultFilteredOut(StringRef Filter,
1054 CodeCompletionResult Result) override {
1055 // This code is mostly copied from CodeCompleteConsumer.
1056 switch (Result.Kind) {
1057 case CodeCompletionResult::RK_Declaration:
1058 return !(
1059 Result.Declaration->getIdentifier() &&
1060 Result.Declaration->getIdentifier()->getName().starts_with(Filter));
1061 case CodeCompletionResult::RK_Keyword:
1062 return !StringRef(Result.Keyword).starts_with(Filter);
1063 case CodeCompletionResult::RK_Macro:
1064 return !Result.Macro->getName().starts_with(Filter);
1065 case CodeCompletionResult::RK_Pattern:
1066 return !StringRef(Result.Pattern->getAsString()).starts_with(Filter);
1067 }
1068 // If we trigger this assert or the above switch yields a warning, then
1069 // CodeCompletionResult has been enhanced with more kinds of completion
1070 // results. Expand the switch above in this case.
1071 assert(false && "Unknown completion result type?");
1072 // If we reach this, then we should just ignore whatever kind of unknown
1073 // result we got back. We probably can't turn it into any kind of useful
1074 // completion suggestion with the existing code.
1075 return true;
1076 }
1077
1078private:
1079 /// Generate the completion strings for the given CodeCompletionResult.
1080 /// Note that this function has to process results that could come in
1081 /// non-deterministic order, so this function should have no side effects.
1082 /// To make this easier to enforce, this function and all its parameters
1083 /// should always be const-qualified.
1084 /// \return Returns std::nullopt if no completion should be provided for the
1085 /// given CodeCompletionResult.
1086 std::optional<CompletionWithPriority>
1087 getCompletionForResult(const CodeCompletionResult &R) const {
1088 std::string ToInsert;
1089 std::string Description;
1090 // Handle the different completion kinds that come from the Sema.
1091 switch (R.Kind) {
1092 case CodeCompletionResult::RK_Declaration: {
1093 const NamedDecl *D = R.Declaration;
1094 ToInsert = R.Declaration->getNameAsString();
1095 // If we have a function decl that has no arguments we want to
1096 // complete the empty parantheses for the user. If the function has
1097 // arguments, we at least complete the opening bracket.
1098 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(D)) {
1099 if (F->getNumParams() == 0)
1100 ToInsert += "()";
1101 else
1102 ToInsert += "(";
1103 raw_string_ostream OS(Description);
1104 F->print(OS, m_desc_policy, false);
1105 } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
1106 Description = V->getType().getAsString(m_desc_policy);
1107 } else if (const FieldDecl *F = dyn_cast<FieldDecl>(D)) {
1108 Description = F->getType().getAsString(m_desc_policy);
1109 } else if (const NamespaceDecl *N = dyn_cast<NamespaceDecl>(D)) {
1110 // If we try to complete a namespace, then we can directly append
1111 // the '::'.
1112 if (!N->isAnonymousNamespace())
1113 ToInsert += "::";
1114 }
1115 break;
1116 }
1117 case CodeCompletionResult::RK_Keyword:
1118 ToInsert = R.Keyword;
1119 break;
1120 case CodeCompletionResult::RK_Macro:
1121 ToInsert = R.Macro->getName().str();
1122 break;
1123 case CodeCompletionResult::RK_Pattern:
1124 ToInsert = R.Pattern->getTypedText();
1125 break;
1126 }
1127 // We also filter some internal lldb identifiers here. The user
1128 // shouldn't see these.
1129 if (llvm::StringRef(ToInsert).starts_with("$__lldb_"))
1130 return std::nullopt;
1131 if (ToInsert.empty())
1132 return std::nullopt;
1133 // Merge the suggested Token into the existing command line to comply
1134 // with the kind of result the lldb API expects.
1135 std::string CompletionSuggestion =
1136 mergeCompletion(m_expr, m_position, ToInsert);
1137
1138 CompletionResult::Completion completion(CompletionSuggestion, Description,
1139 CompletionMode::Normal);
1140 return {{completion, R.Priority}};
1141 }
1142
1143public:
1144 /// Adds the completions to the given CompletionRequest.
1145 void GetCompletions(CompletionRequest &request) {
1146 // Bring m_completions into a deterministic order and pass it on to the
1147 // CompletionRequest.
1148 llvm::sort(m_completions);
1149
1150 for (const CompletionWithPriority &C : m_completions)
1151 request.AddCompletion(C.completion.GetCompletion(),
1152 C.completion.GetDescription(),
1153 C.completion.GetMode());
1154 }
1155
1156 /// \name Code-completion callbacks
1157 /// Process the finalized code-completion results.
1158 void ProcessCodeCompleteResults(Sema &SemaRef, CodeCompletionContext Context,
1159 CodeCompletionResult *Results,
1160 unsigned NumResults) override {
1161
1162 // The Sema put the incomplete token we try to complete in here during
1163 // lexing, so we need to retrieve it here to know what we are completing.
1164 StringRef Filter = SemaRef.getPreprocessor().getCodeCompletionFilter();
1165
1166 // Iterate over all the results. Filter out results we don't want and
1167 // process the rest.
1168 for (unsigned I = 0; I != NumResults; ++I) {
1169 // Filter the results with the information from the Sema.
1170 if (!Filter.empty() && isResultFilteredOut(Filter, Results[I]))
1171 continue;
1172
1173 CodeCompletionResult &R = Results[I];
1174 std::optional<CompletionWithPriority> CompletionAndPriority =
1175 getCompletionForResult(R);
1176 if (!CompletionAndPriority)
1177 continue;
1178 m_completions.push_back(*CompletionAndPriority);
1179 }
1180 }
1181
1182 /// \param S the semantic-analyzer object for which code-completion is being
1183 /// done.
1184 ///
1185 /// \param CurrentArg the index of the current argument.
1186 ///
1187 /// \param Candidates an array of overload candidates.
1188 ///
1189 /// \param NumCandidates the number of overload candidates
1190 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1191 OverloadCandidate *Candidates,
1192 unsigned NumCandidates,
1193 SourceLocation OpenParLoc,
1194 bool Braced) override {
1195 // At the moment we don't filter out any overloaded candidates.
1196 }
1197
1198 CodeCompletionAllocator &getAllocator() override {
1199 return m_info.getAllocator();
1200 }
1201
1202 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return m_info; }
1203};
1204} // namespace
1205
1207 unsigned pos, unsigned typed_pos) {
1209 // We need the raw user expression here because that's what the CodeComplete
1210 // class uses to provide completion suggestions.
1211 // However, the `Text` method only gives us the transformed expression here.
1212 // To actually get the raw user input here, we have to cast our expression to
1213 // the LLVMUserExpression which exposes the right API. This should never fail
1214 // as we always have a ClangUserExpression whenever we call this.
1215 ClangUserExpression *llvm_expr = cast<ClangUserExpression>(&m_expr);
1216 CodeComplete CC(m_compiler->getLangOpts(), llvm_expr->GetUserText(),
1217 typed_pos);
1218 // We don't need a code generator for parsing.
1219 m_code_generator.reset();
1220 // Start parsing the expression with our custom code completion consumer.
1221 ParseInternal(mgr, &CC, line, pos);
1222 CC.GetCompletions(request);
1223 return true;
1224}
1225
1227 return ParseInternal(diagnostic_manager);
1228}
1229
1230unsigned
1232 CodeCompleteConsumer *completion_consumer,
1233 unsigned completion_line,
1234 unsigned completion_column) {
1236 static_cast<ClangDiagnosticManagerAdapter *>(
1237 m_compiler->getDiagnostics().getClient());
1238
1239 adapter->ResetManager(&diagnostic_manager);
1240
1241 const char *expr_text = m_expr.Text();
1242
1243 clang::SourceManager &source_mgr = m_compiler->getSourceManager();
1244 bool created_main_file = false;
1245
1246 // Clang wants to do completion on a real file known by Clang's file manager,
1247 // so we have to create one to make this work.
1248 // TODO: We probably could also simulate to Clang's file manager that there
1249 // is a real file that contains our code.
1250 bool should_create_file = completion_consumer != nullptr;
1251
1252 // We also want a real file on disk if we generate full debug info.
1253 should_create_file |= m_compiler->getCodeGenOpts().getDebugInfo() ==
1254 codegenoptions::FullDebugInfo;
1255
1256 if (should_create_file) {
1257 int temp_fd = -1;
1258 llvm::SmallString<128> result_path;
1259 if (FileSpec tmpdir_file_spec = HostInfo::GetProcessTempDir()) {
1260 tmpdir_file_spec.AppendPathComponent("lldb-%%%%%%.expr");
1261 std::string temp_source_path = tmpdir_file_spec.GetPath();
1262 llvm::sys::fs::createUniqueFile(temp_source_path, temp_fd, result_path);
1263 } else {
1264 llvm::sys::fs::createTemporaryFile("lldb", "expr", temp_fd, result_path);
1265 }
1266
1267 if (temp_fd != -1) {
1269 const size_t expr_text_len = strlen(expr_text);
1270 size_t bytes_written = expr_text_len;
1271 if (file.Write(expr_text, bytes_written).Success()) {
1272 if (bytes_written == expr_text_len) {
1273 file.Close();
1274 if (auto fileEntry = m_compiler->getFileManager().getOptionalFileRef(
1275 result_path)) {
1276 source_mgr.setMainFileID(source_mgr.createFileID(
1277 *fileEntry, SourceLocation(), SrcMgr::C_User));
1278 created_main_file = true;
1279 }
1280 }
1281 }
1282 }
1283 }
1284
1285 if (!created_main_file) {
1286 std::unique_ptr<MemoryBuffer> memory_buffer =
1287 MemoryBuffer::getMemBufferCopy(expr_text, m_filename);
1288 source_mgr.setMainFileID(source_mgr.createFileID(std::move(memory_buffer)));
1289 }
1290
1291 adapter->BeginSourceFile(m_compiler->getLangOpts(),
1292 &m_compiler->getPreprocessor());
1293
1294 ClangExpressionHelper *type_system_helper =
1295 dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
1296
1297 // If we want to parse for code completion, we need to attach our code
1298 // completion consumer to the Sema and specify a completion position.
1299 // While parsing the Sema will call this consumer with the provided
1300 // completion suggestions.
1301 if (completion_consumer) {
1302 auto main_file =
1303 source_mgr.getFileEntryRefForID(source_mgr.getMainFileID());
1304 auto &PP = m_compiler->getPreprocessor();
1305 // Lines and columns start at 1 in Clang, but code completion positions are
1306 // indexed from 0, so we need to add 1 to the line and column here.
1307 ++completion_line;
1308 ++completion_column;
1309 PP.SetCodeCompletionPoint(*main_file, completion_line, completion_column);
1310 }
1311
1312 ASTConsumer *ast_transformer =
1313 type_system_helper->ASTTransformer(m_code_generator.get());
1314
1315 std::unique_ptr<clang::ASTConsumer> Consumer;
1316 if (ast_transformer) {
1317 Consumer = std::make_unique<ASTConsumerForwarder>(ast_transformer);
1318 } else if (m_code_generator) {
1319 Consumer = std::make_unique<ASTConsumerForwarder>(m_code_generator.get());
1320 } else {
1321 Consumer = std::make_unique<ASTConsumer>();
1322 }
1323
1324 clang::ASTContext &ast_context = m_compiler->getASTContext();
1325
1326 m_compiler->setSema(new Sema(m_compiler->getPreprocessor(), ast_context,
1327 *Consumer, TU_Complete, completion_consumer));
1328 m_compiler->setASTConsumer(std::move(Consumer));
1329
1330 if (ast_context.getLangOpts().Modules) {
1331 m_compiler->createASTReader();
1332 m_ast_context->setSema(&m_compiler->getSema());
1333 }
1334
1335 ClangExpressionDeclMap *decl_map = type_system_helper->DeclMap();
1336 if (decl_map) {
1337 decl_map->InstallCodeGenerator(&m_compiler->getASTConsumer());
1338 decl_map->InstallDiagnosticManager(diagnostic_manager);
1339
1340 llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> ast_source =
1341 decl_map->CreateProxy();
1342
1343 auto ast_source_wrapper =
1344 llvm::makeIntrusiveRefCnt<ExternalASTSourceWrapper>(ast_source);
1345
1346 if (ast_context.getExternalSource()) {
1347 auto module_wrapper = llvm::makeIntrusiveRefCnt<ExternalASTSourceWrapper>(
1348 ast_context.getExternalSourcePtr());
1349
1350 auto multiplexer = llvm::makeIntrusiveRefCnt<SemaSourceWithPriorities>(
1351 module_wrapper, ast_source_wrapper);
1352
1353 ast_context.setExternalSource(multiplexer);
1354 } else {
1355 ast_context.setExternalSource(ast_source);
1356 }
1357 m_compiler->getSema().addExternalSource(ast_source_wrapper);
1358 decl_map->InstallASTContext(*m_ast_context);
1359 }
1360
1361 // Check that the ASTReader is properly attached to ASTContext and Sema.
1362 if (ast_context.getLangOpts().Modules) {
1363 assert(m_compiler->getASTContext().getExternalSource() &&
1364 "ASTContext doesn't know about the ASTReader?");
1365 assert(m_compiler->getSema().getExternalSource() &&
1366 "Sema doesn't know about the ASTReader?");
1367 }
1368
1369 {
1370 llvm::CrashRecoveryContextCleanupRegistrar<Sema> CleanupSema(
1371 &m_compiler->getSema());
1372 ParseAST(m_compiler->getSema(), false, false);
1373 }
1374
1375 // Make sure we have no pointer to the Sema we are about to destroy.
1376 if (ast_context.getLangOpts().Modules)
1377 m_ast_context->setSema(nullptr);
1378 // Destroy the Sema. This is necessary because we want to emulate the
1379 // original behavior of ParseAST (which also destroys the Sema after parsing).
1380 m_compiler->setSema(nullptr);
1381
1382 adapter->EndSourceFile();
1383 // Creating persistent variables can trigger diagnostic emission.
1384 // Make sure we reset the manager so we don't get asked to handle
1385 // diagnostics after we finished parsing.
1386 adapter->ResetManager();
1387
1388 unsigned num_errors = adapter->getNumErrors();
1389
1390 if (m_pp_callbacks && m_pp_callbacks->hasErrors()) {
1391 num_errors++;
1392 diagnostic_manager.PutString(lldb::eSeverityError,
1393 "while importing modules:");
1394 diagnostic_manager.AppendMessageToDiagnostic(
1395 m_pp_callbacks->getErrorString());
1396 }
1397
1398 if (!num_errors) {
1399 type_system_helper->CommitPersistentDecls();
1400 }
1401
1402 return num_errors;
1403}
1404
1405/// Applies the given Fix-It hint to the given commit.
1406static void ApplyFixIt(const FixItHint &fixit, clang::edit::Commit &commit) {
1407 // This is cobbed from clang::Rewrite::FixItRewriter.
1408 if (fixit.CodeToInsert.empty()) {
1409 if (fixit.InsertFromRange.isValid()) {
1410 commit.insertFromRange(fixit.RemoveRange.getBegin(),
1411 fixit.InsertFromRange, /*afterToken=*/false,
1412 fixit.BeforePreviousInsertions);
1413 return;
1414 }
1415 commit.remove(fixit.RemoveRange);
1416 return;
1417 }
1418 if (fixit.RemoveRange.isTokenRange() ||
1419 fixit.RemoveRange.getBegin() != fixit.RemoveRange.getEnd()) {
1420 commit.replace(fixit.RemoveRange, fixit.CodeToInsert);
1421 return;
1422 }
1423 commit.insert(fixit.RemoveRange.getBegin(), fixit.CodeToInsert,
1424 /*afterToken=*/false, fixit.BeforePreviousInsertions);
1425}
1426
1428 DiagnosticManager &diagnostic_manager) {
1429 clang::SourceManager &source_manager = m_compiler->getSourceManager();
1430 clang::edit::EditedSource editor(source_manager, m_compiler->getLangOpts(),
1431 nullptr);
1432 clang::edit::Commit commit(editor);
1433 clang::Rewriter rewriter(source_manager, m_compiler->getLangOpts());
1434
1435 class RewritesReceiver : public edit::EditsReceiver {
1436 Rewriter &rewrite;
1437
1438 public:
1439 RewritesReceiver(Rewriter &in_rewrite) : rewrite(in_rewrite) {}
1440
1441 void insert(SourceLocation loc, StringRef text) override {
1442 rewrite.InsertText(loc, text);
1443 }
1444 void replace(CharSourceRange range, StringRef text) override {
1445 rewrite.ReplaceText(range.getBegin(), rewrite.getRangeSize(range), text);
1446 }
1447 };
1448
1449 RewritesReceiver rewrites_receiver(rewriter);
1450
1451 const DiagnosticList &diagnostics = diagnostic_manager.Diagnostics();
1452 size_t num_diags = diagnostics.size();
1453 if (num_diags == 0)
1454 return false;
1455
1456 for (const auto &diag : diagnostic_manager.Diagnostics()) {
1457 const auto *diagnostic = llvm::dyn_cast<ClangDiagnostic>(diag.get());
1458 if (!diagnostic)
1459 continue;
1460 if (!diagnostic->HasFixIts())
1461 continue;
1462 for (const FixItHint &fixit : diagnostic->FixIts())
1463 ApplyFixIt(fixit, commit);
1464 }
1465
1466 // FIXME - do we want to try to propagate specific errors here?
1467 if (!commit.isCommitable())
1468 return false;
1469 else if (!editor.commit(commit))
1470 return false;
1471
1472 // Now play all the edits, and stash the result in the diagnostic manager.
1473 editor.applyRewrites(rewrites_receiver);
1474 RewriteBuffer &main_file_buffer =
1475 rewriter.getEditBuffer(source_manager.getMainFileID());
1476
1477 std::string fixed_expression;
1478 llvm::raw_string_ostream out_stream(fixed_expression);
1479
1480 main_file_buffer.write(out_stream);
1481 diagnostic_manager.SetFixedExpression(fixed_expression);
1482
1483 return true;
1484}
1485
1486static bool FindFunctionInModule(ConstString &mangled_name,
1487 llvm::Module *module, const char *orig_name) {
1488 for (const auto &func : module->getFunctionList()) {
1489 const StringRef &name = func.getName();
1490 if (name.contains(orig_name)) {
1491 mangled_name.SetString(name);
1492 return true;
1493 }
1494 }
1495
1496 return false;
1497}
1498
1500 lldb::addr_t &func_addr, lldb::addr_t &func_end,
1501 lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx,
1502 bool &can_interpret, ExecutionPolicy execution_policy) {
1503 func_addr = LLDB_INVALID_ADDRESS;
1504 func_end = LLDB_INVALID_ADDRESS;
1506
1508
1509 std::unique_ptr<llvm::Module> llvm_module_up(
1510 m_code_generator->ReleaseModule());
1511
1512 if (!llvm_module_up) {
1513 err = Status::FromErrorString("IR doesn't contain a module");
1514 return err;
1515 }
1516
1517 ConstString function_name;
1518
1519 if (execution_policy != eExecutionPolicyTopLevel) {
1520 // Find the actual name of the function (it's often mangled somehow)
1521
1522 if (!FindFunctionInModule(function_name, llvm_module_up.get(),
1523 m_expr.FunctionName())) {
1525 "Couldn't find %s() in the module", m_expr.FunctionName());
1526 return err;
1527 } else {
1528 LLDB_LOG(log, "Found function {0} for {1}", function_name,
1529 m_expr.FunctionName());
1530 }
1531 }
1532
1533 SymbolContext sc;
1534
1535 if (lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP()) {
1536 sc = frame_sp->GetSymbolContext(lldb::eSymbolContextEverything);
1537 } else if (lldb::TargetSP target_sp = exe_ctx.GetTargetSP()) {
1538 sc.target_sp = target_sp;
1539 }
1540
1541 LLVMUserExpression::IRPasses custom_passes;
1542 {
1543 auto lang = m_expr.Language();
1544 LLDB_LOGF(log, "%s - Current expression language is %s\n", __FUNCTION__,
1545 lang.GetDescription().data());
1546 lldb::ProcessSP process_sp = exe_ctx.GetProcessSP();
1547 if (process_sp && lang) {
1548 auto runtime = process_sp->GetLanguageRuntime(lang.AsLanguageType());
1549 if (runtime)
1550 runtime->GetIRPasses(custom_passes);
1551 }
1552 }
1553
1554 if (custom_passes.EarlyPasses) {
1555 LLDB_LOGF(log,
1556 "%s - Running Early IR Passes from LanguageRuntime on "
1557 "expression module '%s'",
1558 __FUNCTION__, m_expr.FunctionName());
1559
1560 custom_passes.EarlyPasses->run(*llvm_module_up);
1561 }
1562
1563 execution_unit_sp = std::make_shared<IRExecutionUnit>(
1564 m_llvm_context, // handed off here
1565 llvm_module_up, // handed off here
1566 function_name, exe_ctx.GetTargetSP(), sc,
1567 m_compiler->getTargetOpts().Features);
1568
1569 if (auto *options = m_expr.GetOptions())
1570 execution_unit_sp->AppendPreferredSymbolContexts(
1571 options->GetPreferredSymbolContexts());
1572
1573 ClangExpressionHelper *type_system_helper =
1574 dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
1575 ClangExpressionDeclMap *decl_map =
1576 type_system_helper->DeclMap(); // result can be NULL
1577
1578 if (decl_map) {
1579 StreamString error_stream;
1580 IRForTarget ir_for_target(
1581 decl_map, m_expr.NeedsVariableResolution(), *execution_unit_sp,
1582 error_stream, execution_policy, function_name.AsCString(nullptr));
1583
1584 if (!ir_for_target.runOnModule(*execution_unit_sp->GetModule())) {
1585 err = Status(error_stream.GetString().str());
1586 return err;
1587 }
1588
1589 Process *process = exe_ctx.GetProcessPtr();
1590
1591 if (execution_policy != eExecutionPolicyAlways &&
1592 execution_policy != eExecutionPolicyTopLevel) {
1593 lldb_private::Status interpret_error;
1594
1595 bool interpret_function_calls =
1596 !process ? false : process->CanInterpretFunctionCalls();
1597 can_interpret = IRInterpreter::CanInterpret(
1598 *execution_unit_sp->GetModule(), *execution_unit_sp->GetFunction(),
1599 interpret_error, interpret_function_calls);
1600
1601 if (!can_interpret && execution_policy == eExecutionPolicyNever) {
1603 "Can't evaluate the expression without a running target due to: %s",
1604 interpret_error.AsCString());
1605 return err;
1606 }
1607 }
1608
1609 if (!process && execution_policy == eExecutionPolicyAlways) {
1611 "Expression needed to run in the target, but the "
1612 "target can't be run");
1613 return err;
1614 }
1615
1616 if (!process && execution_policy == eExecutionPolicyTopLevel) {
1618 "Top-level code needs to be inserted into a runnable "
1619 "target, but the target can't be run");
1620 return err;
1621 }
1622
1623 if (execution_policy == eExecutionPolicyAlways ||
1624 (execution_policy != eExecutionPolicyTopLevel && !can_interpret)) {
1625 if (m_expr.NeedsValidation() && process) {
1626 if (!process->GetDynamicCheckers()) {
1627 ClangDynamicCheckerFunctions *dynamic_checkers =
1629
1630 DiagnosticManager install_diags;
1631 if (Error Err = dynamic_checkers->Install(install_diags, exe_ctx))
1632 return Status::FromError(install_diags.GetAsError(
1633 lldb::eExpressionSetupError, "couldn't install checkers:"));
1634
1635 process->SetDynamicCheckers(dynamic_checkers);
1636
1637 LLDB_LOGF(log, "== [ClangExpressionParser::PrepareForExecution] "
1638 "Finished installing dynamic checkers ==");
1639 }
1640
1641 if (auto *checker_funcs = llvm::dyn_cast<ClangDynamicCheckerFunctions>(
1642 process->GetDynamicCheckers())) {
1643 IRDynamicChecks ir_dynamic_checks(*checker_funcs,
1644 function_name.AsCString(nullptr));
1645
1646 llvm::Module *module = execution_unit_sp->GetModule();
1647 if (!module || !ir_dynamic_checks.runOnModule(*module)) {
1649 "Couldn't add dynamic checks to the expression");
1650 return err;
1651 }
1652
1653 if (custom_passes.LatePasses) {
1654 LLDB_LOGF(log,
1655 "%s - Running Late IR Passes from LanguageRuntime on "
1656 "expression module '%s'",
1657 __FUNCTION__, m_expr.FunctionName());
1658
1659 custom_passes.LatePasses->run(*module);
1660 }
1661 }
1662 }
1663 }
1664
1665 if (execution_policy == eExecutionPolicyAlways ||
1666 execution_policy == eExecutionPolicyTopLevel || !can_interpret) {
1667 execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);
1668 }
1669 } else {
1670 execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);
1671 }
1672
1673 return err;
1674}
static void SetupModuleHeaderPaths(CompilerInstance *compiler, std::vector< std::string > include_directories, lldb::TargetSP target_sp)
static void RemoveAllCppKeywords(IdentifierTable &idents)
Remove all C++ keywords from the given identifier table.
static void SetupLangOpts(CompilerInstance &compiler, ExecutionContextScope &exe_scope, const Expression &expr, DiagnosticManager &diagnostic_manager)
static void ApplyFixIt(const FixItHint &fixit, clang::edit::Commit &commit)
Applies the given Fix-It hint to the given commit.
static void SetupImportStdModuleLangOpts(CompilerInstance &compiler, lldb_private::Target &target)
static void AddAllFixIts(ClangDiagnostic *diag, const clang::Diagnostic &Info)
static void SetupDefaultClangDiagnostics(CompilerInstance &compiler)
Configures Clang diagnostics for the expression parser.
static void SetupTargetOpts(CompilerInstance &compiler, lldb_private::Target const &target)
static void RemoveCppKeyword(IdentifierTable &idents, llvm::StringRef token)
Iff the given identifier is a C++ keyword, remove it from the identifier table (i....
static void SetPointerAuthOptionsForArm64e(LangOptions &lang_opts)
static bool FindFunctionInModule(ConstString &mangled_name, llvm::Module *module, const char *orig_name)
static std::string GetClangTargetABI(const ArchSpec &target_arch)
Returns a string representing current ABI.
#define lldbassert(x)
Definition LLDBAssert.h:16
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:375
#define LLDB_LOGF(log,...)
Definition Log.h:389
void BeginSourceFile(const LangOptions &LO, const Preprocessor *PP) override
std::unique_ptr< clang::TextDiagnosticPrinter > m_passthrough
std::string m_output
Output string filled by m_os.
ClangDiagnosticManagerAdapter(DiagnosticOptions &opts, StringRef filename)
void ResetManager(DiagnosticManager *manager=nullptr)
void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, const clang::Diagnostic &Info) override
ClangDiagnostic * MaybeGetLastClangDiag() const
Returns the last error ClangDiagnostic message that the DiagnosticManager received or a nullptr.
std::unique_ptr< llvm::raw_string_ostream > m_os
Output stream of m_passthrough.
void moduleImport(SourceLocation import_location, clang::ModuleIdPath path, const clang::Module *) override
LLDBPreprocessorCallbacks(ClangModulesDeclVendor &decl_vendor, ClangPersistentVariables &persistent_vars, clang::SourceManager &source_mgr)
StreamString m_error_stream
Accumulates error messages across all moduleImport calls.
Transforms the IR for a function to run in the target.
Definition IRForTarget.h:61
bool runOnModule(llvm::Module &llvm_module)
Run this IR transformer on a single module.
static bool CanInterpret(llvm::Module &module, llvm::Function &function, lldb_private::Status &error, const bool support_function_calls)
An architecture specification class.
Definition ArchSpec.h:32
bool IsValid() const
Tests if this ArchSpec is valid.
Definition ArchSpec.h:455
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition ArchSpec.h:547
@ eLoongArch_abi_single_float
soft float
Definition ArchSpec.h:113
@ eLoongArch_abi_mask
double precision floating point, +d
Definition ArchSpec.h:117
@ eLoongArch_abi_double_float
single precision floating point, +f
Definition ArchSpec.h:115
bool IsMIPS() const
if MIPS architecture return true.
Definition ArchSpec.cpp:752
bool CharIsSignedByDefault() const
Returns true if 'char' is a signed type by default in the architecture false otherwise.
Definition ArchSpec.cpp:915
uint32_t GetFlags() const
Definition ArchSpec.h:618
llvm::Triple::ArchType GetMachine() const
Returns a machine family for the current architecture.
Definition ArchSpec.cpp:886
@ eRISCV_float_abi_double
single precision floating point, +f
Definition ArchSpec.h:98
@ eRISCV_float_abi_soft
RVC, +c.
Definition ArchSpec.h:96
@ eRISCV_float_abi_quad
double precision floating point, +d
Definition ArchSpec.h:99
@ eRISCV_float_abi_mask
quad precision floating point, +q
Definition ArchSpec.h:100
@ eRISCV_float_abi_single
soft float
Definition ArchSpec.h:97
std::string GetClangTargetCPU() const
Returns a string representing current architecture as a target CPU for tools like compiler,...
Definition ArchSpec.cpp:792
llvm::IntrusiveRefCntPtr< clang::ExternalASTSource > CreateProxy()
void InstallASTContext(TypeSystemClang &ast_context)
void AddFixitHint(const clang::FixItHint &fixit)
llvm::Error Install(DiagnosticManager &diagnostic_manager, ExecutionContext &exe_ctx) override
Install the utility functions into a process.
"lldb/Expression/ClangExpressionDeclMap.h" Manages named entities that are defined in LLDB's debug in...
void InstallDiagnosticManager(DiagnosticManager &diag_manager)
void InstallCodeGenerator(clang::ASTConsumer *code_gen)
virtual clang::ASTConsumer * ASTTransformer(clang::ASTConsumer *passthrough)=0
Return the object that the parser should allow to access ASTs.
virtual ClangExpressionDeclMap * DeclMap()=0
Return the object that the parser should use when resolving external values.
ClangExpressionParser(ExecutionContextScope *exe_scope, Expression &expr, bool generate_debug_info, DiagnosticManager &diagnostic_manager, std::vector< std::string > include_directories={}, std::string filename="<clang expression>", bool force_disable_ptrauth_codegen=false)
Constructor.
std::string m_filename
File name used for the user expression.
bool RewriteExpression(DiagnosticManager &diagnostic_manager) override
Try to use the FixIts in the diagnostic_manager to rewrite the expression.
unsigned ParseInternal(DiagnosticManager &diagnostic_manager, clang::CodeCompleteConsumer *completion=nullptr, unsigned completion_line=0, unsigned completion_column=0)
Parses the expression.
std::unique_ptr< clang::CompilerInstance > m_compiler
The Clang compiler used to parse expressions into IR.
Status DoPrepareForExecution(lldb::addr_t &func_addr, lldb::addr_t &func_end, lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx, bool &can_interpret, lldb_private::ExecutionPolicy execution_policy) override
Ready an already-parsed expression for execution, possibly evaluating it statically.
unsigned Parse(DiagnosticManager &diagnostic_manager)
Parse a single expression and convert it to IR using Clang.
bool Complete(CompletionRequest &request, unsigned line, unsigned pos, unsigned typed_pos) override
Attempts to find possible command line completions for the given expression.
~ClangExpressionParser() override
Destructor.
std::unique_ptr< llvm::LLVMContext > m_llvm_context
The LLVM context to generate IR into.
std::unique_ptr< clang::CodeGenerator > m_code_generator
The Clang object that generates IR.
LLDBPreprocessorCallbacks * m_pp_callbacks
Called when the preprocessor encounters module imports.
std::vector< std::string > m_include_directories
std::shared_ptr< TypeSystemClang > m_ast_context
static const llvm::StringRef g_prefix_file_name
The file name we use for the wrapper code that we inject before the user expression.
"lldb/Expression/ClangPersistentVariables.h" Manages persistent values that need to be preserved betw...
"lldb/Expression/ClangUserExpression.h" Encapsulates a single expression for use with Clang
"lldb/Utility/ArgCompletionRequest.h"
void AddCompletion(llvm::StringRef completion, llvm::StringRef description="", CompletionMode mode=CompletionMode::Normal)
Adds a possible completion string.
A single completion and all associated data.
std::string GetUniqueKey() const
Generates a string that uniquely identifies this completion result.
A uniqued constant string class.
Definition ConstString.h:40
void SetString(llvm::StringRef s)
const char * AsCString(const char *value_if_empty) const
Get the string value as a C string.
size_t void PutString(lldb::Severity severity, llvm::StringRef str)
const DiagnosticList & Diagnostics() const
llvm::Error GetAsError(lldb::ExpressionResults result, llvm::Twine message={}) const
Returns an ExpressionError with arg as error code.
void SetFixedExpression(std::string fixed_expression)
void AppendMessageToDiagnostic(llvm::StringRef str)
void AddDiagnostic(llvm::StringRef message, lldb::Severity severity, DiagnosticOrigin origin, uint32_t compiler_id=LLDB_INVALID_COMPILER_ID)
"lldb/Target/ExecutionContextScope.h" Inherit from this if your object can reconstruct its execution ...
virtual lldb::StackFrameSP CalculateStackFrame()=0
virtual lldb::ProcessSP CalculateProcess()=0
virtual lldb::TargetSP CalculateTarget()=0
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
const lldb::TargetSP & GetTargetSP() const
Get accessor to get the target shared pointer.
const lldb::ProcessSP & GetProcessSP() const
Get accessor to get the process shared pointer.
const lldb::StackFrameSP & GetFrameSP() const
Get accessor to get the frame shared pointer.
Process * GetProcessPtr() const
Returns a pointer to the process object.
ExpressionParser(ExecutionContextScope *exe_scope, Expression &expr, bool generate_debug_info)
Constructor.
Expression & m_expr
The expression to be parsed.
Encapsulates a single expression for use in lldb.
Definition Expression.h:32
virtual SourceLanguage Language() const
Return the language that should be used when parsing.
Definition Expression.h:52
virtual ResultType DesiredResultType() const
Return the desired result type of the function, or eResultTypeAny if indifferent.
Definition Expression.h:60
A file utility class.
Definition FileSpec.h:56
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:380
static FileSystem & Instance()
"lldb/Expression/IRDynamicChecks.h" Adds dynamic checks to a user-entered expression to reduce its li...
bool runOnModule(llvm::Module &M) override
Run this IR transformer on a single module.
static const char * GetNameForLanguageType(lldb::LanguageType language)
Returns the internal LLDB name for the specified language.
Definition Language.cpp:334
static llvm::StringRef GetDisplayNameForLanguageType(lldb::LanguageType language)
Returns a user-friendly name for the specified language.
Definition Language.cpp:341
static ModuleListProperties & GetGlobalModuleListProperties()
Status Close() override
Flush any buffers and release any resources owned by the file.
Definition File.cpp:303
Status Write(const void *src, size_t &num_bytes, off_t &offset) override
Write bytes to a file at the specified file offset.
static bool IsSupportedForArchitecture(const ArchSpec &arch)
Returns whether the architecture's object file format supports Objective-C code generation.
static ObjCLanguageRuntime * Get(Process &process)
A plug-in interface definition class for debugging a process.
Definition Process.h:369
void SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers)
Definition Process.cpp:1604
DynamicCheckerFunctions * GetDynamicCheckers()
Definition Process.h:2525
bool CanInterpretFunctionCalls()
Determines whether executing function calls using the interpreter is possible for this process.
Definition Process.h:2122
An error handling class.
Definition Status.h:118
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Definition Status.cpp:106
static Status FromErrorString(const char *str)
Definition Status.h:141
const char * AsCString(const char *default_error_str="unknown error") const
Get the error string associated with the current error.
Definition Status.cpp:194
static Status FromError(llvm::Error error)
Avoid using this in new code. Migrate APIs to llvm::Expected instead.
Definition Status.cpp:136
bool Success() const
Test for success condition.
Definition Status.cpp:303
llvm::StringRef GetString() const
Defines a symbol context baton that can be handed other debug core functions.
lldb::TargetSP target_sp
The Target for a given query.
const ArchSpec & GetArchitecture() const
Definition Target.h:1324
const char * GetUserText()
Return the string that the user typed.
#define LLDB_INVALID_ADDRESS
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:338
FileSpec GetClangResourceDir()
ExecutionPolicy
Expression execution policies.
NativeFilePosix NativeFile
Definition File.h:29
std::vector< std::unique_ptr< Diagnostic > > DiagnosticList
bool operator<(const Address &lhs, const Address &rhs)
Definition Address.cpp:974
std::shared_ptr< lldb_private::IRExecutionUnit > IRExecutionUnitSP
std::shared_ptr< lldb_private::StackFrame > StackFrameSP
LanguageType
Programming language type.
@ eLanguageTypeC_plus_plus_20
ISO C++:2020.
@ eLanguageTypeC_plus_plus_14
ISO C++:2014.
@ eLanguageTypeC11
ISO C:2011.
@ eLanguageTypeC99
ISO C:1999.
@ eLanguageTypeC_plus_plus_03
ISO C++:2003.
@ eLanguageTypeUnknown
Unknown or invalid language value.
@ eLanguageTypeC_plus_plus_17
ISO C++:2017.
@ eLanguageTypeObjC_plus_plus
Objective-C++.
@ eLanguageTypeC_plus_plus_11
ISO C++:2011.
@ eLanguageTypeC89
ISO C:1989.
@ eLanguageTypeC
Non-standardized C, such as K&R.
@ eLanguageTypeObjC
Objective-C.
@ eLanguageTypeC_plus_plus
ISO C++:1998.
@ eExpressionSetupError
std::shared_ptr< lldb_private::Process > ProcessSP
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::Target > TargetSP
A source location consisting of a file name and position.
bool in_user_input
Whether this source location refers to something the user typed as part of the command,...
FileSpec file
"<user expression 0>" in the example above.
bool hidden
Whether this source location should be surfaced to the user.
A compiler-independent representation of an lldb_private::Diagnostic.
std::shared_ptr< llvm::legacy::PassManager > EarlyPasses
std::shared_ptr< llvm::legacy::PassManager > LatePasses
lldb::LanguageType AsLanguageType() const
Definition Language.cpp:657
Information needed to import a source-language module.