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