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