Path: blob/main/contrib/llvm-project/lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp
39648 views
//===-- ClangExpressionParser.cpp -----------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "clang/AST/ASTContext.h"9#include "clang/AST/ASTDiagnostic.h"10#include "clang/AST/ExternalASTSource.h"11#include "clang/AST/PrettyPrinter.h"12#include "clang/Basic/Builtins.h"13#include "clang/Basic/DiagnosticIDs.h"14#include "clang/Basic/SourceLocation.h"15#include "clang/Basic/TargetInfo.h"16#include "clang/Basic/Version.h"17#include "clang/CodeGen/CodeGenAction.h"18#include "clang/CodeGen/ModuleBuilder.h"19#include "clang/Edit/Commit.h"20#include "clang/Edit/EditedSource.h"21#include "clang/Edit/EditsReceiver.h"22#include "clang/Frontend/CompilerInstance.h"23#include "clang/Frontend/CompilerInvocation.h"24#include "clang/Frontend/FrontendActions.h"25#include "clang/Frontend/FrontendDiagnostic.h"26#include "clang/Frontend/FrontendPluginRegistry.h"27#include "clang/Frontend/TextDiagnosticBuffer.h"28#include "clang/Frontend/TextDiagnosticPrinter.h"29#include "clang/Lex/Preprocessor.h"30#include "clang/Parse/ParseAST.h"31#include "clang/Rewrite/Core/Rewriter.h"32#include "clang/Rewrite/Frontend/FrontendActions.h"33#include "clang/Sema/CodeCompleteConsumer.h"34#include "clang/Sema/Sema.h"35#include "clang/Sema/SemaConsumer.h"3637#include "llvm/ADT/StringRef.h"38#include "llvm/ExecutionEngine/ExecutionEngine.h"39#include "llvm/Support/CrashRecoveryContext.h"40#include "llvm/Support/Debug.h"41#include "llvm/Support/FileSystem.h"42#include "llvm/Support/TargetSelect.h"4344#include "llvm/IR/LLVMContext.h"45#include "llvm/IR/Module.h"46#include "llvm/Support/DynamicLibrary.h"47#include "llvm/Support/ErrorHandling.h"48#include "llvm/Support/MemoryBuffer.h"49#include "llvm/Support/Signals.h"50#include "llvm/TargetParser/Host.h"5152#include "ClangDiagnostic.h"53#include "ClangExpressionParser.h"54#include "ClangUserExpression.h"5556#include "ASTUtils.h"57#include "ClangASTSource.h"58#include "ClangDiagnostic.h"59#include "ClangExpressionDeclMap.h"60#include "ClangExpressionHelper.h"61#include "ClangExpressionParser.h"62#include "ClangHost.h"63#include "ClangModulesDeclVendor.h"64#include "ClangPersistentVariables.h"65#include "IRDynamicChecks.h"66#include "IRForTarget.h"67#include "ModuleDependencyCollector.h"6869#include "Plugins/TypeSystem/Clang/TypeSystemClang.h"70#include "lldb/Core/Debugger.h"71#include "lldb/Core/Disassembler.h"72#include "lldb/Core/Module.h"73#include "lldb/Expression/IRExecutionUnit.h"74#include "lldb/Expression/IRInterpreter.h"75#include "lldb/Host/File.h"76#include "lldb/Host/HostInfo.h"77#include "lldb/Symbol/SymbolVendor.h"78#include "lldb/Target/ExecutionContext.h"79#include "lldb/Target/Language.h"80#include "lldb/Target/Process.h"81#include "lldb/Target/Target.h"82#include "lldb/Target/ThreadPlanCallFunction.h"83#include "lldb/Utility/DataBufferHeap.h"84#include "lldb/Utility/LLDBAssert.h"85#include "lldb/Utility/LLDBLog.h"86#include "lldb/Utility/Log.h"87#include "lldb/Utility/Stream.h"88#include "lldb/Utility/StreamString.h"89#include "lldb/Utility/StringList.h"9091#include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h"9293#include <cctype>94#include <memory>95#include <optional>9697using namespace clang;98using namespace llvm;99using namespace lldb_private;100101//===----------------------------------------------------------------------===//102// Utility Methods for Clang103//===----------------------------------------------------------------------===//104105class ClangExpressionParser::LLDBPreprocessorCallbacks : public PPCallbacks {106ClangModulesDeclVendor &m_decl_vendor;107ClangPersistentVariables &m_persistent_vars;108clang::SourceManager &m_source_mgr;109StreamString m_error_stream;110bool m_has_errors = false;111112public:113LLDBPreprocessorCallbacks(ClangModulesDeclVendor &decl_vendor,114ClangPersistentVariables &persistent_vars,115clang::SourceManager &source_mgr)116: m_decl_vendor(decl_vendor), m_persistent_vars(persistent_vars),117m_source_mgr(source_mgr) {}118119void moduleImport(SourceLocation import_location, clang::ModuleIdPath path,120const clang::Module * /*null*/) override {121// Ignore modules that are imported in the wrapper code as these are not122// loaded by the user.123llvm::StringRef filename =124m_source_mgr.getPresumedLoc(import_location).getFilename();125if (filename == ClangExpressionSourceCode::g_prefix_file_name)126return;127128SourceModule module;129130for (const std::pair<IdentifierInfo *, SourceLocation> &component : path)131module.path.push_back(ConstString(component.first->getName()));132133StreamString error_stream;134135ClangModulesDeclVendor::ModuleVector exported_modules;136if (!m_decl_vendor.AddModule(module, &exported_modules, m_error_stream))137m_has_errors = true;138139for (ClangModulesDeclVendor::ModuleID module : exported_modules)140m_persistent_vars.AddHandLoadedClangModule(module);141}142143bool hasErrors() { return m_has_errors; }144145llvm::StringRef getErrorString() { return m_error_stream.GetString(); }146};147148static void AddAllFixIts(ClangDiagnostic *diag, const clang::Diagnostic &Info) {149for (auto &fix_it : Info.getFixItHints()) {150if (fix_it.isNull())151continue;152diag->AddFixitHint(fix_it);153}154}155156class ClangDiagnosticManagerAdapter : public clang::DiagnosticConsumer {157public:158ClangDiagnosticManagerAdapter(DiagnosticOptions &opts) {159DiagnosticOptions *options = new DiagnosticOptions(opts);160options->ShowPresumedLoc = true;161options->ShowLevel = false;162m_os = std::make_shared<llvm::raw_string_ostream>(m_output);163m_passthrough =164std::make_shared<clang::TextDiagnosticPrinter>(*m_os, options);165}166167void ResetManager(DiagnosticManager *manager = nullptr) {168m_manager = manager;169}170171/// Returns the last ClangDiagnostic message that the DiagnosticManager172/// received or a nullptr if the DiagnosticMangager hasn't seen any173/// Clang diagnostics yet.174ClangDiagnostic *MaybeGetLastClangDiag() const {175if (m_manager->Diagnostics().empty())176return nullptr;177lldb_private::Diagnostic *diag = m_manager->Diagnostics().back().get();178ClangDiagnostic *clang_diag = dyn_cast<ClangDiagnostic>(diag);179return clang_diag;180}181182void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,183const clang::Diagnostic &Info) override {184if (!m_manager) {185// We have no DiagnosticManager before/after parsing but we still could186// receive diagnostics (e.g., by the ASTImporter failing to copy decls187// when we move the expression result ot the ScratchASTContext). Let's at188// least log these diagnostics until we find a way to properly render189// them and display them to the user.190Log *log = GetLog(LLDBLog::Expressions);191if (log) {192llvm::SmallVector<char, 32> diag_str;193Info.FormatDiagnostic(diag_str);194diag_str.push_back('\0');195const char *plain_diag = diag_str.data();196LLDB_LOG(log, "Received diagnostic outside parsing: {0}", plain_diag);197}198return;199}200201// Update error/warning counters.202DiagnosticConsumer::HandleDiagnostic(DiagLevel, Info);203204// Render diagnostic message to m_output.205m_output.clear();206m_passthrough->HandleDiagnostic(DiagLevel, Info);207m_os->flush();208209lldb::Severity severity;210bool make_new_diagnostic = true;211212switch (DiagLevel) {213case DiagnosticsEngine::Level::Fatal:214case DiagnosticsEngine::Level::Error:215severity = lldb::eSeverityError;216break;217case DiagnosticsEngine::Level::Warning:218severity = lldb::eSeverityWarning;219break;220case DiagnosticsEngine::Level::Remark:221case DiagnosticsEngine::Level::Ignored:222severity = lldb::eSeverityInfo;223break;224case DiagnosticsEngine::Level::Note:225m_manager->AppendMessageToDiagnostic(m_output);226make_new_diagnostic = false;227228// 'note:' diagnostics for errors and warnings can also contain Fix-Its.229// We add these Fix-Its to the last error diagnostic to make sure230// that we later have all Fix-Its related to an 'error' diagnostic when231// we apply them to the user expression.232auto *clang_diag = MaybeGetLastClangDiag();233// If we don't have a previous diagnostic there is nothing to do.234// If the previous diagnostic already has its own Fix-Its, assume that235// the 'note:' Fix-It is just an alternative way to solve the issue and236// ignore these Fix-Its.237if (!clang_diag || clang_diag->HasFixIts())238break;239// Ignore all Fix-Its that are not associated with an error.240if (clang_diag->GetSeverity() != lldb::eSeverityError)241break;242AddAllFixIts(clang_diag, Info);243break;244}245if (make_new_diagnostic) {246// ClangDiagnostic messages are expected to have no whitespace/newlines247// around them.248std::string stripped_output =249std::string(llvm::StringRef(m_output).trim());250251auto new_diagnostic = std::make_unique<ClangDiagnostic>(252stripped_output, severity, Info.getID());253254// Don't store away warning fixits, since the compiler doesn't have255// enough context in an expression for the warning to be useful.256// FIXME: Should we try to filter out FixIts that apply to our generated257// code, and not the user's expression?258if (severity == lldb::eSeverityError)259AddAllFixIts(new_diagnostic.get(), Info);260261m_manager->AddDiagnostic(std::move(new_diagnostic));262}263}264265void BeginSourceFile(const LangOptions &LO, const Preprocessor *PP) override {266m_passthrough->BeginSourceFile(LO, PP);267}268269void EndSourceFile() override { m_passthrough->EndSourceFile(); }270271private:272DiagnosticManager *m_manager = nullptr;273std::shared_ptr<clang::TextDiagnosticPrinter> m_passthrough;274/// Output stream of m_passthrough.275std::shared_ptr<llvm::raw_string_ostream> m_os;276/// Output string filled by m_os.277std::string m_output;278};279280static void SetupModuleHeaderPaths(CompilerInstance *compiler,281std::vector<std::string> include_directories,282lldb::TargetSP target_sp) {283Log *log = GetLog(LLDBLog::Expressions);284285HeaderSearchOptions &search_opts = compiler->getHeaderSearchOpts();286287for (const std::string &dir : include_directories) {288search_opts.AddPath(dir, frontend::System, false, true);289LLDB_LOG(log, "Added user include dir: {0}", dir);290}291292llvm::SmallString<128> module_cache;293const auto &props = ModuleList::GetGlobalModuleListProperties();294props.GetClangModulesCachePath().GetPath(module_cache);295search_opts.ModuleCachePath = std::string(module_cache.str());296LLDB_LOG(log, "Using module cache path: {0}", module_cache.c_str());297298search_opts.ResourceDir = GetClangResourceDir().GetPath();299300search_opts.ImplicitModuleMaps = true;301}302303/// Iff the given identifier is a C++ keyword, remove it from the304/// identifier table (i.e., make the token a normal identifier).305static void RemoveCppKeyword(IdentifierTable &idents, llvm::StringRef token) {306// FIXME: 'using' is used by LLDB for local variables, so we can't remove307// this keyword without breaking this functionality.308if (token == "using")309return;310// GCC's '__null' is used by LLDB to define NULL/Nil/nil.311if (token == "__null")312return;313314LangOptions cpp_lang_opts;315cpp_lang_opts.CPlusPlus = true;316cpp_lang_opts.CPlusPlus11 = true;317cpp_lang_opts.CPlusPlus20 = true;318319clang::IdentifierInfo &ii = idents.get(token);320// The identifier has to be a C++-exclusive keyword. if not, then there is321// nothing to do.322if (!ii.isCPlusPlusKeyword(cpp_lang_opts))323return;324// If the token is already an identifier, then there is nothing to do.325if (ii.getTokenID() == clang::tok::identifier)326return;327// Otherwise the token is a C++ keyword, so turn it back into a normal328// identifier.329ii.revertTokenIDToIdentifier();330}331332/// Remove all C++ keywords from the given identifier table.333static void RemoveAllCppKeywords(IdentifierTable &idents) {334#define KEYWORD(NAME, FLAGS) RemoveCppKeyword(idents, llvm::StringRef(#NAME));335#include "clang/Basic/TokenKinds.def"336}337338/// Configures Clang diagnostics for the expression parser.339static void SetupDefaultClangDiagnostics(CompilerInstance &compiler) {340// List of Clang warning groups that are not useful when parsing expressions.341const std::vector<const char *> groupsToIgnore = {342"unused-value",343"odr",344"unused-getter-return-value",345};346for (const char *group : groupsToIgnore) {347compiler.getDiagnostics().setSeverityForGroup(348clang::diag::Flavor::WarningOrError, group,349clang::diag::Severity::Ignored, SourceLocation());350}351}352353//===----------------------------------------------------------------------===//354// Implementation of ClangExpressionParser355//===----------------------------------------------------------------------===//356357ClangExpressionParser::ClangExpressionParser(358ExecutionContextScope *exe_scope, Expression &expr,359bool generate_debug_info, std::vector<std::string> include_directories,360std::string filename)361: ExpressionParser(exe_scope, expr, generate_debug_info), m_compiler(),362m_pp_callbacks(nullptr),363m_include_directories(std::move(include_directories)),364m_filename(std::move(filename)) {365Log *log = GetLog(LLDBLog::Expressions);366367// We can't compile expressions without a target. So if the exe_scope is368// null or doesn't have a target, then we just need to get out of here. I'll369// lldbassert and not make any of the compiler objects since370// I can't return errors directly from the constructor. Further calls will371// check if the compiler was made and372// bag out if it wasn't.373374if (!exe_scope) {375lldbassert(exe_scope &&376"Can't make an expression parser with a null scope.");377return;378}379380lldb::TargetSP target_sp;381target_sp = exe_scope->CalculateTarget();382if (!target_sp) {383lldbassert(target_sp.get() &&384"Can't make an expression parser with a null target.");385return;386}387388// 1. Create a new compiler instance.389m_compiler = std::make_unique<CompilerInstance>();390391// Make sure clang uses the same VFS as LLDB.392m_compiler->createFileManager(FileSystem::Instance().GetVirtualFileSystem());393394// Defaults to lldb::eLanguageTypeUnknown.395lldb::LanguageType frame_lang = expr.Language().AsLanguageType();396397std::string abi;398ArchSpec target_arch;399target_arch = target_sp->GetArchitecture();400401const auto target_machine = target_arch.GetMachine();402403// If the expression is being evaluated in the context of an existing stack404// frame, we introspect to see if the language runtime is available.405406lldb::StackFrameSP frame_sp = exe_scope->CalculateStackFrame();407lldb::ProcessSP process_sp = exe_scope->CalculateProcess();408409// Make sure the user hasn't provided a preferred execution language with410// `expression --language X -- ...`411if (frame_sp && frame_lang == lldb::eLanguageTypeUnknown)412frame_lang = frame_sp->GetLanguage().AsLanguageType();413414if (process_sp && frame_lang != lldb::eLanguageTypeUnknown) {415LLDB_LOGF(log, "Frame has language of type %s",416Language::GetNameForLanguageType(frame_lang));417}418419// 2. Configure the compiler with a set of default options that are420// appropriate for most situations.421if (target_arch.IsValid()) {422std::string triple = target_arch.GetTriple().str();423m_compiler->getTargetOpts().Triple = triple;424LLDB_LOGF(log, "Using %s as the target triple",425m_compiler->getTargetOpts().Triple.c_str());426} else {427// If we get here we don't have a valid target and just have to guess.428// Sometimes this will be ok to just use the host target triple (when we429// evaluate say "2+3", but other expressions like breakpoint conditions and430// other things that _are_ target specific really shouldn't just be using431// the host triple. In such a case the language runtime should expose an432// overridden options set (3), below.433m_compiler->getTargetOpts().Triple = llvm::sys::getDefaultTargetTriple();434LLDB_LOGF(log, "Using default target triple of %s",435m_compiler->getTargetOpts().Triple.c_str());436}437// Now add some special fixes for known architectures: Any arm32 iOS438// environment, but not on arm64439if (m_compiler->getTargetOpts().Triple.find("arm64") == std::string::npos &&440m_compiler->getTargetOpts().Triple.find("arm") != std::string::npos &&441m_compiler->getTargetOpts().Triple.find("ios") != std::string::npos) {442m_compiler->getTargetOpts().ABI = "apcs-gnu";443}444// Supported subsets of x86445if (target_machine == llvm::Triple::x86 ||446target_machine == llvm::Triple::x86_64) {447m_compiler->getTargetOpts().FeaturesAsWritten.push_back("+sse");448m_compiler->getTargetOpts().FeaturesAsWritten.push_back("+sse2");449}450451// Set the target CPU to generate code for. This will be empty for any CPU452// that doesn't really need to make a special453// CPU string.454m_compiler->getTargetOpts().CPU = target_arch.GetClangTargetCPU();455456// Set the target ABI457abi = GetClangTargetABI(target_arch);458if (!abi.empty())459m_compiler->getTargetOpts().ABI = abi;460461// 3. Create and install the target on the compiler.462m_compiler->createDiagnostics();463// Limit the number of error diagnostics we emit.464// A value of 0 means no limit for both LLDB and Clang.465m_compiler->getDiagnostics().setErrorLimit(target_sp->GetExprErrorLimit());466467auto target_info = TargetInfo::CreateTargetInfo(468m_compiler->getDiagnostics(), m_compiler->getInvocation().TargetOpts);469if (log) {470LLDB_LOGF(log, "Target datalayout string: '%s'",471target_info->getDataLayoutString());472LLDB_LOGF(log, "Target ABI: '%s'", target_info->getABI().str().c_str());473LLDB_LOGF(log, "Target vector alignment: %d",474target_info->getMaxVectorAlign());475}476m_compiler->setTarget(target_info);477478assert(m_compiler->hasTarget());479480// 4. Set language options.481lldb::LanguageType language = expr.Language().AsLanguageType();482LangOptions &lang_opts = m_compiler->getLangOpts();483484switch (language) {485case lldb::eLanguageTypeC:486case lldb::eLanguageTypeC89:487case lldb::eLanguageTypeC99:488case lldb::eLanguageTypeC11:489// FIXME: the following language option is a temporary workaround,490// to "ask for C, get C++."491// For now, the expression parser must use C++ anytime the language is a C492// family language, because the expression parser uses features of C++ to493// capture values.494lang_opts.CPlusPlus = true;495break;496case lldb::eLanguageTypeObjC:497lang_opts.ObjC = true;498// FIXME: the following language option is a temporary workaround,499// to "ask for ObjC, get ObjC++" (see comment above).500lang_opts.CPlusPlus = true;501502// Clang now sets as default C++14 as the default standard (with503// GNU extensions), so we do the same here to avoid mismatches that504// cause compiler error when evaluating expressions (e.g. nullptr not found505// as it's a C++11 feature). Currently lldb evaluates C++14 as C++11 (see506// two lines below) so we decide to be consistent with that, but this could507// be re-evaluated in the future.508lang_opts.CPlusPlus11 = true;509break;510case lldb::eLanguageTypeC_plus_plus_20:511lang_opts.CPlusPlus20 = true;512[[fallthrough]];513case lldb::eLanguageTypeC_plus_plus_17:514// FIXME: add a separate case for CPlusPlus14. Currently folded into C++17515// because C++14 is the default standard for Clang but enabling CPlusPlus14516// expression evaluatino doesn't pass the test-suite cleanly.517lang_opts.CPlusPlus14 = true;518lang_opts.CPlusPlus17 = true;519[[fallthrough]];520case lldb::eLanguageTypeC_plus_plus:521case lldb::eLanguageTypeC_plus_plus_11:522case lldb::eLanguageTypeC_plus_plus_14:523lang_opts.CPlusPlus11 = true;524m_compiler->getHeaderSearchOpts().UseLibcxx = true;525[[fallthrough]];526case lldb::eLanguageTypeC_plus_plus_03:527lang_opts.CPlusPlus = true;528if (process_sp529// We're stopped in a frame without debug-info. The user probably530// intends to make global queries (which should include Objective-C).531&& !(frame_sp && frame_sp->HasDebugInformation()))532lang_opts.ObjC =533process_sp->GetLanguageRuntime(lldb::eLanguageTypeObjC) != nullptr;534break;535case lldb::eLanguageTypeObjC_plus_plus:536case lldb::eLanguageTypeUnknown:537default:538lang_opts.ObjC = true;539lang_opts.CPlusPlus = true;540lang_opts.CPlusPlus11 = true;541m_compiler->getHeaderSearchOpts().UseLibcxx = true;542break;543}544545lang_opts.Bool = true;546lang_opts.WChar = true;547lang_opts.Blocks = true;548lang_opts.DebuggerSupport =549true; // Features specifically for debugger clients550if (expr.DesiredResultType() == Expression::eResultTypeId)551lang_opts.DebuggerCastResultToId = true;552553lang_opts.CharIsSigned = ArchSpec(m_compiler->getTargetOpts().Triple.c_str())554.CharIsSignedByDefault();555556// Spell checking is a nice feature, but it ends up completing a lot of types557// that we didn't strictly speaking need to complete. As a result, we spend a558// long time parsing and importing debug information.559lang_opts.SpellChecking = false;560561auto *clang_expr = dyn_cast<ClangUserExpression>(&m_expr);562if (clang_expr && clang_expr->DidImportCxxModules()) {563LLDB_LOG(log, "Adding lang options for importing C++ modules");564565lang_opts.Modules = true;566// We want to implicitly build modules.567lang_opts.ImplicitModules = true;568// To automatically import all submodules when we import 'std'.569lang_opts.ModulesLocalVisibility = false;570571// We use the @import statements, so we need this:572// FIXME: We could use the modules-ts, but that currently doesn't work.573lang_opts.ObjC = true;574575// Options we need to parse libc++ code successfully.576// FIXME: We should ask the driver for the appropriate default flags.577lang_opts.GNUMode = true;578lang_opts.GNUKeywords = true;579lang_opts.CPlusPlus11 = true;580lang_opts.BuiltinHeadersInSystemModules = true;581582// The Darwin libc expects this macro to be set.583lang_opts.GNUCVersion = 40201;584585SetupModuleHeaderPaths(m_compiler.get(), m_include_directories,586target_sp);587}588589if (process_sp && lang_opts.ObjC) {590if (auto *runtime = ObjCLanguageRuntime::Get(*process_sp)) {591switch (runtime->GetRuntimeVersion()) {592case ObjCLanguageRuntime::ObjCRuntimeVersions::eAppleObjC_V2:593lang_opts.ObjCRuntime.set(ObjCRuntime::MacOSX, VersionTuple(10, 7));594break;595case ObjCLanguageRuntime::ObjCRuntimeVersions::eObjC_VersionUnknown:596case ObjCLanguageRuntime::ObjCRuntimeVersions::eAppleObjC_V1:597lang_opts.ObjCRuntime.set(ObjCRuntime::FragileMacOSX,598VersionTuple(10, 7));599break;600case ObjCLanguageRuntime::ObjCRuntimeVersions::eGNUstep_libobjc2:601lang_opts.ObjCRuntime.set(ObjCRuntime::GNUstep, VersionTuple(2, 0));602break;603}604605if (runtime->HasNewLiteralsAndIndexing())606lang_opts.DebuggerObjCLiteral = true;607}608}609610lang_opts.ThreadsafeStatics = false;611lang_opts.AccessControl = false; // Debuggers get universal access612lang_opts.DollarIdents = true; // $ indicates a persistent variable name613// We enable all builtin functions beside the builtins from libc/libm (e.g.614// 'fopen'). Those libc functions are already correctly handled by LLDB, and615// additionally enabling them as expandable builtins is breaking Clang.616lang_opts.NoBuiltin = true;617618// Set CodeGen options619m_compiler->getCodeGenOpts().EmitDeclMetadata = true;620m_compiler->getCodeGenOpts().InstrumentFunctions = false;621m_compiler->getCodeGenOpts().setFramePointer(622CodeGenOptions::FramePointerKind::All);623if (generate_debug_info)624m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::FullDebugInfo);625else626m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::NoDebugInfo);627628// Disable some warnings.629SetupDefaultClangDiagnostics(*m_compiler);630631// Inform the target of the language options632//633// FIXME: We shouldn't need to do this, the target should be immutable once634// created. This complexity should be lifted elsewhere.635m_compiler->getTarget().adjust(m_compiler->getDiagnostics(),636m_compiler->getLangOpts());637638// 5. Set up the diagnostic buffer for reporting errors639640auto diag_mgr = new ClangDiagnosticManagerAdapter(641m_compiler->getDiagnostics().getDiagnosticOptions());642m_compiler->getDiagnostics().setClient(diag_mgr);643644// 6. Set up the source management objects inside the compiler645m_compiler->createFileManager();646if (!m_compiler->hasSourceManager())647m_compiler->createSourceManager(m_compiler->getFileManager());648m_compiler->createPreprocessor(TU_Complete);649650switch (language) {651case lldb::eLanguageTypeC:652case lldb::eLanguageTypeC89:653case lldb::eLanguageTypeC99:654case lldb::eLanguageTypeC11:655case lldb::eLanguageTypeObjC:656// This is not a C++ expression but we enabled C++ as explained above.657// Remove all C++ keywords from the PP so that the user can still use658// variables that have C++ keywords as names (e.g. 'int template;').659RemoveAllCppKeywords(m_compiler->getPreprocessor().getIdentifierTable());660break;661default:662break;663}664665if (auto *clang_persistent_vars = llvm::cast<ClangPersistentVariables>(666target_sp->GetPersistentExpressionStateForLanguage(667lldb::eLanguageTypeC))) {668if (std::shared_ptr<ClangModulesDeclVendor> decl_vendor =669clang_persistent_vars->GetClangModulesDeclVendor()) {670std::unique_ptr<PPCallbacks> pp_callbacks(671new LLDBPreprocessorCallbacks(*decl_vendor, *clang_persistent_vars,672m_compiler->getSourceManager()));673m_pp_callbacks =674static_cast<LLDBPreprocessorCallbacks *>(pp_callbacks.get());675m_compiler->getPreprocessor().addPPCallbacks(std::move(pp_callbacks));676}677}678679// 7. Most of this we get from the CompilerInstance, but we also want to give680// the context an ExternalASTSource.681682auto &PP = m_compiler->getPreprocessor();683auto &builtin_context = PP.getBuiltinInfo();684builtin_context.initializeBuiltins(PP.getIdentifierTable(),685m_compiler->getLangOpts());686687m_compiler->createASTContext();688clang::ASTContext &ast_context = m_compiler->getASTContext();689690m_ast_context = std::make_shared<TypeSystemClang>(691"Expression ASTContext for '" + m_filename + "'", ast_context);692693std::string module_name("$__lldb_module");694695m_llvm_context = std::make_unique<LLVMContext>();696m_code_generator.reset(CreateLLVMCodeGen(697m_compiler->getDiagnostics(), module_name,698&m_compiler->getVirtualFileSystem(), m_compiler->getHeaderSearchOpts(),699m_compiler->getPreprocessorOpts(), m_compiler->getCodeGenOpts(),700*m_llvm_context));701}702703ClangExpressionParser::~ClangExpressionParser() = default;704705namespace {706707/// \class CodeComplete708///709/// A code completion consumer for the clang Sema that is responsible for710/// creating the completion suggestions when a user requests completion711/// of an incomplete `expr` invocation.712class CodeComplete : public CodeCompleteConsumer {713CodeCompletionTUInfo m_info;714715std::string m_expr;716unsigned m_position = 0;717/// The printing policy we use when printing declarations for our completion718/// descriptions.719clang::PrintingPolicy m_desc_policy;720721struct CompletionWithPriority {722CompletionResult::Completion completion;723/// See CodeCompletionResult::Priority;724unsigned Priority;725726/// Establishes a deterministic order in a list of CompletionWithPriority.727/// The order returned here is the order in which the completions are728/// displayed to the user.729bool operator<(const CompletionWithPriority &o) const {730// High priority results should come first.731if (Priority != o.Priority)732return Priority > o.Priority;733734// Identical priority, so just make sure it's a deterministic order.735return completion.GetUniqueKey() < o.completion.GetUniqueKey();736}737};738739/// The stored completions.740/// Warning: These are in a non-deterministic order until they are sorted741/// and returned back to the caller.742std::vector<CompletionWithPriority> m_completions;743744/// Returns true if the given character can be used in an identifier.745/// This also returns true for numbers because for completion we usually746/// just iterate backwards over iterators.747///748/// Note: lldb uses '$' in its internal identifiers, so we also allow this.749static bool IsIdChar(char c) {750return c == '_' || std::isalnum(c) || c == '$';751}752753/// Returns true if the given character is used to separate arguments754/// in the command line of lldb.755static bool IsTokenSeparator(char c) { return c == ' ' || c == '\t'; }756757/// Drops all tokens in front of the expression that are unrelated for758/// the completion of the cmd line. 'unrelated' means here that the token759/// is not interested for the lldb completion API result.760StringRef dropUnrelatedFrontTokens(StringRef cmd) const {761if (cmd.empty())762return cmd;763764// If we are at the start of a word, then all tokens are unrelated to765// the current completion logic.766if (IsTokenSeparator(cmd.back()))767return StringRef();768769// Remove all previous tokens from the string as they are unrelated770// to completing the current token.771StringRef to_remove = cmd;772while (!to_remove.empty() && !IsTokenSeparator(to_remove.back())) {773to_remove = to_remove.drop_back();774}775cmd = cmd.drop_front(to_remove.size());776777return cmd;778}779780/// Removes the last identifier token from the given cmd line.781StringRef removeLastToken(StringRef cmd) const {782while (!cmd.empty() && IsIdChar(cmd.back())) {783cmd = cmd.drop_back();784}785return cmd;786}787788/// Attempts to merge the given completion from the given position into the789/// existing command. Returns the completion string that can be returned to790/// the lldb completion API.791std::string mergeCompletion(StringRef existing, unsigned pos,792StringRef completion) const {793StringRef existing_command = existing.substr(0, pos);794// We rewrite the last token with the completion, so let's drop that795// token from the command.796existing_command = removeLastToken(existing_command);797// We also should remove all previous tokens from the command as they798// would otherwise be added to the completion that already has the799// completion.800existing_command = dropUnrelatedFrontTokens(existing_command);801return existing_command.str() + completion.str();802}803804public:805/// Constructs a CodeComplete consumer that can be attached to a Sema.806///807/// \param[out] expr808/// The whole expression string that we are currently parsing. This809/// string needs to be equal to the input the user typed, and NOT the810/// final code that Clang is parsing.811/// \param[out] position812/// The character position of the user cursor in the `expr` parameter.813///814CodeComplete(clang::LangOptions ops, std::string expr, unsigned position)815: CodeCompleteConsumer(CodeCompleteOptions()),816m_info(std::make_shared<GlobalCodeCompletionAllocator>()), m_expr(expr),817m_position(position), m_desc_policy(ops) {818819// Ensure that the printing policy is producing a description that is as820// short as possible.821m_desc_policy.SuppressScope = true;822m_desc_policy.SuppressTagKeyword = true;823m_desc_policy.FullyQualifiedName = false;824m_desc_policy.TerseOutput = true;825m_desc_policy.IncludeNewlines = false;826m_desc_policy.UseVoidForZeroParams = false;827m_desc_policy.Bool = true;828}829830/// \name Code-completion filtering831/// Check if the result should be filtered out.832bool isResultFilteredOut(StringRef Filter,833CodeCompletionResult Result) override {834// This code is mostly copied from CodeCompleteConsumer.835switch (Result.Kind) {836case CodeCompletionResult::RK_Declaration:837return !(838Result.Declaration->getIdentifier() &&839Result.Declaration->getIdentifier()->getName().starts_with(Filter));840case CodeCompletionResult::RK_Keyword:841return !StringRef(Result.Keyword).starts_with(Filter);842case CodeCompletionResult::RK_Macro:843return !Result.Macro->getName().starts_with(Filter);844case CodeCompletionResult::RK_Pattern:845return !StringRef(Result.Pattern->getAsString()).starts_with(Filter);846}847// If we trigger this assert or the above switch yields a warning, then848// CodeCompletionResult has been enhanced with more kinds of completion849// results. Expand the switch above in this case.850assert(false && "Unknown completion result type?");851// If we reach this, then we should just ignore whatever kind of unknown852// result we got back. We probably can't turn it into any kind of useful853// completion suggestion with the existing code.854return true;855}856857private:858/// Generate the completion strings for the given CodeCompletionResult.859/// Note that this function has to process results that could come in860/// non-deterministic order, so this function should have no side effects.861/// To make this easier to enforce, this function and all its parameters862/// should always be const-qualified.863/// \return Returns std::nullopt if no completion should be provided for the864/// given CodeCompletionResult.865std::optional<CompletionWithPriority>866getCompletionForResult(const CodeCompletionResult &R) const {867std::string ToInsert;868std::string Description;869// Handle the different completion kinds that come from the Sema.870switch (R.Kind) {871case CodeCompletionResult::RK_Declaration: {872const NamedDecl *D = R.Declaration;873ToInsert = R.Declaration->getNameAsString();874// If we have a function decl that has no arguments we want to875// complete the empty parantheses for the user. If the function has876// arguments, we at least complete the opening bracket.877if (const FunctionDecl *F = dyn_cast<FunctionDecl>(D)) {878if (F->getNumParams() == 0)879ToInsert += "()";880else881ToInsert += "(";882raw_string_ostream OS(Description);883F->print(OS, m_desc_policy, false);884OS.flush();885} else if (const VarDecl *V = dyn_cast<VarDecl>(D)) {886Description = V->getType().getAsString(m_desc_policy);887} else if (const FieldDecl *F = dyn_cast<FieldDecl>(D)) {888Description = F->getType().getAsString(m_desc_policy);889} else if (const NamespaceDecl *N = dyn_cast<NamespaceDecl>(D)) {890// If we try to complete a namespace, then we can directly append891// the '::'.892if (!N->isAnonymousNamespace())893ToInsert += "::";894}895break;896}897case CodeCompletionResult::RK_Keyword:898ToInsert = R.Keyword;899break;900case CodeCompletionResult::RK_Macro:901ToInsert = R.Macro->getName().str();902break;903case CodeCompletionResult::RK_Pattern:904ToInsert = R.Pattern->getTypedText();905break;906}907// We also filter some internal lldb identifiers here. The user908// shouldn't see these.909if (llvm::StringRef(ToInsert).starts_with("$__lldb_"))910return std::nullopt;911if (ToInsert.empty())912return std::nullopt;913// Merge the suggested Token into the existing command line to comply914// with the kind of result the lldb API expects.915std::string CompletionSuggestion =916mergeCompletion(m_expr, m_position, ToInsert);917918CompletionResult::Completion completion(CompletionSuggestion, Description,919CompletionMode::Normal);920return {{completion, R.Priority}};921}922923public:924/// Adds the completions to the given CompletionRequest.925void GetCompletions(CompletionRequest &request) {926// Bring m_completions into a deterministic order and pass it on to the927// CompletionRequest.928llvm::sort(m_completions);929930for (const CompletionWithPriority &C : m_completions)931request.AddCompletion(C.completion.GetCompletion(),932C.completion.GetDescription(),933C.completion.GetMode());934}935936/// \name Code-completion callbacks937/// Process the finalized code-completion results.938void ProcessCodeCompleteResults(Sema &SemaRef, CodeCompletionContext Context,939CodeCompletionResult *Results,940unsigned NumResults) override {941942// The Sema put the incomplete token we try to complete in here during943// lexing, so we need to retrieve it here to know what we are completing.944StringRef Filter = SemaRef.getPreprocessor().getCodeCompletionFilter();945946// Iterate over all the results. Filter out results we don't want and947// process the rest.948for (unsigned I = 0; I != NumResults; ++I) {949// Filter the results with the information from the Sema.950if (!Filter.empty() && isResultFilteredOut(Filter, Results[I]))951continue;952953CodeCompletionResult &R = Results[I];954std::optional<CompletionWithPriority> CompletionAndPriority =955getCompletionForResult(R);956if (!CompletionAndPriority)957continue;958m_completions.push_back(*CompletionAndPriority);959}960}961962/// \param S the semantic-analyzer object for which code-completion is being963/// done.964///965/// \param CurrentArg the index of the current argument.966///967/// \param Candidates an array of overload candidates.968///969/// \param NumCandidates the number of overload candidates970void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,971OverloadCandidate *Candidates,972unsigned NumCandidates,973SourceLocation OpenParLoc,974bool Braced) override {975// At the moment we don't filter out any overloaded candidates.976}977978CodeCompletionAllocator &getAllocator() override {979return m_info.getAllocator();980}981982CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return m_info; }983};984} // namespace985986bool ClangExpressionParser::Complete(CompletionRequest &request, unsigned line,987unsigned pos, unsigned typed_pos) {988DiagnosticManager mgr;989// We need the raw user expression here because that's what the CodeComplete990// class uses to provide completion suggestions.991// However, the `Text` method only gives us the transformed expression here.992// To actually get the raw user input here, we have to cast our expression to993// the LLVMUserExpression which exposes the right API. This should never fail994// as we always have a ClangUserExpression whenever we call this.995ClangUserExpression *llvm_expr = cast<ClangUserExpression>(&m_expr);996CodeComplete CC(m_compiler->getLangOpts(), llvm_expr->GetUserText(),997typed_pos);998// We don't need a code generator for parsing.999m_code_generator.reset();1000// Start parsing the expression with our custom code completion consumer.1001ParseInternal(mgr, &CC, line, pos);1002CC.GetCompletions(request);1003return true;1004}10051006unsigned ClangExpressionParser::Parse(DiagnosticManager &diagnostic_manager) {1007return ParseInternal(diagnostic_manager);1008}10091010unsigned1011ClangExpressionParser::ParseInternal(DiagnosticManager &diagnostic_manager,1012CodeCompleteConsumer *completion_consumer,1013unsigned completion_line,1014unsigned completion_column) {1015ClangDiagnosticManagerAdapter *adapter =1016static_cast<ClangDiagnosticManagerAdapter *>(1017m_compiler->getDiagnostics().getClient());10181019adapter->ResetManager(&diagnostic_manager);10201021const char *expr_text = m_expr.Text();10221023clang::SourceManager &source_mgr = m_compiler->getSourceManager();1024bool created_main_file = false;10251026// Clang wants to do completion on a real file known by Clang's file manager,1027// so we have to create one to make this work.1028// TODO: We probably could also simulate to Clang's file manager that there1029// is a real file that contains our code.1030bool should_create_file = completion_consumer != nullptr;10311032// We also want a real file on disk if we generate full debug info.1033should_create_file |= m_compiler->getCodeGenOpts().getDebugInfo() ==1034codegenoptions::FullDebugInfo;10351036if (should_create_file) {1037int temp_fd = -1;1038llvm::SmallString<128> result_path;1039if (FileSpec tmpdir_file_spec = HostInfo::GetProcessTempDir()) {1040tmpdir_file_spec.AppendPathComponent("lldb-%%%%%%.expr");1041std::string temp_source_path = tmpdir_file_spec.GetPath();1042llvm::sys::fs::createUniqueFile(temp_source_path, temp_fd, result_path);1043} else {1044llvm::sys::fs::createTemporaryFile("lldb", "expr", temp_fd, result_path);1045}10461047if (temp_fd != -1) {1048lldb_private::NativeFile file(temp_fd, File::eOpenOptionWriteOnly, true);1049const size_t expr_text_len = strlen(expr_text);1050size_t bytes_written = expr_text_len;1051if (file.Write(expr_text, bytes_written).Success()) {1052if (bytes_written == expr_text_len) {1053file.Close();1054if (auto fileEntry = m_compiler->getFileManager().getOptionalFileRef(1055result_path)) {1056source_mgr.setMainFileID(source_mgr.createFileID(1057*fileEntry,1058SourceLocation(), SrcMgr::C_User));1059created_main_file = true;1060}1061}1062}1063}1064}10651066if (!created_main_file) {1067std::unique_ptr<MemoryBuffer> memory_buffer =1068MemoryBuffer::getMemBufferCopy(expr_text, m_filename);1069source_mgr.setMainFileID(source_mgr.createFileID(std::move(memory_buffer)));1070}10711072adapter->BeginSourceFile(m_compiler->getLangOpts(),1073&m_compiler->getPreprocessor());10741075ClangExpressionHelper *type_system_helper =1076dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());10771078// If we want to parse for code completion, we need to attach our code1079// completion consumer to the Sema and specify a completion position.1080// While parsing the Sema will call this consumer with the provided1081// completion suggestions.1082if (completion_consumer) {1083auto main_file =1084source_mgr.getFileEntryRefForID(source_mgr.getMainFileID());1085auto &PP = m_compiler->getPreprocessor();1086// Lines and columns start at 1 in Clang, but code completion positions are1087// indexed from 0, so we need to add 1 to the line and column here.1088++completion_line;1089++completion_column;1090PP.SetCodeCompletionPoint(*main_file, completion_line, completion_column);1091}10921093ASTConsumer *ast_transformer =1094type_system_helper->ASTTransformer(m_code_generator.get());10951096std::unique_ptr<clang::ASTConsumer> Consumer;1097if (ast_transformer) {1098Consumer = std::make_unique<ASTConsumerForwarder>(ast_transformer);1099} else if (m_code_generator) {1100Consumer = std::make_unique<ASTConsumerForwarder>(m_code_generator.get());1101} else {1102Consumer = std::make_unique<ASTConsumer>();1103}11041105clang::ASTContext &ast_context = m_compiler->getASTContext();11061107m_compiler->setSema(new Sema(m_compiler->getPreprocessor(), ast_context,1108*Consumer, TU_Complete, completion_consumer));1109m_compiler->setASTConsumer(std::move(Consumer));11101111if (ast_context.getLangOpts().Modules) {1112m_compiler->createASTReader();1113m_ast_context->setSema(&m_compiler->getSema());1114}11151116ClangExpressionDeclMap *decl_map = type_system_helper->DeclMap();1117if (decl_map) {1118decl_map->InstallCodeGenerator(&m_compiler->getASTConsumer());1119decl_map->InstallDiagnosticManager(diagnostic_manager);11201121clang::ExternalASTSource *ast_source = decl_map->CreateProxy();11221123if (ast_context.getExternalSource()) {1124auto module_wrapper =1125new ExternalASTSourceWrapper(ast_context.getExternalSource());11261127auto ast_source_wrapper = new ExternalASTSourceWrapper(ast_source);11281129auto multiplexer =1130new SemaSourceWithPriorities(*module_wrapper, *ast_source_wrapper);1131IntrusiveRefCntPtr<ExternalASTSource> Source(multiplexer);1132ast_context.setExternalSource(Source);1133} else {1134ast_context.setExternalSource(ast_source);1135}1136decl_map->InstallASTContext(*m_ast_context);1137}11381139// Check that the ASTReader is properly attached to ASTContext and Sema.1140if (ast_context.getLangOpts().Modules) {1141assert(m_compiler->getASTContext().getExternalSource() &&1142"ASTContext doesn't know about the ASTReader?");1143assert(m_compiler->getSema().getExternalSource() &&1144"Sema doesn't know about the ASTReader?");1145}11461147{1148llvm::CrashRecoveryContextCleanupRegistrar<Sema> CleanupSema(1149&m_compiler->getSema());1150ParseAST(m_compiler->getSema(), false, false);1151}11521153// Make sure we have no pointer to the Sema we are about to destroy.1154if (ast_context.getLangOpts().Modules)1155m_ast_context->setSema(nullptr);1156// Destroy the Sema. This is necessary because we want to emulate the1157// original behavior of ParseAST (which also destroys the Sema after parsing).1158m_compiler->setSema(nullptr);11591160adapter->EndSourceFile();11611162unsigned num_errors = adapter->getNumErrors();11631164if (m_pp_callbacks && m_pp_callbacks->hasErrors()) {1165num_errors++;1166diagnostic_manager.PutString(lldb::eSeverityError,1167"while importing modules:");1168diagnostic_manager.AppendMessageToDiagnostic(1169m_pp_callbacks->getErrorString());1170}11711172if (!num_errors) {1173type_system_helper->CommitPersistentDecls();1174}11751176adapter->ResetManager();11771178return num_errors;1179}11801181std::string1182ClangExpressionParser::GetClangTargetABI(const ArchSpec &target_arch) {1183std::string abi;11841185if (target_arch.IsMIPS()) {1186switch (target_arch.GetFlags() & ArchSpec::eMIPSABI_mask) {1187case ArchSpec::eMIPSABI_N64:1188abi = "n64";1189break;1190case ArchSpec::eMIPSABI_N32:1191abi = "n32";1192break;1193case ArchSpec::eMIPSABI_O32:1194abi = "o32";1195break;1196default:1197break;1198}1199}1200return abi;1201}12021203/// Applies the given Fix-It hint to the given commit.1204static void ApplyFixIt(const FixItHint &fixit, clang::edit::Commit &commit) {1205// This is cobbed from clang::Rewrite::FixItRewriter.1206if (fixit.CodeToInsert.empty()) {1207if (fixit.InsertFromRange.isValid()) {1208commit.insertFromRange(fixit.RemoveRange.getBegin(),1209fixit.InsertFromRange, /*afterToken=*/false,1210fixit.BeforePreviousInsertions);1211return;1212}1213commit.remove(fixit.RemoveRange);1214return;1215}1216if (fixit.RemoveRange.isTokenRange() ||1217fixit.RemoveRange.getBegin() != fixit.RemoveRange.getEnd()) {1218commit.replace(fixit.RemoveRange, fixit.CodeToInsert);1219return;1220}1221commit.insert(fixit.RemoveRange.getBegin(), fixit.CodeToInsert,1222/*afterToken=*/false, fixit.BeforePreviousInsertions);1223}12241225bool ClangExpressionParser::RewriteExpression(1226DiagnosticManager &diagnostic_manager) {1227clang::SourceManager &source_manager = m_compiler->getSourceManager();1228clang::edit::EditedSource editor(source_manager, m_compiler->getLangOpts(),1229nullptr);1230clang::edit::Commit commit(editor);1231clang::Rewriter rewriter(source_manager, m_compiler->getLangOpts());12321233class RewritesReceiver : public edit::EditsReceiver {1234Rewriter &rewrite;12351236public:1237RewritesReceiver(Rewriter &in_rewrite) : rewrite(in_rewrite) {}12381239void insert(SourceLocation loc, StringRef text) override {1240rewrite.InsertText(loc, text);1241}1242void replace(CharSourceRange range, StringRef text) override {1243rewrite.ReplaceText(range.getBegin(), rewrite.getRangeSize(range), text);1244}1245};12461247RewritesReceiver rewrites_receiver(rewriter);12481249const DiagnosticList &diagnostics = diagnostic_manager.Diagnostics();1250size_t num_diags = diagnostics.size();1251if (num_diags == 0)1252return false;12531254for (const auto &diag : diagnostic_manager.Diagnostics()) {1255const auto *diagnostic = llvm::dyn_cast<ClangDiagnostic>(diag.get());1256if (!diagnostic)1257continue;1258if (!diagnostic->HasFixIts())1259continue;1260for (const FixItHint &fixit : diagnostic->FixIts())1261ApplyFixIt(fixit, commit);1262}12631264// FIXME - do we want to try to propagate specific errors here?1265if (!commit.isCommitable())1266return false;1267else if (!editor.commit(commit))1268return false;12691270// Now play all the edits, and stash the result in the diagnostic manager.1271editor.applyRewrites(rewrites_receiver);1272RewriteBuffer &main_file_buffer =1273rewriter.getEditBuffer(source_manager.getMainFileID());12741275std::string fixed_expression;1276llvm::raw_string_ostream out_stream(fixed_expression);12771278main_file_buffer.write(out_stream);1279out_stream.flush();1280diagnostic_manager.SetFixedExpression(fixed_expression);12811282return true;1283}12841285static bool FindFunctionInModule(ConstString &mangled_name,1286llvm::Module *module, const char *orig_name) {1287for (const auto &func : module->getFunctionList()) {1288const StringRef &name = func.getName();1289if (name.contains(orig_name)) {1290mangled_name.SetString(name);1291return true;1292}1293}12941295return false;1296}12971298lldb_private::Status ClangExpressionParser::DoPrepareForExecution(1299lldb::addr_t &func_addr, lldb::addr_t &func_end,1300lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx,1301bool &can_interpret, ExecutionPolicy execution_policy) {1302func_addr = LLDB_INVALID_ADDRESS;1303func_end = LLDB_INVALID_ADDRESS;1304Log *log = GetLog(LLDBLog::Expressions);13051306lldb_private::Status err;13071308std::unique_ptr<llvm::Module> llvm_module_up(1309m_code_generator->ReleaseModule());13101311if (!llvm_module_up) {1312err.SetErrorToGenericError();1313err.SetErrorString("IR doesn't contain a module");1314return err;1315}13161317ConstString function_name;13181319if (execution_policy != eExecutionPolicyTopLevel) {1320// Find the actual name of the function (it's often mangled somehow)13211322if (!FindFunctionInModule(function_name, llvm_module_up.get(),1323m_expr.FunctionName())) {1324err.SetErrorToGenericError();1325err.SetErrorStringWithFormat("Couldn't find %s() in the module",1326m_expr.FunctionName());1327return err;1328} else {1329LLDB_LOGF(log, "Found function %s for %s", function_name.AsCString(),1330m_expr.FunctionName());1331}1332}13331334SymbolContext sc;13351336if (lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP()) {1337sc = frame_sp->GetSymbolContext(lldb::eSymbolContextEverything);1338} else if (lldb::TargetSP target_sp = exe_ctx.GetTargetSP()) {1339sc.target_sp = target_sp;1340}13411342LLVMUserExpression::IRPasses custom_passes;1343{1344auto lang = m_expr.Language();1345LLDB_LOGF(log, "%s - Current expression language is %s\n", __FUNCTION__,1346lang.GetDescription().data());1347lldb::ProcessSP process_sp = exe_ctx.GetProcessSP();1348if (process_sp && lang != lldb::eLanguageTypeUnknown) {1349auto runtime = process_sp->GetLanguageRuntime(lang.AsLanguageType());1350if (runtime)1351runtime->GetIRPasses(custom_passes);1352}1353}13541355if (custom_passes.EarlyPasses) {1356LLDB_LOGF(log,1357"%s - Running Early IR Passes from LanguageRuntime on "1358"expression module '%s'",1359__FUNCTION__, m_expr.FunctionName());13601361custom_passes.EarlyPasses->run(*llvm_module_up);1362}13631364execution_unit_sp = std::make_shared<IRExecutionUnit>(1365m_llvm_context, // handed off here1366llvm_module_up, // handed off here1367function_name, exe_ctx.GetTargetSP(), sc,1368m_compiler->getTargetOpts().Features);13691370ClangExpressionHelper *type_system_helper =1371dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());1372ClangExpressionDeclMap *decl_map =1373type_system_helper->DeclMap(); // result can be NULL13741375if (decl_map) {1376StreamString error_stream;1377IRForTarget ir_for_target(decl_map, m_expr.NeedsVariableResolution(),1378*execution_unit_sp, error_stream,1379function_name.AsCString());13801381if (!ir_for_target.runOnModule(*execution_unit_sp->GetModule())) {1382err.SetErrorString(error_stream.GetString());1383return err;1384}13851386Process *process = exe_ctx.GetProcessPtr();13871388if (execution_policy != eExecutionPolicyAlways &&1389execution_policy != eExecutionPolicyTopLevel) {1390lldb_private::Status interpret_error;13911392bool interpret_function_calls =1393!process ? false : process->CanInterpretFunctionCalls();1394can_interpret = IRInterpreter::CanInterpret(1395*execution_unit_sp->GetModule(), *execution_unit_sp->GetFunction(),1396interpret_error, interpret_function_calls);13971398if (!can_interpret && execution_policy == eExecutionPolicyNever) {1399err.SetErrorStringWithFormat(1400"Can't evaluate the expression without a running target due to: %s",1401interpret_error.AsCString());1402return err;1403}1404}14051406if (!process && execution_policy == eExecutionPolicyAlways) {1407err.SetErrorString("Expression needed to run in the target, but the "1408"target can't be run");1409return err;1410}14111412if (!process && execution_policy == eExecutionPolicyTopLevel) {1413err.SetErrorString("Top-level code needs to be inserted into a runnable "1414"target, but the target can't be run");1415return err;1416}14171418if (execution_policy == eExecutionPolicyAlways ||1419(execution_policy != eExecutionPolicyTopLevel && !can_interpret)) {1420if (m_expr.NeedsValidation() && process) {1421if (!process->GetDynamicCheckers()) {1422ClangDynamicCheckerFunctions *dynamic_checkers =1423new ClangDynamicCheckerFunctions();14241425DiagnosticManager install_diags;1426if (Error Err = dynamic_checkers->Install(install_diags, exe_ctx)) {1427std::string ErrMsg = "couldn't install checkers: " + toString(std::move(Err));1428if (install_diags.Diagnostics().size())1429ErrMsg = ErrMsg + "\n" + install_diags.GetString().c_str();1430err.SetErrorString(ErrMsg);1431return err;1432}14331434process->SetDynamicCheckers(dynamic_checkers);14351436LLDB_LOGF(log, "== [ClangExpressionParser::PrepareForExecution] "1437"Finished installing dynamic checkers ==");1438}14391440if (auto *checker_funcs = llvm::dyn_cast<ClangDynamicCheckerFunctions>(1441process->GetDynamicCheckers())) {1442IRDynamicChecks ir_dynamic_checks(*checker_funcs,1443function_name.AsCString());14441445llvm::Module *module = execution_unit_sp->GetModule();1446if (!module || !ir_dynamic_checks.runOnModule(*module)) {1447err.SetErrorToGenericError();1448err.SetErrorString("Couldn't add dynamic checks to the expression");1449return err;1450}14511452if (custom_passes.LatePasses) {1453LLDB_LOGF(log,1454"%s - Running Late IR Passes from LanguageRuntime on "1455"expression module '%s'",1456__FUNCTION__, m_expr.FunctionName());14571458custom_passes.LatePasses->run(*module);1459}1460}1461}1462}14631464if (execution_policy == eExecutionPolicyAlways ||1465execution_policy == eExecutionPolicyTopLevel || !can_interpret) {1466execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);1467}1468} else {1469execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);1470}14711472return err;1473}147414751476