1 //===-- ClangExpressionParser.cpp -------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
12 // Other libraries and framework includes
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/ASTDiagnostic.h"
15 #include "clang/AST/ExternalASTSource.h"
16 #include "clang/Basic/DiagnosticIDs.h"
17 #include "clang/Basic/FileManager.h"
18 #include "clang/Basic/SourceLocation.h"
19 #include "clang/Basic/TargetInfo.h"
20 #include "clang/Basic/Version.h"
21 #include "clang/CodeGen/CodeGenAction.h"
22 #include "clang/CodeGen/ModuleBuilder.h"
23 #include "clang/Edit/Commit.h"
24 #include "clang/Edit/EditedSource.h"
25 #include "clang/Edit/EditsReceiver.h"
26 #include "clang/Frontend/CompilerInstance.h"
27 #include "clang/Frontend/CompilerInvocation.h"
28 #include "clang/Frontend/FrontendActions.h"
29 #include "clang/Frontend/FrontendDiagnostic.h"
30 #include "clang/Frontend/FrontendPluginRegistry.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/SemaConsumer.h"
39 #include "llvm/ADT/StringRef.h"
40 #include "llvm/ExecutionEngine/ExecutionEngine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/FileSystem.h"
43 #include "llvm/Support/TargetSelect.h"
45 #pragma clang diagnostic push
46 #pragma clang diagnostic ignored "-Wglobal-constructors"
47 #include "llvm/ExecutionEngine/MCJIT.h"
48 #pragma clang diagnostic pop
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/Host.h"
55 #include "llvm/Support/MemoryBuffer.h"
56 #include "llvm/Support/Signals.h"
59 #include "ClangDiagnostic.h"
60 #include "ClangExpressionParser.h"
62 #include "ClangASTSource.h"
63 #include "ClangExpressionDeclMap.h"
64 #include "ClangExpressionHelper.h"
65 #include "ClangModulesDeclVendor.h"
66 #include "ClangPersistentVariables.h"
67 #include "IRForTarget.h"
69 #include "lldb/Core/Debugger.h"
70 #include "lldb/Core/Disassembler.h"
71 #include "lldb/Core/Module.h"
72 #include "lldb/Core/StreamFile.h"
73 #include "lldb/Expression/IRDynamicChecks.h"
74 #include "lldb/Expression/IRExecutionUnit.h"
75 #include "lldb/Expression/IRInterpreter.h"
76 #include "lldb/Host/File.h"
77 #include "lldb/Host/HostInfo.h"
78 #include "lldb/Symbol/ClangASTContext.h"
79 #include "lldb/Symbol/SymbolVendor.h"
80 #include "lldb/Target/ExecutionContext.h"
81 #include "lldb/Target/Language.h"
82 #include "lldb/Target/ObjCLanguageRuntime.h"
83 #include "lldb/Target/Process.h"
84 #include "lldb/Target/Target.h"
85 #include "lldb/Target/ThreadPlanCallFunction.h"
86 #include "lldb/Utility/DataBufferHeap.h"
87 #include "lldb/Utility/LLDBAssert.h"
88 #include "lldb/Utility/Log.h"
89 #include "lldb/Utility/Stream.h"
90 #include "lldb/Utility/StreamString.h"
91 #include "lldb/Utility/StringList.h"
93 using namespace clang;
95 using namespace lldb_private;
97 //===----------------------------------------------------------------------===//
98 // Utility Methods for Clang
99 //===----------------------------------------------------------------------===//
101 class ClangExpressionParser::LLDBPreprocessorCallbacks : public PPCallbacks {
102 ClangModulesDeclVendor &m_decl_vendor;
103 ClangPersistentVariables &m_persistent_vars;
104 StreamString m_error_stream;
105 bool m_has_errors = false;
108 LLDBPreprocessorCallbacks(ClangModulesDeclVendor &decl_vendor,
109 ClangPersistentVariables &persistent_vars)
110 : m_decl_vendor(decl_vendor), m_persistent_vars(persistent_vars) {}
112 void moduleImport(SourceLocation import_location, clang::ModuleIdPath path,
113 const clang::Module * /*null*/) override {
114 std::vector<ConstString> string_path;
116 for (const std::pair<IdentifierInfo *, SourceLocation> &component : path) {
117 string_path.push_back(ConstString(component.first->getName()));
120 StreamString error_stream;
122 ClangModulesDeclVendor::ModuleVector exported_modules;
124 if (!m_decl_vendor.AddModule(string_path, &exported_modules,
129 for (ClangModulesDeclVendor::ModuleID module : exported_modules) {
130 m_persistent_vars.AddHandLoadedClangModule(module);
134 bool hasErrors() { return m_has_errors; }
136 llvm::StringRef getErrorString() { return m_error_stream.GetString(); }
139 class ClangDiagnosticManagerAdapter : public clang::DiagnosticConsumer {
141 ClangDiagnosticManagerAdapter()
142 : m_passthrough(new clang::TextDiagnosticBuffer) {}
144 ClangDiagnosticManagerAdapter(
145 const std::shared_ptr<clang::TextDiagnosticBuffer> &passthrough)
146 : m_passthrough(passthrough) {}
148 void ResetManager(DiagnosticManager *manager = nullptr) {
152 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
153 const clang::Diagnostic &Info) {
155 llvm::SmallVector<char, 32> diag_str;
156 Info.FormatDiagnostic(diag_str);
157 diag_str.push_back('\0');
158 const char *data = diag_str.data();
160 lldb_private::DiagnosticSeverity severity;
161 bool make_new_diagnostic = true;
164 case DiagnosticsEngine::Level::Fatal:
165 case DiagnosticsEngine::Level::Error:
166 severity = eDiagnosticSeverityError;
168 case DiagnosticsEngine::Level::Warning:
169 severity = eDiagnosticSeverityWarning;
171 case DiagnosticsEngine::Level::Remark:
172 case DiagnosticsEngine::Level::Ignored:
173 severity = eDiagnosticSeverityRemark;
175 case DiagnosticsEngine::Level::Note:
176 m_manager->AppendMessageToDiagnostic(data);
177 make_new_diagnostic = false;
179 if (make_new_diagnostic) {
180 ClangDiagnostic *new_diagnostic =
181 new ClangDiagnostic(data, severity, Info.getID());
182 m_manager->AddDiagnostic(new_diagnostic);
184 // Don't store away warning fixits, since the compiler doesn't have
185 // enough context in an expression for the warning to be useful.
186 // FIXME: Should we try to filter out FixIts that apply to our generated
187 // code, and not the user's expression?
188 if (severity == eDiagnosticSeverityError) {
189 size_t num_fixit_hints = Info.getNumFixItHints();
190 for (size_t i = 0; i < num_fixit_hints; i++) {
191 const clang::FixItHint &fixit = Info.getFixItHint(i);
193 new_diagnostic->AddFixitHint(fixit);
199 m_passthrough->HandleDiagnostic(DiagLevel, Info);
202 void FlushDiagnostics(DiagnosticsEngine &Diags) {
203 m_passthrough->FlushDiagnostics(Diags);
206 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
207 return new ClangDiagnosticManagerAdapter(m_passthrough);
210 clang::TextDiagnosticBuffer *GetPassthrough() { return m_passthrough.get(); }
213 DiagnosticManager *m_manager = nullptr;
214 std::shared_ptr<clang::TextDiagnosticBuffer> m_passthrough;
217 //===----------------------------------------------------------------------===//
218 // Implementation of ClangExpressionParser
219 //===----------------------------------------------------------------------===//
221 ClangExpressionParser::ClangExpressionParser(ExecutionContextScope *exe_scope,
223 bool generate_debug_info)
224 : ExpressionParser(exe_scope, expr, generate_debug_info), m_compiler(),
225 m_code_generator(), m_pp_callbacks(nullptr) {
226 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
228 // We can't compile expressions without a target. So if the exe_scope is
229 // null or doesn't have a target, then we just need to get out of here. I'll
230 // lldb_assert and not make any of the compiler objects since
231 // I can't return errors directly from the constructor. Further calls will
232 // check if the compiler was made and
233 // bag out if it wasn't.
236 lldb_assert(exe_scope, "Can't make an expression parser with a null scope.",
237 __FUNCTION__, __FILE__, __LINE__);
241 lldb::TargetSP target_sp;
242 target_sp = exe_scope->CalculateTarget();
244 lldb_assert(target_sp.get(),
245 "Can't make an expression parser with a null target.",
246 __FUNCTION__, __FILE__, __LINE__);
250 // 1. Create a new compiler instance.
251 m_compiler.reset(new CompilerInstance());
252 lldb::LanguageType frame_lang =
253 expr.Language(); // defaults to lldb::eLanguageTypeUnknown
254 bool overridden_target_opts = false;
255 lldb_private::LanguageRuntime *lang_rt = nullptr;
258 ArchSpec target_arch;
259 target_arch = target_sp->GetArchitecture();
261 const auto target_machine = target_arch.GetMachine();
263 // If the expression is being evaluated in the context of an existing stack
264 // frame, we introspect to see if the language runtime is available.
266 lldb::StackFrameSP frame_sp = exe_scope->CalculateStackFrame();
267 lldb::ProcessSP process_sp = exe_scope->CalculateProcess();
269 // Make sure the user hasn't provided a preferred execution language with
270 // `expression --language X -- ...`
271 if (frame_sp && frame_lang == lldb::eLanguageTypeUnknown)
272 frame_lang = frame_sp->GetLanguage();
274 if (process_sp && frame_lang != lldb::eLanguageTypeUnknown) {
275 lang_rt = process_sp->GetLanguageRuntime(frame_lang);
277 log->Printf("Frame has language of type %s",
278 Language::GetNameForLanguageType(frame_lang));
281 // 2. Configure the compiler with a set of default options that are
282 // appropriate for most situations.
283 if (target_arch.IsValid()) {
284 std::string triple = target_arch.GetTriple().str();
285 m_compiler->getTargetOpts().Triple = triple;
287 log->Printf("Using %s as the target triple",
288 m_compiler->getTargetOpts().Triple.c_str());
290 // If we get here we don't have a valid target and just have to guess.
291 // Sometimes this will be ok to just use the host target triple (when we
292 // evaluate say "2+3", but other expressions like breakpoint conditions and
293 // other things that _are_ target specific really shouldn't just be using
294 // the host triple. In such a case the language runtime should expose an
295 // overridden options set (3), below.
296 m_compiler->getTargetOpts().Triple = llvm::sys::getDefaultTargetTriple();
298 log->Printf("Using default target triple of %s",
299 m_compiler->getTargetOpts().Triple.c_str());
301 // Now add some special fixes for known architectures: Any arm32 iOS
302 // environment, but not on arm64
303 if (m_compiler->getTargetOpts().Triple.find("arm64") == std::string::npos &&
304 m_compiler->getTargetOpts().Triple.find("arm") != std::string::npos &&
305 m_compiler->getTargetOpts().Triple.find("ios") != std::string::npos) {
306 m_compiler->getTargetOpts().ABI = "apcs-gnu";
308 // Supported subsets of x86
309 if (target_machine == llvm::Triple::x86 ||
310 target_machine == llvm::Triple::x86_64) {
311 m_compiler->getTargetOpts().Features.push_back("+sse");
312 m_compiler->getTargetOpts().Features.push_back("+sse2");
315 // Set the target CPU to generate code for. This will be empty for any CPU
316 // that doesn't really need to make a special
318 m_compiler->getTargetOpts().CPU = target_arch.GetClangTargetCPU();
320 // Set the target ABI
321 abi = GetClangTargetABI(target_arch);
323 m_compiler->getTargetOpts().ABI = abi;
325 // 3. Now allow the runtime to provide custom configuration options for the
326 // target. In this case, a specialized language runtime is available and we
327 // can query it for extra options. For 99% of use cases, this will not be
328 // needed and should be provided when basic platform detection is not enough.
330 overridden_target_opts =
331 lang_rt->GetOverrideExprOptions(m_compiler->getTargetOpts());
333 if (overridden_target_opts)
334 if (log && log->GetVerbose()) {
336 log, "Using overridden target options for the expression evaluation");
338 auto opts = m_compiler->getTargetOpts();
339 LLDB_LOGV(log, "Triple: '{0}'", opts.Triple);
340 LLDB_LOGV(log, "CPU: '{0}'", opts.CPU);
341 LLDB_LOGV(log, "FPMath: '{0}'", opts.FPMath);
342 LLDB_LOGV(log, "ABI: '{0}'", opts.ABI);
343 LLDB_LOGV(log, "LinkerVersion: '{0}'", opts.LinkerVersion);
344 StringList::LogDump(log, opts.FeaturesAsWritten, "FeaturesAsWritten");
345 StringList::LogDump(log, opts.Features, "Features");
348 // 4. Create and install the target on the compiler.
349 m_compiler->createDiagnostics();
350 auto target_info = TargetInfo::CreateTargetInfo(
351 m_compiler->getDiagnostics(), m_compiler->getInvocation().TargetOpts);
353 log->Printf("Using SIMD alignment: %d", target_info->getSimdDefaultAlign());
354 log->Printf("Target datalayout string: '%s'",
355 target_info->getDataLayout().getStringRepresentation().c_str());
356 log->Printf("Target ABI: '%s'", target_info->getABI().str().c_str());
357 log->Printf("Target vector alignment: %d",
358 target_info->getMaxVectorAlign());
360 m_compiler->setTarget(target_info);
362 assert(m_compiler->hasTarget());
364 // 5. Set language options.
365 lldb::LanguageType language = expr.Language();
368 case lldb::eLanguageTypeC:
369 case lldb::eLanguageTypeC89:
370 case lldb::eLanguageTypeC99:
371 case lldb::eLanguageTypeC11:
372 // FIXME: the following language option is a temporary workaround,
373 // to "ask for C, get C++."
374 // For now, the expression parser must use C++ anytime the language is a C
375 // family language, because the expression parser uses features of C++ to
377 m_compiler->getLangOpts().CPlusPlus = true;
379 case lldb::eLanguageTypeObjC:
380 m_compiler->getLangOpts().ObjC1 = true;
381 m_compiler->getLangOpts().ObjC2 = true;
382 // FIXME: the following language option is a temporary workaround,
383 // to "ask for ObjC, get ObjC++" (see comment above).
384 m_compiler->getLangOpts().CPlusPlus = true;
386 // Clang now sets as default C++14 as the default standard (with
387 // GNU extensions), so we do the same here to avoid mismatches that
388 // cause compiler error when evaluating expressions (e.g. nullptr not found
389 // as it's a C++11 feature). Currently lldb evaluates C++14 as C++11 (see
390 // two lines below) so we decide to be consistent with that, but this could
391 // be re-evaluated in the future.
392 m_compiler->getLangOpts().CPlusPlus11 = true;
394 case lldb::eLanguageTypeC_plus_plus:
395 case lldb::eLanguageTypeC_plus_plus_11:
396 case lldb::eLanguageTypeC_plus_plus_14:
397 m_compiler->getLangOpts().CPlusPlus11 = true;
398 m_compiler->getHeaderSearchOpts().UseLibcxx = true;
400 case lldb::eLanguageTypeC_plus_plus_03:
401 m_compiler->getLangOpts().CPlusPlus = true;
402 // FIXME: the following language option is a temporary workaround,
403 // to "ask for C++, get ObjC++". Apple hopes to remove this requirement on
404 // non-Apple platforms, but for now it is needed.
405 m_compiler->getLangOpts().ObjC1 = true;
407 case lldb::eLanguageTypeObjC_plus_plus:
408 case lldb::eLanguageTypeUnknown:
410 m_compiler->getLangOpts().ObjC1 = true;
411 m_compiler->getLangOpts().ObjC2 = true;
412 m_compiler->getLangOpts().CPlusPlus = true;
413 m_compiler->getLangOpts().CPlusPlus11 = true;
414 m_compiler->getHeaderSearchOpts().UseLibcxx = true;
418 m_compiler->getLangOpts().Bool = true;
419 m_compiler->getLangOpts().WChar = true;
420 m_compiler->getLangOpts().Blocks = true;
421 m_compiler->getLangOpts().DebuggerSupport =
422 true; // Features specifically for debugger clients
423 if (expr.DesiredResultType() == Expression::eResultTypeId)
424 m_compiler->getLangOpts().DebuggerCastResultToId = true;
426 m_compiler->getLangOpts().CharIsSigned =
427 ArchSpec(m_compiler->getTargetOpts().Triple.c_str())
428 .CharIsSignedByDefault();
430 // Spell checking is a nice feature, but it ends up completing a lot of types
431 // that we didn't strictly speaking need to complete. As a result, we spend a
432 // long time parsing and importing debug information.
433 m_compiler->getLangOpts().SpellChecking = false;
435 if (process_sp && m_compiler->getLangOpts().ObjC1) {
436 if (process_sp->GetObjCLanguageRuntime()) {
437 if (process_sp->GetObjCLanguageRuntime()->GetRuntimeVersion() ==
438 ObjCLanguageRuntime::ObjCRuntimeVersions::eAppleObjC_V2)
439 m_compiler->getLangOpts().ObjCRuntime.set(ObjCRuntime::MacOSX,
440 VersionTuple(10, 7));
442 m_compiler->getLangOpts().ObjCRuntime.set(ObjCRuntime::FragileMacOSX,
443 VersionTuple(10, 7));
445 if (process_sp->GetObjCLanguageRuntime()->HasNewLiteralsAndIndexing())
446 m_compiler->getLangOpts().DebuggerObjCLiteral = true;
450 m_compiler->getLangOpts().ThreadsafeStatics = false;
451 m_compiler->getLangOpts().AccessControl =
452 false; // Debuggers get universal access
453 m_compiler->getLangOpts().DollarIdents =
454 true; // $ indicates a persistent variable name
456 // Set CodeGen options
457 m_compiler->getCodeGenOpts().EmitDeclMetadata = true;
458 m_compiler->getCodeGenOpts().InstrumentFunctions = false;
459 m_compiler->getCodeGenOpts().DisableFPElim = true;
460 m_compiler->getCodeGenOpts().OmitLeafFramePointer = false;
461 if (generate_debug_info)
462 m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::FullDebugInfo);
464 m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::NoDebugInfo);
466 // Disable some warnings.
467 m_compiler->getDiagnostics().setSeverityForGroup(
468 clang::diag::Flavor::WarningOrError, "unused-value",
469 clang::diag::Severity::Ignored, SourceLocation());
470 m_compiler->getDiagnostics().setSeverityForGroup(
471 clang::diag::Flavor::WarningOrError, "odr",
472 clang::diag::Severity::Ignored, SourceLocation());
474 // Inform the target of the language options
476 // FIXME: We shouldn't need to do this, the target should be immutable once
477 // created. This complexity should be lifted elsewhere.
478 m_compiler->getTarget().adjust(m_compiler->getLangOpts());
480 // 6. Set up the diagnostic buffer for reporting errors
482 m_compiler->getDiagnostics().setClient(new ClangDiagnosticManagerAdapter);
484 // 7. Set up the source management objects inside the compiler
486 clang::FileSystemOptions file_system_options;
487 m_file_manager.reset(new clang::FileManager(file_system_options));
489 if (!m_compiler->hasSourceManager())
490 m_compiler->createSourceManager(*m_file_manager.get());
492 m_compiler->createFileManager();
493 m_compiler->createPreprocessor(TU_Complete);
495 if (ClangModulesDeclVendor *decl_vendor =
496 target_sp->GetClangModulesDeclVendor()) {
497 ClangPersistentVariables *clang_persistent_vars =
498 llvm::cast<ClangPersistentVariables>(
499 target_sp->GetPersistentExpressionStateForLanguage(
500 lldb::eLanguageTypeC));
501 std::unique_ptr<PPCallbacks> pp_callbacks(
502 new LLDBPreprocessorCallbacks(*decl_vendor, *clang_persistent_vars));
504 static_cast<LLDBPreprocessorCallbacks *>(pp_callbacks.get());
505 m_compiler->getPreprocessor().addPPCallbacks(std::move(pp_callbacks));
508 // 8. Most of this we get from the CompilerInstance, but we also want to give
509 // the context an ExternalASTSource.
510 m_selector_table.reset(new SelectorTable());
511 m_builtin_context.reset(new Builtin::Context());
513 std::unique_ptr<clang::ASTContext> ast_context(
514 new ASTContext(m_compiler->getLangOpts(), m_compiler->getSourceManager(),
515 m_compiler->getPreprocessor().getIdentifierTable(),
516 *m_selector_table.get(), *m_builtin_context.get()));
518 ast_context->InitBuiltinTypes(m_compiler->getTarget());
520 ClangExpressionHelper *type_system_helper =
521 dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
522 ClangExpressionDeclMap *decl_map = type_system_helper->DeclMap();
525 llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> ast_source(
526 decl_map->CreateProxy());
527 decl_map->InstallASTContext(*ast_context, m_compiler->getFileManager());
528 ast_context->setExternalSource(ast_source);
532 new ClangASTContext(m_compiler->getTargetOpts().Triple.c_str()));
533 m_ast_context->setASTContext(ast_context.get());
534 m_compiler->setASTContext(ast_context.release());
536 std::string module_name("$__lldb_module");
538 m_llvm_context.reset(new LLVMContext());
539 m_code_generator.reset(CreateLLVMCodeGen(
540 m_compiler->getDiagnostics(), module_name,
541 m_compiler->getHeaderSearchOpts(), m_compiler->getPreprocessorOpts(),
542 m_compiler->getCodeGenOpts(), *m_llvm_context));
545 ClangExpressionParser::~ClangExpressionParser() {}
547 unsigned ClangExpressionParser::Parse(DiagnosticManager &diagnostic_manager) {
548 ClangDiagnosticManagerAdapter *adapter =
549 static_cast<ClangDiagnosticManagerAdapter *>(
550 m_compiler->getDiagnostics().getClient());
551 clang::TextDiagnosticBuffer *diag_buf = adapter->GetPassthrough();
552 diag_buf->FlushDiagnostics(m_compiler->getDiagnostics());
554 adapter->ResetManager(&diagnostic_manager);
556 const char *expr_text = m_expr.Text();
558 clang::SourceManager &source_mgr = m_compiler->getSourceManager();
559 bool created_main_file = false;
560 if (m_compiler->getCodeGenOpts().getDebugInfo() ==
561 codegenoptions::FullDebugInfo) {
563 llvm::SmallString<PATH_MAX> result_path;
564 if (FileSpec tmpdir_file_spec = HostInfo::GetProcessTempDir()) {
565 tmpdir_file_spec.AppendPathComponent("lldb-%%%%%%.expr");
566 std::string temp_source_path = tmpdir_file_spec.GetPath();
567 llvm::sys::fs::createUniqueFile(temp_source_path, temp_fd, result_path);
569 llvm::sys::fs::createTemporaryFile("lldb", "expr", temp_fd, result_path);
573 lldb_private::File file(temp_fd, true);
574 const size_t expr_text_len = strlen(expr_text);
575 size_t bytes_written = expr_text_len;
576 if (file.Write(expr_text, bytes_written).Success()) {
577 if (bytes_written == expr_text_len) {
579 source_mgr.setMainFileID(
580 source_mgr.createFileID(m_file_manager->getFile(result_path),
581 SourceLocation(), SrcMgr::C_User));
582 created_main_file = true;
588 if (!created_main_file) {
589 std::unique_ptr<MemoryBuffer> memory_buffer =
590 MemoryBuffer::getMemBufferCopy(expr_text, __FUNCTION__);
591 source_mgr.setMainFileID(source_mgr.createFileID(std::move(memory_buffer)));
594 diag_buf->BeginSourceFile(m_compiler->getLangOpts(),
595 &m_compiler->getPreprocessor());
597 ClangExpressionHelper *type_system_helper =
598 dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
600 ASTConsumer *ast_transformer =
601 type_system_helper->ASTTransformer(m_code_generator.get());
603 if (ClangExpressionDeclMap *decl_map = type_system_helper->DeclMap())
604 decl_map->InstallCodeGenerator(m_code_generator.get());
606 if (ast_transformer) {
607 ast_transformer->Initialize(m_compiler->getASTContext());
608 ParseAST(m_compiler->getPreprocessor(), ast_transformer,
609 m_compiler->getASTContext());
611 m_code_generator->Initialize(m_compiler->getASTContext());
612 ParseAST(m_compiler->getPreprocessor(), m_code_generator.get(),
613 m_compiler->getASTContext());
616 diag_buf->EndSourceFile();
618 unsigned num_errors = diag_buf->getNumErrors();
620 if (m_pp_callbacks && m_pp_callbacks->hasErrors()) {
622 diagnostic_manager.PutString(eDiagnosticSeverityError,
623 "while importing modules:");
624 diagnostic_manager.AppendMessageToDiagnostic(
625 m_pp_callbacks->getErrorString());
629 if (type_system_helper->DeclMap() &&
630 !type_system_helper->DeclMap()->ResolveUnknownTypes()) {
631 diagnostic_manager.Printf(eDiagnosticSeverityError,
632 "Couldn't infer the type of a variable");
638 type_system_helper->CommitPersistentDecls();
641 adapter->ResetManager();
647 ClangExpressionParser::GetClangTargetABI(const ArchSpec &target_arch) {
650 if (target_arch.IsMIPS()) {
651 switch (target_arch.GetFlags() & ArchSpec::eMIPSABI_mask) {
652 case ArchSpec::eMIPSABI_N64:
655 case ArchSpec::eMIPSABI_N32:
658 case ArchSpec::eMIPSABI_O32:
668 bool ClangExpressionParser::RewriteExpression(
669 DiagnosticManager &diagnostic_manager) {
670 clang::SourceManager &source_manager = m_compiler->getSourceManager();
671 clang::edit::EditedSource editor(source_manager, m_compiler->getLangOpts(),
673 clang::edit::Commit commit(editor);
674 clang::Rewriter rewriter(source_manager, m_compiler->getLangOpts());
676 class RewritesReceiver : public edit::EditsReceiver {
680 RewritesReceiver(Rewriter &in_rewrite) : rewrite(in_rewrite) {}
682 void insert(SourceLocation loc, StringRef text) override {
683 rewrite.InsertText(loc, text);
685 void replace(CharSourceRange range, StringRef text) override {
686 rewrite.ReplaceText(range.getBegin(), rewrite.getRangeSize(range), text);
690 RewritesReceiver rewrites_receiver(rewriter);
692 const DiagnosticList &diagnostics = diagnostic_manager.Diagnostics();
693 size_t num_diags = diagnostics.size();
697 for (const Diagnostic *diag : diagnostic_manager.Diagnostics()) {
698 const ClangDiagnostic *diagnostic = llvm::dyn_cast<ClangDiagnostic>(diag);
699 if (diagnostic && diagnostic->HasFixIts()) {
700 for (const FixItHint &fixit : diagnostic->FixIts()) {
701 // This is cobbed from clang::Rewrite::FixItRewriter.
702 if (fixit.CodeToInsert.empty()) {
703 if (fixit.InsertFromRange.isValid()) {
704 commit.insertFromRange(fixit.RemoveRange.getBegin(),
705 fixit.InsertFromRange, /*afterToken=*/false,
706 fixit.BeforePreviousInsertions);
708 commit.remove(fixit.RemoveRange);
710 if (fixit.RemoveRange.isTokenRange() ||
711 fixit.RemoveRange.getBegin() != fixit.RemoveRange.getEnd())
712 commit.replace(fixit.RemoveRange, fixit.CodeToInsert);
714 commit.insert(fixit.RemoveRange.getBegin(), fixit.CodeToInsert,
715 /*afterToken=*/false, fixit.BeforePreviousInsertions);
721 // FIXME - do we want to try to propagate specific errors here?
722 if (!commit.isCommitable())
724 else if (!editor.commit(commit))
727 // Now play all the edits, and stash the result in the diagnostic manager.
728 editor.applyRewrites(rewrites_receiver);
729 RewriteBuffer &main_file_buffer =
730 rewriter.getEditBuffer(source_manager.getMainFileID());
732 std::string fixed_expression;
733 llvm::raw_string_ostream out_stream(fixed_expression);
735 main_file_buffer.write(out_stream);
737 diagnostic_manager.SetFixedExpression(fixed_expression);
742 static bool FindFunctionInModule(ConstString &mangled_name,
743 llvm::Module *module, const char *orig_name) {
744 for (const auto &func : module->getFunctionList()) {
745 const StringRef &name = func.getName();
746 if (name.find(orig_name) != StringRef::npos) {
747 mangled_name.SetString(name);
755 lldb_private::Status ClangExpressionParser::PrepareForExecution(
756 lldb::addr_t &func_addr, lldb::addr_t &func_end,
757 lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx,
758 bool &can_interpret, ExecutionPolicy execution_policy) {
759 func_addr = LLDB_INVALID_ADDRESS;
760 func_end = LLDB_INVALID_ADDRESS;
761 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
763 lldb_private::Status err;
765 std::unique_ptr<llvm::Module> llvm_module_ap(
766 m_code_generator->ReleaseModule());
768 if (!llvm_module_ap.get()) {
769 err.SetErrorToGenericError();
770 err.SetErrorString("IR doesn't contain a module");
774 ConstString function_name;
776 if (execution_policy != eExecutionPolicyTopLevel) {
777 // Find the actual name of the function (it's often mangled somehow)
779 if (!FindFunctionInModule(function_name, llvm_module_ap.get(),
780 m_expr.FunctionName())) {
781 err.SetErrorToGenericError();
782 err.SetErrorStringWithFormat("Couldn't find %s() in the module",
783 m_expr.FunctionName());
787 log->Printf("Found function %s for %s", function_name.AsCString(),
788 m_expr.FunctionName());
794 if (lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP()) {
795 sc = frame_sp->GetSymbolContext(lldb::eSymbolContextEverything);
796 } else if (lldb::TargetSP target_sp = exe_ctx.GetTargetSP()) {
797 sc.target_sp = target_sp;
800 LLVMUserExpression::IRPasses custom_passes;
802 auto lang = m_expr.Language();
804 log->Printf("%s - Current expression language is %s\n", __FUNCTION__,
805 Language::GetNameForLanguageType(lang));
806 lldb::ProcessSP process_sp = exe_ctx.GetProcessSP();
807 if (process_sp && lang != lldb::eLanguageTypeUnknown) {
808 auto runtime = process_sp->GetLanguageRuntime(lang);
810 runtime->GetIRPasses(custom_passes);
814 if (custom_passes.EarlyPasses) {
816 log->Printf("%s - Running Early IR Passes from LanguageRuntime on "
817 "expression module '%s'",
818 __FUNCTION__, m_expr.FunctionName());
820 custom_passes.EarlyPasses->run(*llvm_module_ap);
823 execution_unit_sp.reset(
824 new IRExecutionUnit(m_llvm_context, // handed off here
825 llvm_module_ap, // handed off here
826 function_name, exe_ctx.GetTargetSP(), sc,
827 m_compiler->getTargetOpts().Features));
829 ClangExpressionHelper *type_system_helper =
830 dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
831 ClangExpressionDeclMap *decl_map =
832 type_system_helper->DeclMap(); // result can be NULL
835 Stream *error_stream = NULL;
836 Target *target = exe_ctx.GetTargetPtr();
837 error_stream = target->GetDebugger().GetErrorFile().get();
839 IRForTarget ir_for_target(decl_map, m_expr.NeedsVariableResolution(),
840 *execution_unit_sp, *error_stream,
841 function_name.AsCString());
844 ir_for_target.runOnModule(*execution_unit_sp->GetModule());
848 "The expression could not be prepared to run in the target");
852 Process *process = exe_ctx.GetProcessPtr();
854 if (execution_policy != eExecutionPolicyAlways &&
855 execution_policy != eExecutionPolicyTopLevel) {
856 lldb_private::Status interpret_error;
858 bool interpret_function_calls =
859 !process ? false : process->CanInterpretFunctionCalls();
860 can_interpret = IRInterpreter::CanInterpret(
861 *execution_unit_sp->GetModule(), *execution_unit_sp->GetFunction(),
862 interpret_error, interpret_function_calls);
864 if (!can_interpret && execution_policy == eExecutionPolicyNever) {
865 err.SetErrorStringWithFormat("Can't run the expression locally: %s",
866 interpret_error.AsCString());
871 if (!process && execution_policy == eExecutionPolicyAlways) {
872 err.SetErrorString("Expression needed to run in the target, but the "
873 "target can't be run");
877 if (!process && execution_policy == eExecutionPolicyTopLevel) {
878 err.SetErrorString("Top-level code needs to be inserted into a runnable "
879 "target, but the target can't be run");
883 if (execution_policy == eExecutionPolicyAlways ||
884 (execution_policy != eExecutionPolicyTopLevel && !can_interpret)) {
885 if (m_expr.NeedsValidation() && process) {
886 if (!process->GetDynamicCheckers()) {
887 DynamicCheckerFunctions *dynamic_checkers =
888 new DynamicCheckerFunctions();
890 DiagnosticManager install_diagnostics;
892 if (!dynamic_checkers->Install(install_diagnostics, exe_ctx)) {
893 if (install_diagnostics.Diagnostics().size())
894 err.SetErrorString("couldn't install checkers, unknown error");
896 err.SetErrorString(install_diagnostics.GetString().c_str());
901 process->SetDynamicCheckers(dynamic_checkers);
904 log->Printf("== [ClangUserExpression::Evaluate] Finished "
905 "installing dynamic checkers ==");
908 IRDynamicChecks ir_dynamic_checks(*process->GetDynamicCheckers(),
909 function_name.AsCString());
911 llvm::Module *module = execution_unit_sp->GetModule();
912 if (!module || !ir_dynamic_checks.runOnModule(*module)) {
913 err.SetErrorToGenericError();
914 err.SetErrorString("Couldn't add dynamic checks to the expression");
918 if (custom_passes.LatePasses) {
920 log->Printf("%s - Running Late IR Passes from LanguageRuntime on "
921 "expression module '%s'",
922 __FUNCTION__, m_expr.FunctionName());
924 custom_passes.LatePasses->run(*module);
929 if (execution_policy == eExecutionPolicyAlways ||
930 execution_policy == eExecutionPolicyTopLevel || !can_interpret) {
931 execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);
934 execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);
940 lldb_private::Status ClangExpressionParser::RunStaticInitializers(
941 lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx) {
942 lldb_private::Status err;
944 lldbassert(execution_unit_sp.get());
945 lldbassert(exe_ctx.HasThreadScope());
947 if (!execution_unit_sp.get()) {
949 "can't run static initializers for a NULL execution unit");
953 if (!exe_ctx.HasThreadScope()) {
954 err.SetErrorString("can't run static initializers without a thread");
958 std::vector<lldb::addr_t> static_initializers;
960 execution_unit_sp->GetStaticInitializers(static_initializers);
962 for (lldb::addr_t static_initializer : static_initializers) {
963 EvaluateExpressionOptions options;
965 lldb::ThreadPlanSP call_static_initializer(new ThreadPlanCallFunction(
966 exe_ctx.GetThreadRef(), Address(static_initializer), CompilerType(),
967 llvm::ArrayRef<lldb::addr_t>(), options));
969 DiagnosticManager execution_errors;
970 lldb::ExpressionResults results =
971 exe_ctx.GetThreadRef().GetProcess()->RunThreadPlan(
972 exe_ctx, call_static_initializer, options, execution_errors);
974 if (results != lldb::eExpressionCompleted) {
975 err.SetErrorStringWithFormat("couldn't run static initializer: %s",
976 execution_errors.GetString().c_str());