blob: ec757501c23773c292eed01407841c865598b933 [file] [log] [blame]
Sean Callanan1a8d4092010-08-27 01:01:44 +00001//===-- ClangExpressionParser.cpp -------------------------------*- C++ -*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Sean Callanan1a8d4092010-08-27 01:01:44 +00006//
7//===----------------------------------------------------------------------===//
8
Sean Callanan1a8d4092010-08-27 01:01:44 +00009#include "clang/AST/ASTContext.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000010#include "clang/AST/ASTDiagnostic.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000011#include "clang/AST/ExternalASTSource.h"
Raphael Isemann9dd34c82018-09-17 12:06:07 +000012#include "clang/AST/PrettyPrinter.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000013#include "clang/Basic/DiagnosticIDs.h"
Jim Ingham151c0322015-09-15 21:13:50 +000014#include "clang/Basic/SourceLocation.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000015#include "clang/Basic/TargetInfo.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000016#include "clang/Basic/Version.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000017#include "clang/CodeGen/CodeGenAction.h"
18#include "clang/CodeGen/ModuleBuilder.h"
Jim Inghama1e541b2016-03-25 01:57:14 +000019#include "clang/Edit/Commit.h"
Jim Inghama1e541b2016-03-25 01:57:14 +000020#include "clang/Edit/EditedSource.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000021#include "clang/Edit/EditsReceiver.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000022#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"
Sean Callanan1a8d4092010-08-27 01:01:44 +000029#include "clang/Lex/Preprocessor.h"
Sean Callanane2ef6e32010-09-23 03:01:22 +000030#include "clang/Parse/ParseAST.h"
Jim Inghama1e541b2016-03-25 01:57:14 +000031#include "clang/Rewrite/Core/Rewriter.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000032#include "clang/Rewrite/Frontend/FrontendActions.h"
Raphael Isemann74829732018-08-30 17:29:37 +000033#include "clang/Sema/CodeCompleteConsumer.h"
34#include "clang/Sema/Sema.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000035#include "clang/Sema/SemaConsumer.h"
36
37#include "llvm/ADT/StringRef.h"
38#include "llvm/ExecutionEngine/ExecutionEngine.h"
Raphael Isemann6c0bbfc2019-03-12 17:09:33 +000039#include "llvm/Support/CrashRecoveryContext.h"
Sean Callanan3d654b32012-09-24 22:25:51 +000040#include "llvm/Support/Debug.h"
Rafael Espindola4609ea82013-06-26 14:10:56 +000041#include "llvm/Support/FileSystem.h"
Sean Callanan880e6802011-10-07 23:18:13 +000042#include "llvm/Support/TargetSelect.h"
Greg Clayton70b57652011-05-15 01:25:55 +000043
Chandler Carruth1e157582013-01-02 12:20:07 +000044#include "llvm/IR/LLVMContext.h"
45#include "llvm/IR/Module.h"
Greg Clayton38a61402010-12-02 23:20:03 +000046#include "llvm/Support/DynamicLibrary.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000047#include "llvm/Support/ErrorHandling.h"
Greg Clayton38a61402010-12-02 23:20:03 +000048#include "llvm/Support/Host.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000049#include "llvm/Support/MemoryBuffer.h"
Greg Clayton38a61402010-12-02 23:20:03 +000050#include "llvm/Support/Signals.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000051
Raphael Isemann6c0bbfc2019-03-12 17:09:33 +000052#include "ClangDiagnostic.h"
53#include "ClangExpressionParser.h"
54#include "ClangUserExpression.h"
55
56#include "ASTUtils.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000057#include "ClangASTSource.h"
Jonas Devlieghere63e2e592019-02-13 01:30:41 +000058#include "ClangDiagnostic.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000059#include "ClangExpressionDeclMap.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000060#include "ClangExpressionHelper.h"
Jonas Devlieghere63e2e592019-02-13 01:30:41 +000061#include "ClangExpressionParser.h"
Raphael Isemann6c0bbfc2019-03-12 17:09:33 +000062#include "ClangHost.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000063#include "ClangModulesDeclVendor.h"
64#include "ClangPersistentVariables.h"
65#include "IRForTarget.h"
Jonas Devlieghere63e2e592019-02-13 01:30:41 +000066#include "ModuleDependencyCollector.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000067
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000068#include "lldb/Core/Debugger.h"
69#include "lldb/Core/Disassembler.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000070#include "lldb/Core/Module.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000071#include "lldb/Core/StreamFile.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000072#include "lldb/Expression/IRDynamicChecks.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000073#include "lldb/Expression/IRExecutionUnit.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000074#include "lldb/Expression/IRInterpreter.h"
75#include "lldb/Host/File.h"
76#include "lldb/Host/HostInfo.h"
77#include "lldb/Symbol/ClangASTContext.h"
78#include "lldb/Symbol/SymbolVendor.h"
79#include "lldb/Target/ExecutionContext.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000080#include "lldb/Target/Language.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000081#include "lldb/Target/ObjCLanguageRuntime.h"
82#include "lldb/Target/Process.h"
83#include "lldb/Target/Target.h"
Sean Callananbd4dc692016-03-21 22:23:38 +000084#include "lldb/Target/ThreadPlanCallFunction.h"
Zachary Turner666cc0b2017-03-04 01:30:05 +000085#include "lldb/Utility/DataBufferHeap.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000086#include "lldb/Utility/LLDBAssert.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000087#include "lldb/Utility/Log.h"
Jonas Devlieghere63e2e592019-02-13 01:30:41 +000088#include "lldb/Utility/Reproducer.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000089#include "lldb/Utility/Stream.h"
90#include "lldb/Utility/StreamString.h"
Zachary Turner573ab902017-03-21 18:25:04 +000091#include "lldb/Utility/StringList.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000092
Jonas Devlieghere796ac802019-02-11 23:13:08 +000093#include <cctype>
94#include <memory>
95
Sean Callanan1a8d4092010-08-27 01:01:44 +000096using namespace clang;
97using namespace llvm;
98using namespace lldb_private;
99
100//===----------------------------------------------------------------------===//
101// Utility Methods for Clang
102//===----------------------------------------------------------------------===//
103
Kate Stoneb9c1b512016-09-06 20:57:50 +0000104class ClangExpressionParser::LLDBPreprocessorCallbacks : public PPCallbacks {
105 ClangModulesDeclVendor &m_decl_vendor;
106 ClangPersistentVariables &m_persistent_vars;
107 StreamString m_error_stream;
108 bool m_has_errors = false;
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +0000109
Sean Callananc8278af2014-12-05 01:27:35 +0000110public:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000111 LLDBPreprocessorCallbacks(ClangModulesDeclVendor &decl_vendor,
112 ClangPersistentVariables &persistent_vars)
113 : m_decl_vendor(decl_vendor), m_persistent_vars(persistent_vars) {}
114
115 void moduleImport(SourceLocation import_location, clang::ModuleIdPath path,
116 const clang::Module * /*null*/) override {
Adrian Prantl0f30a3b2019-02-13 18:10:41 +0000117 SourceModule module;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000118
Adrian Prantl0f30a3b2019-02-13 18:10:41 +0000119 for (const std::pair<IdentifierInfo *, SourceLocation> &component : path)
120 module.path.push_back(ConstString(component.first->getName()));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000121
122 StreamString error_stream;
123
124 ClangModulesDeclVendor::ModuleVector exported_modules;
Adrian Prantl0f30a3b2019-02-13 18:10:41 +0000125 if (!m_decl_vendor.AddModule(module, &exported_modules, m_error_stream))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000126 m_has_errors = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000127
Adrian Prantl0f30a3b2019-02-13 18:10:41 +0000128 for (ClangModulesDeclVendor::ModuleID module : exported_modules)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000129 m_persistent_vars.AddHandLoadedClangModule(module);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000130 }
131
132 bool hasErrors() { return m_has_errors; }
133
Zachary Turnerc1564272016-11-16 21:15:24 +0000134 llvm::StringRef getErrorString() { return m_error_stream.GetString(); }
Sean Callananc8278af2014-12-05 01:27:35 +0000135};
136
Kate Stoneb9c1b512016-09-06 20:57:50 +0000137class ClangDiagnosticManagerAdapter : public clang::DiagnosticConsumer {
Sean Callanan579e70c2016-03-19 00:03:59 +0000138public:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000139 ClangDiagnosticManagerAdapter()
140 : m_passthrough(new clang::TextDiagnosticBuffer) {}
Sean Callanan579e70c2016-03-19 00:03:59 +0000141
Kate Stoneb9c1b512016-09-06 20:57:50 +0000142 ClangDiagnosticManagerAdapter(
143 const std::shared_ptr<clang::TextDiagnosticBuffer> &passthrough)
144 : m_passthrough(passthrough) {}
Sean Callanan579e70c2016-03-19 00:03:59 +0000145
Kate Stoneb9c1b512016-09-06 20:57:50 +0000146 void ResetManager(DiagnosticManager *manager = nullptr) {
147 m_manager = manager;
148 }
Sean Callanan579e70c2016-03-19 00:03:59 +0000149
Kate Stoneb9c1b512016-09-06 20:57:50 +0000150 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
Raphael Isemann17566302019-05-03 10:03:28 +0000151 const clang::Diagnostic &Info) override {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000152 if (m_manager) {
153 llvm::SmallVector<char, 32> diag_str;
154 Info.FormatDiagnostic(diag_str);
155 diag_str.push_back('\0');
156 const char *data = diag_str.data();
Sean Callanan579e70c2016-03-19 00:03:59 +0000157
Kate Stoneb9c1b512016-09-06 20:57:50 +0000158 lldb_private::DiagnosticSeverity severity;
159 bool make_new_diagnostic = true;
160
161 switch (DiagLevel) {
162 case DiagnosticsEngine::Level::Fatal:
163 case DiagnosticsEngine::Level::Error:
164 severity = eDiagnosticSeverityError;
165 break;
166 case DiagnosticsEngine::Level::Warning:
167 severity = eDiagnosticSeverityWarning;
168 break;
169 case DiagnosticsEngine::Level::Remark:
170 case DiagnosticsEngine::Level::Ignored:
171 severity = eDiagnosticSeverityRemark;
172 break;
173 case DiagnosticsEngine::Level::Note:
174 m_manager->AppendMessageToDiagnostic(data);
175 make_new_diagnostic = false;
176 }
177 if (make_new_diagnostic) {
178 ClangDiagnostic *new_diagnostic =
179 new ClangDiagnostic(data, severity, Info.getID());
180 m_manager->AddDiagnostic(new_diagnostic);
181
182 // Don't store away warning fixits, since the compiler doesn't have
Adrian Prantl05097242018-04-30 16:49:04 +0000183 // enough context in an expression for the warning to be useful.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000184 // FIXME: Should we try to filter out FixIts that apply to our generated
185 // code, and not the user's expression?
186 if (severity == eDiagnosticSeverityError) {
187 size_t num_fixit_hints = Info.getNumFixItHints();
188 for (size_t i = 0; i < num_fixit_hints; i++) {
189 const clang::FixItHint &fixit = Info.getFixItHint(i);
190 if (!fixit.isNull())
191 new_diagnostic->AddFixitHint(fixit);
192 }
Sean Callanan579e70c2016-03-19 00:03:59 +0000193 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000194 }
Sean Callanan579e70c2016-03-19 00:03:59 +0000195 }
196
Kate Stoneb9c1b512016-09-06 20:57:50 +0000197 m_passthrough->HandleDiagnostic(DiagLevel, Info);
198 }
Sean Callanan579e70c2016-03-19 00:03:59 +0000199
Kate Stoneb9c1b512016-09-06 20:57:50 +0000200 void FlushDiagnostics(DiagnosticsEngine &Diags) {
201 m_passthrough->FlushDiagnostics(Diags);
202 }
Sean Callanan579e70c2016-03-19 00:03:59 +0000203
Kate Stoneb9c1b512016-09-06 20:57:50 +0000204 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
205 return new ClangDiagnosticManagerAdapter(m_passthrough);
206 }
207
208 clang::TextDiagnosticBuffer *GetPassthrough() { return m_passthrough.get(); }
Sean Callanan579e70c2016-03-19 00:03:59 +0000209
210private:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000211 DiagnosticManager *m_manager = nullptr;
212 std::shared_ptr<clang::TextDiagnosticBuffer> m_passthrough;
Sean Callanan579e70c2016-03-19 00:03:59 +0000213};
214
Raphael Isemann6c0bbfc2019-03-12 17:09:33 +0000215static void
216SetupModuleHeaderPaths(CompilerInstance *compiler,
217 std::vector<ConstString> include_directories,
218 lldb::TargetSP target_sp) {
219 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
220
221 HeaderSearchOptions &search_opts = compiler->getHeaderSearchOpts();
222
223 for (ConstString dir : include_directories) {
224 search_opts.AddPath(dir.AsCString(), frontend::System, false, true);
225 LLDB_LOG(log, "Added user include dir: {0}", dir);
226 }
227
228 llvm::SmallString<128> module_cache;
229 auto props = ModuleList::GetGlobalModuleListProperties();
230 props.GetClangModulesCachePath().GetPath(module_cache);
231 search_opts.ModuleCachePath = module_cache.str();
232 LLDB_LOG(log, "Using module cache path: {0}", module_cache.c_str());
233
234 FileSpec clang_resource_dir = GetClangResourceDir();
235 std::string resource_dir = clang_resource_dir.GetPath();
236 if (FileSystem::Instance().IsDirectory(resource_dir)) {
237 search_opts.ResourceDir = resource_dir;
238 std::string resource_include = resource_dir + "/include";
239 search_opts.AddPath(resource_include, frontend::System, false, true);
240
241 LLDB_LOG(log, "Added resource include dir: {0}", resource_include);
242 }
243
244 search_opts.ImplicitModuleMaps = true;
245
246 std::vector<std::string> system_include_directories =
247 target_sp->GetPlatform()->GetSystemIncludeDirectories(
248 lldb::eLanguageTypeC_plus_plus);
249
250 for (const std::string &include_dir : system_include_directories) {
251 search_opts.AddPath(include_dir, frontend::System, false, true);
252
253 LLDB_LOG(log, "Added system include dir: {0}", include_dir);
254 }
255}
256
Sean Callanan1a8d4092010-08-27 01:01:44 +0000257//===----------------------------------------------------------------------===//
258// Implementation of ClangExpressionParser
259//===----------------------------------------------------------------------===//
260
Raphael Isemann6c0bbfc2019-03-12 17:09:33 +0000261ClangExpressionParser::ClangExpressionParser(
262 ExecutionContextScope *exe_scope, Expression &expr,
263 bool generate_debug_info, std::vector<ConstString> include_directories)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000264 : ExpressionParser(exe_scope, expr, generate_debug_info), m_compiler(),
Raphael Isemann6c0bbfc2019-03-12 17:09:33 +0000265 m_pp_callbacks(nullptr),
266 m_include_directories(std::move(include_directories)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000267 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
Aidan Dodds1b6785a2016-02-03 12:33:05 +0000268
Adrian Prantl05097242018-04-30 16:49:04 +0000269 // We can't compile expressions without a target. So if the exe_scope is
270 // null or doesn't have a target, then we just need to get out of here. I'll
271 // lldb_assert and not make any of the compiler objects since
Kate Stoneb9c1b512016-09-06 20:57:50 +0000272 // I can't return errors directly from the constructor. Further calls will
273 // check if the compiler was made and
274 // bag out if it wasn't.
Sagar Thakuradc1abe2016-05-13 11:04:47 +0000275
Kate Stoneb9c1b512016-09-06 20:57:50 +0000276 if (!exe_scope) {
277 lldb_assert(exe_scope, "Can't make an expression parser with a null scope.",
278 __FUNCTION__, __FILE__, __LINE__);
279 return;
280 }
Bhushan D. Attarde3592a6e2016-02-18 11:53:28 +0000281
Kate Stoneb9c1b512016-09-06 20:57:50 +0000282 lldb::TargetSP target_sp;
283 target_sp = exe_scope->CalculateTarget();
284 if (!target_sp) {
285 lldb_assert(target_sp.get(),
286 "Can't make an expression parser with a null target.",
287 __FUNCTION__, __FILE__, __LINE__);
288 return;
289 }
Bhushan D. Attarde3592a6e2016-02-18 11:53:28 +0000290
Kate Stoneb9c1b512016-09-06 20:57:50 +0000291 // 1. Create a new compiler instance.
292 m_compiler.reset(new CompilerInstance());
Jonas Devlieghere63e2e592019-02-13 01:30:41 +0000293
294 // When capturing a reproducer, hook up the file collector with clang to
295 // collector modules and headers.
296 if (repro::Generator *g = repro::Reproducer::Instance().GetGenerator()) {
297 repro::FileProvider &fp = g->GetOrCreate<repro::FileProvider>();
298 m_compiler->setModuleDepCollector(
299 std::make_shared<ModuleDependencyCollectorAdaptor>(
300 fp.GetFileCollector()));
301 DependencyOutputOptions &opts = m_compiler->getDependencyOutputOpts();
302 opts.IncludeSystemHeaders = true;
303 opts.IncludeModuleFiles = true;
304 }
305
Jonas Devlieghere9764b652019-02-18 20:31:18 +0000306 // Make sure clang uses the same VFS as LLDB.
Duncan P. N. Exon Smith1da7eac2019-03-26 22:18:52 +0000307 m_compiler->createFileManager(FileSystem::Instance().GetVirtualFileSystem());
Jonas Devlieghere9764b652019-02-18 20:31:18 +0000308
Kate Stoneb9c1b512016-09-06 20:57:50 +0000309 lldb::LanguageType frame_lang =
310 expr.Language(); // defaults to lldb::eLanguageTypeUnknown
311 bool overridden_target_opts = false;
312 lldb_private::LanguageRuntime *lang_rt = nullptr;
Aidan Dodds1b6785a2016-02-03 12:33:05 +0000313
Kate Stoneb9c1b512016-09-06 20:57:50 +0000314 std::string abi;
315 ArchSpec target_arch;
316 target_arch = target_sp->GetArchitecture();
Aidan Dodds1b6785a2016-02-03 12:33:05 +0000317
Kate Stoneb9c1b512016-09-06 20:57:50 +0000318 const auto target_machine = target_arch.GetMachine();
Jason Molendaa3329782014-03-29 18:54:20 +0000319
Adrian Prantl05097242018-04-30 16:49:04 +0000320 // If the expression is being evaluated in the context of an existing stack
321 // frame, we introspect to see if the language runtime is available.
Bhushan D. Attarde3592a6e2016-02-18 11:53:28 +0000322
Kate Stoneb9c1b512016-09-06 20:57:50 +0000323 lldb::StackFrameSP frame_sp = exe_scope->CalculateStackFrame();
324 lldb::ProcessSP process_sp = exe_scope->CalculateProcess();
Sagar Thakuradc1abe2016-05-13 11:04:47 +0000325
Adrian Prantl05097242018-04-30 16:49:04 +0000326 // Make sure the user hasn't provided a preferred execution language with
327 // `expression --language X -- ...`
Kate Stoneb9c1b512016-09-06 20:57:50 +0000328 if (frame_sp && frame_lang == lldb::eLanguageTypeUnknown)
329 frame_lang = frame_sp->GetLanguage();
Aidan Dodds1b6785a2016-02-03 12:33:05 +0000330
Kate Stoneb9c1b512016-09-06 20:57:50 +0000331 if (process_sp && frame_lang != lldb::eLanguageTypeUnknown) {
332 lang_rt = process_sp->GetLanguageRuntime(frame_lang);
Aidan Dodds1b6785a2016-02-03 12:33:05 +0000333 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000334 log->Printf("Frame has language of type %s",
335 Language::GetNameForLanguageType(frame_lang));
336 }
Alp Toker5f838642014-07-06 05:36:57 +0000337
Kate Stoneb9c1b512016-09-06 20:57:50 +0000338 // 2. Configure the compiler with a set of default options that are
Adrian Prantl05097242018-04-30 16:49:04 +0000339 // appropriate for most situations.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000340 if (target_arch.IsValid()) {
341 std::string triple = target_arch.GetTriple().str();
342 m_compiler->getTargetOpts().Triple = triple;
343 if (log)
344 log->Printf("Using %s as the target triple",
345 m_compiler->getTargetOpts().Triple.c_str());
346 } else {
347 // If we get here we don't have a valid target and just have to guess.
348 // Sometimes this will be ok to just use the host target triple (when we
Adrian Prantl05097242018-04-30 16:49:04 +0000349 // evaluate say "2+3", but other expressions like breakpoint conditions and
350 // other things that _are_ target specific really shouldn't just be using
351 // the host triple. In such a case the language runtime should expose an
352 // overridden options set (3), below.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000353 m_compiler->getTargetOpts().Triple = llvm::sys::getDefaultTargetTriple();
354 if (log)
355 log->Printf("Using default target triple of %s",
356 m_compiler->getTargetOpts().Triple.c_str());
357 }
Adrian Prantl05097242018-04-30 16:49:04 +0000358 // Now add some special fixes for known architectures: Any arm32 iOS
359 // environment, but not on arm64
Kate Stoneb9c1b512016-09-06 20:57:50 +0000360 if (m_compiler->getTargetOpts().Triple.find("arm64") == std::string::npos &&
361 m_compiler->getTargetOpts().Triple.find("arm") != std::string::npos &&
362 m_compiler->getTargetOpts().Triple.find("ios") != std::string::npos) {
363 m_compiler->getTargetOpts().ABI = "apcs-gnu";
364 }
365 // Supported subsets of x86
366 if (target_machine == llvm::Triple::x86 ||
367 target_machine == llvm::Triple::x86_64) {
368 m_compiler->getTargetOpts().Features.push_back("+sse");
369 m_compiler->getTargetOpts().Features.push_back("+sse2");
370 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000371
Adrian Prantl05097242018-04-30 16:49:04 +0000372 // Set the target CPU to generate code for. This will be empty for any CPU
373 // that doesn't really need to make a special
Kate Stoneb9c1b512016-09-06 20:57:50 +0000374 // CPU string.
375 m_compiler->getTargetOpts().CPU = target_arch.GetClangTargetCPU();
Ewan Crawford7648dd32016-03-10 12:38:55 +0000376
Kate Stoneb9c1b512016-09-06 20:57:50 +0000377 // Set the target ABI
378 abi = GetClangTargetABI(target_arch);
379 if (!abi.empty())
380 m_compiler->getTargetOpts().ABI = abi;
381
382 // 3. Now allow the runtime to provide custom configuration options for the
Adrian Prantl05097242018-04-30 16:49:04 +0000383 // target. In this case, a specialized language runtime is available and we
384 // can query it for extra options. For 99% of use cases, this will not be
385 // needed and should be provided when basic platform detection is not enough.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000386 if (lang_rt)
387 overridden_target_opts =
388 lang_rt->GetOverrideExprOptions(m_compiler->getTargetOpts());
389
390 if (overridden_target_opts)
Pavel Labath6302bf62017-02-13 11:03:17 +0000391 if (log && log->GetVerbose()) {
392 LLDB_LOGV(
393 log, "Using overridden target options for the expression evaluation");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000394
395 auto opts = m_compiler->getTargetOpts();
Pavel Labath6302bf62017-02-13 11:03:17 +0000396 LLDB_LOGV(log, "Triple: '{0}'", opts.Triple);
397 LLDB_LOGV(log, "CPU: '{0}'", opts.CPU);
398 LLDB_LOGV(log, "FPMath: '{0}'", opts.FPMath);
399 LLDB_LOGV(log, "ABI: '{0}'", opts.ABI);
400 LLDB_LOGV(log, "LinkerVersion: '{0}'", opts.LinkerVersion);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000401 StringList::LogDump(log, opts.FeaturesAsWritten, "FeaturesAsWritten");
402 StringList::LogDump(log, opts.Features, "Features");
Sean Callananc7b65062011-11-07 23:35:40 +0000403 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000404
Kate Stoneb9c1b512016-09-06 20:57:50 +0000405 // 4. Create and install the target on the compiler.
406 m_compiler->createDiagnostics();
407 auto target_info = TargetInfo::CreateTargetInfo(
408 m_compiler->getDiagnostics(), m_compiler->getInvocation().TargetOpts);
409 if (log) {
410 log->Printf("Using SIMD alignment: %d", target_info->getSimdDefaultAlign());
411 log->Printf("Target datalayout string: '%s'",
412 target_info->getDataLayout().getStringRepresentation().c_str());
413 log->Printf("Target ABI: '%s'", target_info->getABI().str().c_str());
414 log->Printf("Target vector alignment: %d",
415 target_info->getMaxVectorAlign());
416 }
417 m_compiler->setTarget(target_info);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000418
Kate Stoneb9c1b512016-09-06 20:57:50 +0000419 assert(m_compiler->hasTarget());
Tamas Berghammerdccbfaf2015-03-31 10:21:50 +0000420
Kate Stoneb9c1b512016-09-06 20:57:50 +0000421 // 5. Set language options.
422 lldb::LanguageType language = expr.Language();
Raphael Isemann0d649c62019-01-25 22:41:31 +0000423 LangOptions &lang_opts = m_compiler->getLangOpts();
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000424
Kate Stoneb9c1b512016-09-06 20:57:50 +0000425 switch (language) {
426 case lldb::eLanguageTypeC:
427 case lldb::eLanguageTypeC89:
428 case lldb::eLanguageTypeC99:
429 case lldb::eLanguageTypeC11:
430 // FIXME: the following language option is a temporary workaround,
431 // to "ask for C, get C++."
Adrian Prantl05097242018-04-30 16:49:04 +0000432 // For now, the expression parser must use C++ anytime the language is a C
433 // family language, because the expression parser uses features of C++ to
434 // capture values.
Raphael Isemann0d649c62019-01-25 22:41:31 +0000435 lang_opts.CPlusPlus = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000436 break;
437 case lldb::eLanguageTypeObjC:
Raphael Isemann0d649c62019-01-25 22:41:31 +0000438 lang_opts.ObjC = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000439 // FIXME: the following language option is a temporary workaround,
440 // to "ask for ObjC, get ObjC++" (see comment above).
Raphael Isemann0d649c62019-01-25 22:41:31 +0000441 lang_opts.CPlusPlus = true;
Davide Italiano89419f82017-12-15 00:50:43 +0000442
443 // Clang now sets as default C++14 as the default standard (with
444 // GNU extensions), so we do the same here to avoid mismatches that
Adrian Prantl05097242018-04-30 16:49:04 +0000445 // cause compiler error when evaluating expressions (e.g. nullptr not found
446 // as it's a C++11 feature). Currently lldb evaluates C++14 as C++11 (see
447 // two lines below) so we decide to be consistent with that, but this could
448 // be re-evaluated in the future.
Raphael Isemann0d649c62019-01-25 22:41:31 +0000449 lang_opts.CPlusPlus11 = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000450 break;
451 case lldb::eLanguageTypeC_plus_plus:
452 case lldb::eLanguageTypeC_plus_plus_11:
453 case lldb::eLanguageTypeC_plus_plus_14:
Raphael Isemann0d649c62019-01-25 22:41:31 +0000454 lang_opts.CPlusPlus11 = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000455 m_compiler->getHeaderSearchOpts().UseLibcxx = true;
456 LLVM_FALLTHROUGH;
457 case lldb::eLanguageTypeC_plus_plus_03:
Raphael Isemann0d649c62019-01-25 22:41:31 +0000458 lang_opts.CPlusPlus = true;
Aleksandr Urakovf3351882018-12-04 09:51:29 +0000459 if (process_sp)
Raphael Isemann0d649c62019-01-25 22:41:31 +0000460 lang_opts.ObjC =
Aleksandr Urakovf3351882018-12-04 09:51:29 +0000461 process_sp->GetLanguageRuntime(lldb::eLanguageTypeObjC) != nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000462 break;
463 case lldb::eLanguageTypeObjC_plus_plus:
464 case lldb::eLanguageTypeUnknown:
465 default:
Raphael Isemann0d649c62019-01-25 22:41:31 +0000466 lang_opts.ObjC = true;
467 lang_opts.CPlusPlus = true;
468 lang_opts.CPlusPlus11 = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000469 m_compiler->getHeaderSearchOpts().UseLibcxx = true;
470 break;
471 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000472
Raphael Isemann0d649c62019-01-25 22:41:31 +0000473 lang_opts.Bool = true;
474 lang_opts.WChar = true;
475 lang_opts.Blocks = true;
476 lang_opts.DebuggerSupport =
Kate Stoneb9c1b512016-09-06 20:57:50 +0000477 true; // Features specifically for debugger clients
478 if (expr.DesiredResultType() == Expression::eResultTypeId)
Raphael Isemann0d649c62019-01-25 22:41:31 +0000479 lang_opts.DebuggerCastResultToId = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000480
Raphael Isemann0d649c62019-01-25 22:41:31 +0000481 lang_opts.CharIsSigned = ArchSpec(m_compiler->getTargetOpts().Triple.c_str())
482 .CharIsSignedByDefault();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000483
Adrian Prantl05097242018-04-30 16:49:04 +0000484 // Spell checking is a nice feature, but it ends up completing a lot of types
485 // that we didn't strictly speaking need to complete. As a result, we spend a
486 // long time parsing and importing debug information.
Raphael Isemann0d649c62019-01-25 22:41:31 +0000487 lang_opts.SpellChecking = false;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000488
Adrian Prantl7e34d782019-03-13 19:46:30 +0000489 auto *clang_expr = dyn_cast<ClangUserExpression>(&m_expr);
490 if (clang_expr && clang_expr->DidImportCxxModules()) {
Raphael Isemann6c0bbfc2019-03-12 17:09:33 +0000491 LLDB_LOG(log, "Adding lang options for importing C++ modules");
492
493 lang_opts.Modules = true;
494 // We want to implicitly build modules.
495 lang_opts.ImplicitModules = true;
496 // To automatically import all submodules when we import 'std'.
497 lang_opts.ModulesLocalVisibility = false;
498
499 // We use the @import statements, so we need this:
500 // FIXME: We could use the modules-ts, but that currently doesn't work.
501 lang_opts.ObjC = true;
502
503 // Options we need to parse libc++ code successfully.
504 // FIXME: We should ask the driver for the appropriate default flags.
505 lang_opts.GNUMode = true;
506 lang_opts.GNUKeywords = true;
507 lang_opts.DoubleSquareBracketAttributes = true;
508 lang_opts.CPlusPlus11 = true;
509
510 SetupModuleHeaderPaths(m_compiler.get(), m_include_directories,
511 target_sp);
512 }
513
Raphael Isemann0d649c62019-01-25 22:41:31 +0000514 if (process_sp && lang_opts.ObjC) {
Alex Langforde823bbe2019-06-10 20:53:23 +0000515 if (auto *runtime = ObjCLanguageRuntime::Get(*process_sp)) {
516 if (runtime->GetRuntimeVersion() ==
Kate Stoneb9c1b512016-09-06 20:57:50 +0000517 ObjCLanguageRuntime::ObjCRuntimeVersions::eAppleObjC_V2)
Raphael Isemann0d649c62019-01-25 22:41:31 +0000518 lang_opts.ObjCRuntime.set(ObjCRuntime::MacOSX, VersionTuple(10, 7));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000519 else
Raphael Isemann0d649c62019-01-25 22:41:31 +0000520 lang_opts.ObjCRuntime.set(ObjCRuntime::FragileMacOSX,
521 VersionTuple(10, 7));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000522
Alex Langforde823bbe2019-06-10 20:53:23 +0000523 if (runtime->HasNewLiteralsAndIndexing())
Raphael Isemann0d649c62019-01-25 22:41:31 +0000524 lang_opts.DebuggerObjCLiteral = true;
Sean Callananc3a16002011-01-17 23:42:46 +0000525 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000526 }
Greg Claytonf83f32d2011-01-15 01:32:14 +0000527
Raphael Isemann0d649c62019-01-25 22:41:31 +0000528 lang_opts.ThreadsafeStatics = false;
529 lang_opts.AccessControl = false; // Debuggers get universal access
530 lang_opts.DollarIdents = true; // $ indicates a persistent variable name
Raphael Isemannd424c2a2018-08-30 20:56:58 +0000531 // We enable all builtin functions beside the builtins from libc/libm (e.g.
532 // 'fopen'). Those libc functions are already correctly handled by LLDB, and
533 // additionally enabling them as expandable builtins is breaking Clang.
Raphael Isemann0d649c62019-01-25 22:41:31 +0000534 lang_opts.NoBuiltin = true;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000535
Kate Stoneb9c1b512016-09-06 20:57:50 +0000536 // Set CodeGen options
537 m_compiler->getCodeGenOpts().EmitDeclMetadata = true;
538 m_compiler->getCodeGenOpts().InstrumentFunctions = false;
539 m_compiler->getCodeGenOpts().DisableFPElim = true;
540 m_compiler->getCodeGenOpts().OmitLeafFramePointer = false;
541 if (generate_debug_info)
542 m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::FullDebugInfo);
543 else
544 m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::NoDebugInfo);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000545
Kate Stoneb9c1b512016-09-06 20:57:50 +0000546 // Disable some warnings.
547 m_compiler->getDiagnostics().setSeverityForGroup(
548 clang::diag::Flavor::WarningOrError, "unused-value",
549 clang::diag::Severity::Ignored, SourceLocation());
550 m_compiler->getDiagnostics().setSeverityForGroup(
551 clang::diag::Flavor::WarningOrError, "odr",
552 clang::diag::Severity::Ignored, SourceLocation());
Alp Toker10933d12014-06-12 11:14:32 +0000553
Kate Stoneb9c1b512016-09-06 20:57:50 +0000554 // Inform the target of the language options
555 //
556 // FIXME: We shouldn't need to do this, the target should be immutable once
557 // created. This complexity should be lifted elsewhere.
558 m_compiler->getTarget().adjust(m_compiler->getLangOpts());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000559
Kate Stoneb9c1b512016-09-06 20:57:50 +0000560 // 6. Set up the diagnostic buffer for reporting errors
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000561
Kate Stoneb9c1b512016-09-06 20:57:50 +0000562 m_compiler->getDiagnostics().setClient(new ClangDiagnosticManagerAdapter);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000563
Kate Stoneb9c1b512016-09-06 20:57:50 +0000564 // 7. Set up the source management objects inside the compiler
Kate Stoneb9c1b512016-09-06 20:57:50 +0000565 m_compiler->createFileManager();
Jonas Devlieghereff04b3d2019-02-14 18:05:43 +0000566 if (!m_compiler->hasSourceManager())
567 m_compiler->createSourceManager(m_compiler->getFileManager());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000568 m_compiler->createPreprocessor(TU_Complete);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000569
Kate Stoneb9c1b512016-09-06 20:57:50 +0000570 if (ClangModulesDeclVendor *decl_vendor =
571 target_sp->GetClangModulesDeclVendor()) {
572 ClangPersistentVariables *clang_persistent_vars =
573 llvm::cast<ClangPersistentVariables>(
574 target_sp->GetPersistentExpressionStateForLanguage(
575 lldb::eLanguageTypeC));
576 std::unique_ptr<PPCallbacks> pp_callbacks(
577 new LLDBPreprocessorCallbacks(*decl_vendor, *clang_persistent_vars));
578 m_pp_callbacks =
579 static_cast<LLDBPreprocessorCallbacks *>(pp_callbacks.get());
580 m_compiler->getPreprocessor().addPPCallbacks(std::move(pp_callbacks));
581 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000582
Adrian Prantl05097242018-04-30 16:49:04 +0000583 // 8. Most of this we get from the CompilerInstance, but we also want to give
584 // the context an ExternalASTSource.
Raphael Isemann778b3082018-08-23 20:40:45 +0000585
586 auto &PP = m_compiler->getPreprocessor();
587 auto &builtin_context = PP.getBuiltinInfo();
588 builtin_context.initializeBuiltins(PP.getIdentifierTable(),
589 m_compiler->getLangOpts());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000590
Raphael Isemann596709d2018-08-27 15:18:33 +0000591 m_compiler->createASTContext();
592 clang::ASTContext &ast_context = m_compiler->getASTContext();
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000593
Kate Stoneb9c1b512016-09-06 20:57:50 +0000594 m_ast_context.reset(
595 new ClangASTContext(m_compiler->getTargetOpts().Triple.c_str()));
Raphael Isemann596709d2018-08-27 15:18:33 +0000596 m_ast_context->setASTContext(&ast_context);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000597
598 std::string module_name("$__lldb_module");
599
600 m_llvm_context.reset(new LLVMContext());
601 m_code_generator.reset(CreateLLVMCodeGen(
602 m_compiler->getDiagnostics(), module_name,
603 m_compiler->getHeaderSearchOpts(), m_compiler->getPreprocessorOpts(),
604 m_compiler->getCodeGenOpts(), *m_llvm_context));
Sean Callanan1a8d4092010-08-27 01:01:44 +0000605}
606
Kate Stoneb9c1b512016-09-06 20:57:50 +0000607ClangExpressionParser::~ClangExpressionParser() {}
Sean Callanan1a8d4092010-08-27 01:01:44 +0000608
Raphael Isemann74829732018-08-30 17:29:37 +0000609namespace {
610
Adrian Prantlf05b42e2019-03-11 17:09:29 +0000611/// \class CodeComplete
Raphael Isemann74829732018-08-30 17:29:37 +0000612///
613/// A code completion consumer for the clang Sema that is responsible for
614/// creating the completion suggestions when a user requests completion
615/// of an incomplete `expr` invocation.
Raphael Isemann74829732018-08-30 17:29:37 +0000616class CodeComplete : public CodeCompleteConsumer {
Raphael Isemann39ec6e72018-08-30 19:47:53 +0000617 CodeCompletionTUInfo m_info;
Raphael Isemann74829732018-08-30 17:29:37 +0000618
Raphael Isemann39ec6e72018-08-30 19:47:53 +0000619 std::string m_expr;
620 unsigned m_position = 0;
Raphael Isemannc11a7802018-08-30 21:26:32 +0000621 CompletionRequest &m_request;
Raphael Isemann9dd34c82018-09-17 12:06:07 +0000622 /// The printing policy we use when printing declarations for our completion
623 /// descriptions.
624 clang::PrintingPolicy m_desc_policy;
Raphael Isemann74829732018-08-30 17:29:37 +0000625
626 /// Returns true if the given character can be used in an identifier.
627 /// This also returns true for numbers because for completion we usually
628 /// just iterate backwards over iterators.
629 ///
630 /// Note: lldb uses '$' in its internal identifiers, so we also allow this.
631 static bool IsIdChar(char c) {
632 return c == '_' || std::isalnum(c) || c == '$';
633 }
634
635 /// Returns true if the given character is used to separate arguments
636 /// in the command line of lldb.
637 static bool IsTokenSeparator(char c) { return c == ' ' || c == '\t'; }
638
639 /// Drops all tokens in front of the expression that are unrelated for
640 /// the completion of the cmd line. 'unrelated' means here that the token
641 /// is not interested for the lldb completion API result.
642 StringRef dropUnrelatedFrontTokens(StringRef cmd) {
643 if (cmd.empty())
644 return cmd;
645
646 // If we are at the start of a word, then all tokens are unrelated to
647 // the current completion logic.
648 if (IsTokenSeparator(cmd.back()))
649 return StringRef();
650
651 // Remove all previous tokens from the string as they are unrelated
652 // to completing the current token.
653 StringRef to_remove = cmd;
654 while (!to_remove.empty() && !IsTokenSeparator(to_remove.back())) {
655 to_remove = to_remove.drop_back();
656 }
657 cmd = cmd.drop_front(to_remove.size());
658
659 return cmd;
660 }
661
662 /// Removes the last identifier token from the given cmd line.
663 StringRef removeLastToken(StringRef cmd) {
664 while (!cmd.empty() && IsIdChar(cmd.back())) {
665 cmd = cmd.drop_back();
666 }
667 return cmd;
668 }
669
670 /// Attemps to merge the given completion from the given position into the
671 /// existing command. Returns the completion string that can be returned to
672 /// the lldb completion API.
673 std::string mergeCompletion(StringRef existing, unsigned pos,
674 StringRef completion) {
675 StringRef existing_command = existing.substr(0, pos);
676 // We rewrite the last token with the completion, so let's drop that
677 // token from the command.
678 existing_command = removeLastToken(existing_command);
679 // We also should remove all previous tokens from the command as they
680 // would otherwise be added to the completion that already has the
681 // completion.
682 existing_command = dropUnrelatedFrontTokens(existing_command);
683 return existing_command.str() + completion.str();
684 }
685
686public:
687 /// Constructs a CodeComplete consumer that can be attached to a Sema.
Adrian Prantlf05b42e2019-03-11 17:09:29 +0000688 /// \param[out] matches
Raphael Isemann74829732018-08-30 17:29:37 +0000689 /// The list of matches that the lldb completion API expects as a result.
690 /// This may already contain matches, so it's only allowed to append
691 /// to this variable.
Adrian Prantlf05b42e2019-03-11 17:09:29 +0000692 /// \param[out] expr
Raphael Isemann74829732018-08-30 17:29:37 +0000693 /// The whole expression string that we are currently parsing. This
694 /// string needs to be equal to the input the user typed, and NOT the
695 /// final code that Clang is parsing.
Adrian Prantlf05b42e2019-03-11 17:09:29 +0000696 /// \param[out] position
Raphael Isemann74829732018-08-30 17:29:37 +0000697 /// The character position of the user cursor in the `expr` parameter.
698 ///
Raphael Isemann9dd34c82018-09-17 12:06:07 +0000699 CodeComplete(CompletionRequest &request, clang::LangOptions ops,
700 std::string expr, unsigned position)
Sam McCall3a753302019-04-18 17:35:55 +0000701 : CodeCompleteConsumer(CodeCompleteOptions()),
Raphael Isemann39ec6e72018-08-30 19:47:53 +0000702 m_info(std::make_shared<GlobalCodeCompletionAllocator>()), m_expr(expr),
Raphael Isemann9dd34c82018-09-17 12:06:07 +0000703 m_position(position), m_request(request), m_desc_policy(ops) {
704
705 // Ensure that the printing policy is producing a description that is as
706 // short as possible.
707 m_desc_policy.SuppressScope = true;
708 m_desc_policy.SuppressTagKeyword = true;
709 m_desc_policy.FullyQualifiedName = false;
710 m_desc_policy.TerseOutput = true;
711 m_desc_policy.IncludeNewlines = false;
712 m_desc_policy.UseVoidForZeroParams = false;
713 m_desc_policy.Bool = true;
714 }
Raphael Isemann74829732018-08-30 17:29:37 +0000715
716 /// Deregisters and destroys this code-completion consumer.
Raphael Isemann17566302019-05-03 10:03:28 +0000717 ~CodeComplete() override {}
Raphael Isemann74829732018-08-30 17:29:37 +0000718
719 /// \name Code-completion filtering
720 /// Check if the result should be filtered out.
721 bool isResultFilteredOut(StringRef Filter,
722 CodeCompletionResult Result) override {
723 // This code is mostly copied from CodeCompleteConsumer.
724 switch (Result.Kind) {
725 case CodeCompletionResult::RK_Declaration:
726 return !(
727 Result.Declaration->getIdentifier() &&
728 Result.Declaration->getIdentifier()->getName().startswith(Filter));
729 case CodeCompletionResult::RK_Keyword:
730 return !StringRef(Result.Keyword).startswith(Filter);
731 case CodeCompletionResult::RK_Macro:
732 return !Result.Macro->getName().startswith(Filter);
733 case CodeCompletionResult::RK_Pattern:
734 return !StringRef(Result.Pattern->getAsString()).startswith(Filter);
735 }
736 // If we trigger this assert or the above switch yields a warning, then
737 // CodeCompletionResult has been enhanced with more kinds of completion
738 // results. Expand the switch above in this case.
739 assert(false && "Unknown completion result type?");
740 // If we reach this, then we should just ignore whatever kind of unknown
741 // result we got back. We probably can't turn it into any kind of useful
742 // completion suggestion with the existing code.
743 return true;
744 }
745
746 /// \name Code-completion callbacks
747 /// Process the finalized code-completion results.
748 void ProcessCodeCompleteResults(Sema &SemaRef, CodeCompletionContext Context,
749 CodeCompletionResult *Results,
750 unsigned NumResults) override {
751
752 // The Sema put the incomplete token we try to complete in here during
753 // lexing, so we need to retrieve it here to know what we are completing.
754 StringRef Filter = SemaRef.getPreprocessor().getCodeCompletionFilter();
755
756 // Iterate over all the results. Filter out results we don't want and
757 // process the rest.
758 for (unsigned I = 0; I != NumResults; ++I) {
759 // Filter the results with the information from the Sema.
760 if (!Filter.empty() && isResultFilteredOut(Filter, Results[I]))
761 continue;
762
763 CodeCompletionResult &R = Results[I];
764 std::string ToInsert;
Raphael Isemann9dd34c82018-09-17 12:06:07 +0000765 std::string Description;
Raphael Isemann74829732018-08-30 17:29:37 +0000766 // Handle the different completion kinds that come from the Sema.
767 switch (R.Kind) {
768 case CodeCompletionResult::RK_Declaration: {
769 const NamedDecl *D = R.Declaration;
770 ToInsert = R.Declaration->getNameAsString();
771 // If we have a function decl that has no arguments we want to
772 // complete the empty parantheses for the user. If the function has
773 // arguments, we at least complete the opening bracket.
774 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(D)) {
775 if (F->getNumParams() == 0)
776 ToInsert += "()";
777 else
778 ToInsert += "(";
Raphael Isemann9dd34c82018-09-17 12:06:07 +0000779 raw_string_ostream OS(Description);
780 F->print(OS, m_desc_policy, false);
781 OS.flush();
782 } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
783 Description = V->getType().getAsString(m_desc_policy);
784 } else if (const FieldDecl *F = dyn_cast<FieldDecl>(D)) {
785 Description = F->getType().getAsString(m_desc_policy);
786 } else if (const NamespaceDecl *N = dyn_cast<NamespaceDecl>(D)) {
787 // If we try to complete a namespace, then we can directly append
788 // the '::'.
Raphael Isemann74829732018-08-30 17:29:37 +0000789 if (!N->isAnonymousNamespace())
790 ToInsert += "::";
791 }
792 break;
793 }
794 case CodeCompletionResult::RK_Keyword:
795 ToInsert = R.Keyword;
796 break;
797 case CodeCompletionResult::RK_Macro:
Raphael Isemann74829732018-08-30 17:29:37 +0000798 ToInsert = R.Macro->getName().str();
799 break;
800 case CodeCompletionResult::RK_Pattern:
801 ToInsert = R.Pattern->getTypedText();
802 break;
803 }
804 // At this point all information is in the ToInsert string.
805
806 // We also filter some internal lldb identifiers here. The user
807 // shouldn't see these.
808 if (StringRef(ToInsert).startswith("$__lldb_"))
809 continue;
810 if (!ToInsert.empty()) {
811 // Merge the suggested Token into the existing command line to comply
812 // with the kind of result the lldb API expects.
813 std::string CompletionSuggestion =
Raphael Isemann39ec6e72018-08-30 19:47:53 +0000814 mergeCompletion(m_expr, m_position, ToInsert);
Raphael Isemann9dd34c82018-09-17 12:06:07 +0000815 m_request.AddCompletion(CompletionSuggestion, Description);
Raphael Isemann74829732018-08-30 17:29:37 +0000816 }
817 }
818 }
819
820 /// \param S the semantic-analyzer object for which code-completion is being
821 /// done.
822 ///
823 /// \param CurrentArg the index of the current argument.
824 ///
825 /// \param Candidates an array of overload candidates.
826 ///
827 /// \param NumCandidates the number of overload candidates
828 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
829 OverloadCandidate *Candidates,
830 unsigned NumCandidates,
831 SourceLocation OpenParLoc) override {
832 // At the moment we don't filter out any overloaded candidates.
833 }
834
835 CodeCompletionAllocator &getAllocator() override {
Raphael Isemann39ec6e72018-08-30 19:47:53 +0000836 return m_info.getAllocator();
Raphael Isemann74829732018-08-30 17:29:37 +0000837 }
838
Raphael Isemann39ec6e72018-08-30 19:47:53 +0000839 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return m_info; }
Raphael Isemann74829732018-08-30 17:29:37 +0000840};
841} // namespace
842
Raphael Isemannc11a7802018-08-30 21:26:32 +0000843bool ClangExpressionParser::Complete(CompletionRequest &request, unsigned line,
Raphael Isemann74829732018-08-30 17:29:37 +0000844 unsigned pos, unsigned typed_pos) {
845 DiagnosticManager mgr;
846 // We need the raw user expression here because that's what the CodeComplete
847 // class uses to provide completion suggestions.
848 // However, the `Text` method only gives us the transformed expression here.
849 // To actually get the raw user input here, we have to cast our expression to
850 // the LLVMUserExpression which exposes the right API. This should never fail
851 // as we always have a ClangUserExpression whenever we call this.
Raphael Isemannd63c1db2019-03-14 17:39:39 +0000852 ClangUserExpression *llvm_expr = cast<ClangUserExpression>(&m_expr);
853 CodeComplete CC(request, m_compiler->getLangOpts(), llvm_expr->GetUserText(),
Raphael Isemann9dd34c82018-09-17 12:06:07 +0000854 typed_pos);
Raphael Isemann74829732018-08-30 17:29:37 +0000855 // We don't need a code generator for parsing.
856 m_code_generator.reset();
857 // Start parsing the expression with our custom code completion consumer.
858 ParseInternal(mgr, &CC, line, pos);
859 return true;
860}
861
Kate Stoneb9c1b512016-09-06 20:57:50 +0000862unsigned ClangExpressionParser::Parse(DiagnosticManager &diagnostic_manager) {
Raphael Isemann74829732018-08-30 17:29:37 +0000863 return ParseInternal(diagnostic_manager);
864}
865
866unsigned
867ClangExpressionParser::ParseInternal(DiagnosticManager &diagnostic_manager,
868 CodeCompleteConsumer *completion_consumer,
869 unsigned completion_line,
870 unsigned completion_column) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000871 ClangDiagnosticManagerAdapter *adapter =
872 static_cast<ClangDiagnosticManagerAdapter *>(
873 m_compiler->getDiagnostics().getClient());
874 clang::TextDiagnosticBuffer *diag_buf = adapter->GetPassthrough();
875 diag_buf->FlushDiagnostics(m_compiler->getDiagnostics());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000876
Kate Stoneb9c1b512016-09-06 20:57:50 +0000877 adapter->ResetManager(&diagnostic_manager);
Sean Callanan579e70c2016-03-19 00:03:59 +0000878
Kate Stoneb9c1b512016-09-06 20:57:50 +0000879 const char *expr_text = m_expr.Text();
Rafael Espindola9cb97b62014-05-21 15:08:27 +0000880
Kate Stoneb9c1b512016-09-06 20:57:50 +0000881 clang::SourceManager &source_mgr = m_compiler->getSourceManager();
882 bool created_main_file = false;
Raphael Isemann74829732018-08-30 17:29:37 +0000883
884 // Clang wants to do completion on a real file known by Clang's file manager,
885 // so we have to create one to make this work.
886 // TODO: We probably could also simulate to Clang's file manager that there
887 // is a real file that contains our code.
888 bool should_create_file = completion_consumer != nullptr;
889
890 // We also want a real file on disk if we generate full debug info.
891 should_create_file |= m_compiler->getCodeGenOpts().getDebugInfo() ==
892 codegenoptions::FullDebugInfo;
893
894 if (should_create_file) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000895 int temp_fd = -1;
Stella Stamenovab3f44ad2018-12-10 17:23:28 +0000896 llvm::SmallString<128> result_path;
Pavel Labath60f028f2018-06-19 15:09:07 +0000897 if (FileSpec tmpdir_file_spec = HostInfo::GetProcessTempDir()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000898 tmpdir_file_spec.AppendPathComponent("lldb-%%%%%%.expr");
899 std::string temp_source_path = tmpdir_file_spec.GetPath();
900 llvm::sys::fs::createUniqueFile(temp_source_path, temp_fd, result_path);
901 } else {
902 llvm::sys::fs::createTemporaryFile("lldb", "expr", temp_fd, result_path);
903 }
904
905 if (temp_fd != -1) {
906 lldb_private::File file(temp_fd, true);
907 const size_t expr_text_len = strlen(expr_text);
908 size_t bytes_written = expr_text_len;
909 if (file.Write(expr_text, bytes_written).Success()) {
910 if (bytes_written == expr_text_len) {
911 file.Close();
Jonas Devlieghereff04b3d2019-02-14 18:05:43 +0000912 source_mgr.setMainFileID(source_mgr.createFileID(
913 m_compiler->getFileManager().getFile(result_path),
914 SourceLocation(), SrcMgr::C_User));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000915 created_main_file = true;
Greg Clayton23f8c952014-03-24 23:10:19 +0000916 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000917 }
Greg Clayton23f8c952014-03-24 23:10:19 +0000918 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000919 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000920
Kate Stoneb9c1b512016-09-06 20:57:50 +0000921 if (!created_main_file) {
922 std::unique_ptr<MemoryBuffer> memory_buffer =
923 MemoryBuffer::getMemBufferCopy(expr_text, __FUNCTION__);
924 source_mgr.setMainFileID(source_mgr.createFileID(std::move(memory_buffer)));
925 }
926
927 diag_buf->BeginSourceFile(m_compiler->getLangOpts(),
928 &m_compiler->getPreprocessor());
929
930 ClangExpressionHelper *type_system_helper =
931 dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
932
Raphael Isemann74829732018-08-30 17:29:37 +0000933 // If we want to parse for code completion, we need to attach our code
934 // completion consumer to the Sema and specify a completion position.
935 // While parsing the Sema will call this consumer with the provided
936 // completion suggestions.
937 if (completion_consumer) {
938 auto main_file = source_mgr.getFileEntryForID(source_mgr.getMainFileID());
939 auto &PP = m_compiler->getPreprocessor();
940 // Lines and columns start at 1 in Clang, but code completion positions are
941 // indexed from 0, so we need to add 1 to the line and column here.
942 ++completion_line;
943 ++completion_column;
944 PP.SetCodeCompletionPoint(main_file, completion_line, completion_column);
945 }
946
Raphael Isemann6c0bbfc2019-03-12 17:09:33 +0000947 ASTConsumer *ast_transformer =
948 type_system_helper->ASTTransformer(m_code_generator.get());
949
950 std::unique_ptr<clang::ASTConsumer> Consumer;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000951 if (ast_transformer) {
Raphael Isemann6c0bbfc2019-03-12 17:09:33 +0000952 Consumer.reset(new ASTConsumerForwarder(ast_transformer));
953 } else if (m_code_generator) {
954 Consumer.reset(new ASTConsumerForwarder(m_code_generator.get()));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000955 } else {
Raphael Isemann6c0bbfc2019-03-12 17:09:33 +0000956 Consumer.reset(new ASTConsumer());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000957 }
958
Raphael Isemann6c0bbfc2019-03-12 17:09:33 +0000959 clang::ASTContext &ast_context = m_compiler->getASTContext();
960
961 m_compiler->setSema(new Sema(m_compiler->getPreprocessor(), ast_context,
962 *Consumer, TU_Complete, completion_consumer));
963 m_compiler->setASTConsumer(std::move(Consumer));
964
Raphael Isemannf74a4c12019-04-30 08:41:35 +0000965 if (ast_context.getLangOpts().Modules) {
Raphael Isemann6c0bbfc2019-03-12 17:09:33 +0000966 m_compiler->createModuleManager();
Raphael Isemannf74a4c12019-04-30 08:41:35 +0000967 m_ast_context->setSema(&m_compiler->getSema());
968 }
Raphael Isemann6c0bbfc2019-03-12 17:09:33 +0000969
970 ClangExpressionDeclMap *decl_map = type_system_helper->DeclMap();
971 if (decl_map) {
972 decl_map->InstallCodeGenerator(&m_compiler->getASTConsumer());
973
974 clang::ExternalASTSource *ast_source = decl_map->CreateProxy();
975
976 if (ast_context.getExternalSource()) {
977 auto module_wrapper =
978 new ExternalASTSourceWrapper(ast_context.getExternalSource());
979
980 auto ast_source_wrapper = new ExternalASTSourceWrapper(ast_source);
981
982 auto multiplexer =
983 new SemaSourceWithPriorities(*module_wrapper, *ast_source_wrapper);
984 IntrusiveRefCntPtr<ExternalASTSource> Source(multiplexer);
985 ast_context.setExternalSource(Source);
986 } else {
987 ast_context.setExternalSource(ast_source);
988 }
989 decl_map->InstallASTContext(ast_context, m_compiler->getFileManager());
990 }
991
992 // Check that the ASTReader is properly attached to ASTContext and Sema.
993 if (ast_context.getLangOpts().Modules) {
994 assert(m_compiler->getASTContext().getExternalSource() &&
995 "ASTContext doesn't know about the ASTReader?");
996 assert(m_compiler->getSema().getExternalSource() &&
997 "Sema doesn't know about the ASTReader?");
998 }
999
1000 {
1001 llvm::CrashRecoveryContextCleanupRegistrar<Sema> CleanupSema(
1002 &m_compiler->getSema());
1003 ParseAST(m_compiler->getSema(), false, false);
1004 }
Raphael Isemannf74a4c12019-04-30 08:41:35 +00001005
1006 // Make sure we have no pointer to the Sema we are about to destroy.
1007 if (ast_context.getLangOpts().Modules)
1008 m_ast_context->setSema(nullptr);
Raphael Isemann6c0bbfc2019-03-12 17:09:33 +00001009 // Destroy the Sema. This is necessary because we want to emulate the
1010 // original behavior of ParseAST (which also destroys the Sema after parsing).
1011 m_compiler->setSema(nullptr);
1012
Kate Stoneb9c1b512016-09-06 20:57:50 +00001013 diag_buf->EndSourceFile();
1014
1015 unsigned num_errors = diag_buf->getNumErrors();
1016
1017 if (m_pp_callbacks && m_pp_callbacks->hasErrors()) {
1018 num_errors++;
Zachary Turnere2411fa2016-11-12 19:12:56 +00001019 diagnostic_manager.PutString(eDiagnosticSeverityError,
1020 "while importing modules:");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001021 diagnostic_manager.AppendMessageToDiagnostic(
Zachary Turnerc1564272016-11-16 21:15:24 +00001022 m_pp_callbacks->getErrorString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001023 }
1024
1025 if (!num_errors) {
1026 if (type_system_helper->DeclMap() &&
1027 !type_system_helper->DeclMap()->ResolveUnknownTypes()) {
1028 diagnostic_manager.Printf(eDiagnosticSeverityError,
1029 "Couldn't infer the type of a variable");
1030 num_errors++;
Greg Clayton23f8c952014-03-24 23:10:19 +00001031 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001032 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001033
Kate Stoneb9c1b512016-09-06 20:57:50 +00001034 if (!num_errors) {
1035 type_system_helper->CommitPersistentDecls();
1036 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001037
Kate Stoneb9c1b512016-09-06 20:57:50 +00001038 adapter->ResetManager();
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001039
Kate Stoneb9c1b512016-09-06 20:57:50 +00001040 return num_errors;
Sean Callanan1a8d4092010-08-27 01:01:44 +00001041}
1042
Sagar Thakuradc1abe2016-05-13 11:04:47 +00001043std::string
Kate Stoneb9c1b512016-09-06 20:57:50 +00001044ClangExpressionParser::GetClangTargetABI(const ArchSpec &target_arch) {
1045 std::string abi;
1046
1047 if (target_arch.IsMIPS()) {
1048 switch (target_arch.GetFlags() & ArchSpec::eMIPSABI_mask) {
1049 case ArchSpec::eMIPSABI_N64:
1050 abi = "n64";
1051 break;
1052 case ArchSpec::eMIPSABI_N32:
1053 abi = "n32";
1054 break;
1055 case ArchSpec::eMIPSABI_O32:
1056 abi = "o32";
1057 break;
1058 default:
1059 break;
Sagar Thakuradc1abe2016-05-13 11:04:47 +00001060 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001061 }
1062 return abi;
Sagar Thakuradc1abe2016-05-13 11:04:47 +00001063}
1064
Kate Stoneb9c1b512016-09-06 20:57:50 +00001065bool ClangExpressionParser::RewriteExpression(
1066 DiagnosticManager &diagnostic_manager) {
1067 clang::SourceManager &source_manager = m_compiler->getSourceManager();
1068 clang::edit::EditedSource editor(source_manager, m_compiler->getLangOpts(),
1069 nullptr);
1070 clang::edit::Commit commit(editor);
1071 clang::Rewriter rewriter(source_manager, m_compiler->getLangOpts());
Jim Inghama1e541b2016-03-25 01:57:14 +00001072
Kate Stoneb9c1b512016-09-06 20:57:50 +00001073 class RewritesReceiver : public edit::EditsReceiver {
1074 Rewriter &rewrite;
Jim Inghama1e541b2016-03-25 01:57:14 +00001075
Kate Stoneb9c1b512016-09-06 20:57:50 +00001076 public:
1077 RewritesReceiver(Rewriter &in_rewrite) : rewrite(in_rewrite) {}
1078
1079 void insert(SourceLocation loc, StringRef text) override {
1080 rewrite.InsertText(loc, text);
Jim Inghama1e541b2016-03-25 01:57:14 +00001081 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001082 void replace(CharSourceRange range, StringRef text) override {
1083 rewrite.ReplaceText(range.getBegin(), rewrite.getRangeSize(range), text);
Sean Callananfc55f5d2010-09-21 00:44:12 +00001084 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001085 };
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001086
Kate Stoneb9c1b512016-09-06 20:57:50 +00001087 RewritesReceiver rewrites_receiver(rewriter);
1088
1089 const DiagnosticList &diagnostics = diagnostic_manager.Diagnostics();
1090 size_t num_diags = diagnostics.size();
1091 if (num_diags == 0)
Sean Callananfc55f5d2010-09-21 00:44:12 +00001092 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001093
1094 for (const Diagnostic *diag : diagnostic_manager.Diagnostics()) {
1095 const ClangDiagnostic *diagnostic = llvm::dyn_cast<ClangDiagnostic>(diag);
1096 if (diagnostic && diagnostic->HasFixIts()) {
1097 for (const FixItHint &fixit : diagnostic->FixIts()) {
1098 // This is cobbed from clang::Rewrite::FixItRewriter.
1099 if (fixit.CodeToInsert.empty()) {
1100 if (fixit.InsertFromRange.isValid()) {
1101 commit.insertFromRange(fixit.RemoveRange.getBegin(),
1102 fixit.InsertFromRange, /*afterToken=*/false,
1103 fixit.BeforePreviousInsertions);
1104 } else
1105 commit.remove(fixit.RemoveRange);
1106 } else {
1107 if (fixit.RemoveRange.isTokenRange() ||
1108 fixit.RemoveRange.getBegin() != fixit.RemoveRange.getEnd())
1109 commit.replace(fixit.RemoveRange, fixit.CodeToInsert);
1110 else
1111 commit.insert(fixit.RemoveRange.getBegin(), fixit.CodeToInsert,
1112 /*afterToken=*/false, fixit.BeforePreviousInsertions);
1113 }
1114 }
1115 }
1116 }
1117
1118 // FIXME - do we want to try to propagate specific errors here?
1119 if (!commit.isCommitable())
1120 return false;
1121 else if (!editor.commit(commit))
1122 return false;
1123
1124 // Now play all the edits, and stash the result in the diagnostic manager.
1125 editor.applyRewrites(rewrites_receiver);
1126 RewriteBuffer &main_file_buffer =
1127 rewriter.getEditBuffer(source_manager.getMainFileID());
1128
1129 std::string fixed_expression;
1130 llvm::raw_string_ostream out_stream(fixed_expression);
1131
1132 main_file_buffer.write(out_stream);
1133 out_stream.flush();
1134 diagnostic_manager.SetFixedExpression(fixed_expression);
1135
1136 return true;
Sean Callananfc55f5d2010-09-21 00:44:12 +00001137}
1138
Kate Stoneb9c1b512016-09-06 20:57:50 +00001139static bool FindFunctionInModule(ConstString &mangled_name,
1140 llvm::Module *module, const char *orig_name) {
1141 for (const auto &func : module->getFunctionList()) {
1142 const StringRef &name = func.getName();
1143 if (name.find(orig_name) != StringRef::npos) {
1144 mangled_name.SetString(name);
1145 return true;
Sean Callanan1a8d4092010-08-27 01:01:44 +00001146 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001147 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001148
Kate Stoneb9c1b512016-09-06 20:57:50 +00001149 return false;
Sean Callanan1a8d4092010-08-27 01:01:44 +00001150}
Sean Callananbd4dc692016-03-21 22:23:38 +00001151
Zachary Turner97206d52017-05-12 04:51:55 +00001152lldb_private::Status ClangExpressionParser::PrepareForExecution(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001153 lldb::addr_t &func_addr, lldb::addr_t &func_end,
1154 lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx,
1155 bool &can_interpret, ExecutionPolicy execution_policy) {
1156 func_addr = LLDB_INVALID_ADDRESS;
1157 func_end = LLDB_INVALID_ADDRESS;
1158 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1159
Zachary Turner97206d52017-05-12 04:51:55 +00001160 lldb_private::Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001161
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001162 std::unique_ptr<llvm::Module> llvm_module_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001163 m_code_generator->ReleaseModule());
1164
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001165 if (!llvm_module_up) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001166 err.SetErrorToGenericError();
1167 err.SetErrorString("IR doesn't contain a module");
Sean Callananbd4dc692016-03-21 22:23:38 +00001168 return err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001169 }
1170
1171 ConstString function_name;
1172
1173 if (execution_policy != eExecutionPolicyTopLevel) {
1174 // Find the actual name of the function (it's often mangled somehow)
1175
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001176 if (!FindFunctionInModule(function_name, llvm_module_up.get(),
Kate Stoneb9c1b512016-09-06 20:57:50 +00001177 m_expr.FunctionName())) {
1178 err.SetErrorToGenericError();
1179 err.SetErrorStringWithFormat("Couldn't find %s() in the module",
1180 m_expr.FunctionName());
1181 return err;
1182 } else {
1183 if (log)
1184 log->Printf("Found function %s for %s", function_name.AsCString(),
1185 m_expr.FunctionName());
1186 }
1187 }
1188
1189 SymbolContext sc;
1190
1191 if (lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP()) {
1192 sc = frame_sp->GetSymbolContext(lldb::eSymbolContextEverything);
1193 } else if (lldb::TargetSP target_sp = exe_ctx.GetTargetSP()) {
1194 sc.target_sp = target_sp;
1195 }
1196
1197 LLVMUserExpression::IRPasses custom_passes;
1198 {
1199 auto lang = m_expr.Language();
1200 if (log)
Bruce Mitchener4ebdee02018-05-29 09:10:46 +00001201 log->Printf("%s - Current expression language is %s\n", __FUNCTION__,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001202 Language::GetNameForLanguageType(lang));
Jim Ingham22562152016-11-03 23:42:09 +00001203 lldb::ProcessSP process_sp = exe_ctx.GetProcessSP();
1204 if (process_sp && lang != lldb::eLanguageTypeUnknown) {
1205 auto runtime = process_sp->GetLanguageRuntime(lang);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001206 if (runtime)
1207 runtime->GetIRPasses(custom_passes);
1208 }
1209 }
1210
1211 if (custom_passes.EarlyPasses) {
1212 if (log)
1213 log->Printf("%s - Running Early IR Passes from LanguageRuntime on "
1214 "expression module '%s'",
1215 __FUNCTION__, m_expr.FunctionName());
1216
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001217 custom_passes.EarlyPasses->run(*llvm_module_up);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001218 }
1219
Jonas Devlieghere796ac802019-02-11 23:13:08 +00001220 execution_unit_sp = std::make_shared<IRExecutionUnit>(
1221 m_llvm_context, // handed off here
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001222 llvm_module_up, // handed off here
1223 function_name, exe_ctx.GetTargetSP(), sc,
Jonas Devlieghere796ac802019-02-11 23:13:08 +00001224 m_compiler->getTargetOpts().Features);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001225
1226 ClangExpressionHelper *type_system_helper =
1227 dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
1228 ClangExpressionDeclMap *decl_map =
1229 type_system_helper->DeclMap(); // result can be NULL
1230
1231 if (decl_map) {
Konrad Kleine248a1302019-05-23 11:14:47 +00001232 Stream *error_stream = nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001233 Target *target = exe_ctx.GetTargetPtr();
1234 error_stream = target->GetDebugger().GetErrorFile().get();
1235
1236 IRForTarget ir_for_target(decl_map, m_expr.NeedsVariableResolution(),
1237 *execution_unit_sp, *error_stream,
1238 function_name.AsCString());
1239
1240 bool ir_can_run =
1241 ir_for_target.runOnModule(*execution_unit_sp->GetModule());
1242
1243 if (!ir_can_run) {
1244 err.SetErrorString(
1245 "The expression could not be prepared to run in the target");
1246 return err;
1247 }
1248
1249 Process *process = exe_ctx.GetProcessPtr();
1250
1251 if (execution_policy != eExecutionPolicyAlways &&
1252 execution_policy != eExecutionPolicyTopLevel) {
Zachary Turner97206d52017-05-12 04:51:55 +00001253 lldb_private::Status interpret_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001254
1255 bool interpret_function_calls =
1256 !process ? false : process->CanInterpretFunctionCalls();
1257 can_interpret = IRInterpreter::CanInterpret(
1258 *execution_unit_sp->GetModule(), *execution_unit_sp->GetFunction(),
1259 interpret_error, interpret_function_calls);
1260
1261 if (!can_interpret && execution_policy == eExecutionPolicyNever) {
1262 err.SetErrorStringWithFormat("Can't run the expression locally: %s",
1263 interpret_error.AsCString());
1264 return err;
1265 }
1266 }
1267
1268 if (!process && execution_policy == eExecutionPolicyAlways) {
1269 err.SetErrorString("Expression needed to run in the target, but the "
1270 "target can't be run");
1271 return err;
1272 }
1273
1274 if (!process && execution_policy == eExecutionPolicyTopLevel) {
1275 err.SetErrorString("Top-level code needs to be inserted into a runnable "
1276 "target, but the target can't be run");
1277 return err;
1278 }
1279
1280 if (execution_policy == eExecutionPolicyAlways ||
1281 (execution_policy != eExecutionPolicyTopLevel && !can_interpret)) {
1282 if (m_expr.NeedsValidation() && process) {
1283 if (!process->GetDynamicCheckers()) {
1284 DynamicCheckerFunctions *dynamic_checkers =
1285 new DynamicCheckerFunctions();
1286
1287 DiagnosticManager install_diagnostics;
1288
1289 if (!dynamic_checkers->Install(install_diagnostics, exe_ctx)) {
1290 if (install_diagnostics.Diagnostics().size())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001291 err.SetErrorString(install_diagnostics.GetString().c_str());
Raphael Isemann262dd8c2018-09-11 13:59:47 +00001292 else
1293 err.SetErrorString("couldn't install checkers, unknown error");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001294
1295 return err;
1296 }
1297
1298 process->SetDynamicCheckers(dynamic_checkers);
1299
1300 if (log)
Raphael Isemannf75a9dc2019-02-11 21:45:33 +00001301 log->Printf("== [ClangExpressionParser::PrepareForExecution] "
1302 "Finished installing dynamic checkers ==");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001303 }
1304
1305 IRDynamicChecks ir_dynamic_checks(*process->GetDynamicCheckers(),
1306 function_name.AsCString());
1307
1308 llvm::Module *module = execution_unit_sp->GetModule();
1309 if (!module || !ir_dynamic_checks.runOnModule(*module)) {
1310 err.SetErrorToGenericError();
1311 err.SetErrorString("Couldn't add dynamic checks to the expression");
1312 return err;
1313 }
1314
1315 if (custom_passes.LatePasses) {
1316 if (log)
1317 log->Printf("%s - Running Late IR Passes from LanguageRuntime on "
1318 "expression module '%s'",
1319 __FUNCTION__, m_expr.FunctionName());
1320
1321 custom_passes.LatePasses->run(*module);
1322 }
1323 }
1324 }
1325
1326 if (execution_policy == eExecutionPolicyAlways ||
1327 execution_policy == eExecutionPolicyTopLevel || !can_interpret) {
1328 execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);
1329 }
1330 } else {
1331 execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);
1332 }
1333
1334 return err;
1335}
1336
Zachary Turner97206d52017-05-12 04:51:55 +00001337lldb_private::Status ClangExpressionParser::RunStaticInitializers(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001338 lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx) {
Zachary Turner97206d52017-05-12 04:51:55 +00001339 lldb_private::Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001340
1341 lldbassert(execution_unit_sp.get());
1342 lldbassert(exe_ctx.HasThreadScope());
1343
1344 if (!execution_unit_sp.get()) {
1345 err.SetErrorString(
1346 "can't run static initializers for a NULL execution unit");
1347 return err;
1348 }
1349
1350 if (!exe_ctx.HasThreadScope()) {
1351 err.SetErrorString("can't run static initializers without a thread");
1352 return err;
1353 }
1354
1355 std::vector<lldb::addr_t> static_initializers;
1356
1357 execution_unit_sp->GetStaticInitializers(static_initializers);
1358
1359 for (lldb::addr_t static_initializer : static_initializers) {
1360 EvaluateExpressionOptions options;
1361
1362 lldb::ThreadPlanSP call_static_initializer(new ThreadPlanCallFunction(
1363 exe_ctx.GetThreadRef(), Address(static_initializer), CompilerType(),
1364 llvm::ArrayRef<lldb::addr_t>(), options));
1365
1366 DiagnosticManager execution_errors;
1367 lldb::ExpressionResults results =
1368 exe_ctx.GetThreadRef().GetProcess()->RunThreadPlan(
1369 exe_ctx, call_static_initializer, options, execution_errors);
1370
1371 if (results != lldb::eExpressionCompleted) {
1372 err.SetErrorStringWithFormat("couldn't run static initializer: %s",
1373 execution_errors.GetString().c_str());
1374 return err;
1375 }
1376 }
1377
1378 return err;
Sean Callananbd4dc692016-03-21 22:23:38 +00001379}