blob: bf41126dbf6131e3c49343a4c60eca561402e975 [file] [log] [blame]
Sean Callanan1a8d4092010-08-27 01:01:44 +00001//===-- ClangExpressionParser.cpp -------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000010// C Includes
11// C++ Includes
Raphael Isemannb83f9142018-08-30 20:14:22 +000012#include <cctype> // for alnum
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000013// Other libraries and framework includes
Sean Callanan1a8d4092010-08-27 01:01:44 +000014#include "clang/AST/ASTContext.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000015#include "clang/AST/ASTDiagnostic.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000016#include "clang/AST/ExternalASTSource.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000017#include "clang/Basic/DiagnosticIDs.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000018#include "clang/Basic/FileManager.h"
Jim Ingham151c0322015-09-15 21:13:50 +000019#include "clang/Basic/SourceLocation.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000020#include "clang/Basic/TargetInfo.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000021#include "clang/Basic/Version.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000022#include "clang/CodeGen/CodeGenAction.h"
23#include "clang/CodeGen/ModuleBuilder.h"
Jim Inghama1e541b2016-03-25 01:57:14 +000024#include "clang/Edit/Commit.h"
Jim Inghama1e541b2016-03-25 01:57:14 +000025#include "clang/Edit/EditedSource.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000026#include "clang/Edit/EditsReceiver.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000027#include "clang/Frontend/CompilerInstance.h"
28#include "clang/Frontend/CompilerInvocation.h"
29#include "clang/Frontend/FrontendActions.h"
30#include "clang/Frontend/FrontendDiagnostic.h"
31#include "clang/Frontend/FrontendPluginRegistry.h"
32#include "clang/Frontend/TextDiagnosticBuffer.h"
33#include "clang/Frontend/TextDiagnosticPrinter.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000034#include "clang/Lex/Preprocessor.h"
Sean Callanane2ef6e32010-09-23 03:01:22 +000035#include "clang/Parse/ParseAST.h"
Jim Inghama1e541b2016-03-25 01:57:14 +000036#include "clang/Rewrite/Core/Rewriter.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000037#include "clang/Rewrite/Frontend/FrontendActions.h"
Raphael Isemann74829732018-08-30 17:29:37 +000038#include "clang/Sema/CodeCompleteConsumer.h"
39#include "clang/Sema/Sema.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000040#include "clang/Sema/SemaConsumer.h"
41
42#include "llvm/ADT/StringRef.h"
43#include "llvm/ExecutionEngine/ExecutionEngine.h"
Sean Callanan3d654b32012-09-24 22:25:51 +000044#include "llvm/Support/Debug.h"
Rafael Espindola4609ea82013-06-26 14:10:56 +000045#include "llvm/Support/FileSystem.h"
Sean Callanan880e6802011-10-07 23:18:13 +000046#include "llvm/Support/TargetSelect.h"
Greg Clayton70b57652011-05-15 01:25:55 +000047
Greg Claytonc9a078a2016-03-24 23:50:03 +000048#pragma clang diagnostic push
49#pragma clang diagnostic ignored "-Wglobal-constructors"
Ed Mastea09ed032014-03-18 18:55:06 +000050#include "llvm/ExecutionEngine/MCJIT.h"
Greg Claytonc9a078a2016-03-24 23:50:03 +000051#pragma clang diagnostic pop
52
Chandler Carruth1e157582013-01-02 12:20:07 +000053#include "llvm/IR/LLVMContext.h"
54#include "llvm/IR/Module.h"
Greg Clayton38a61402010-12-02 23:20:03 +000055#include "llvm/Support/DynamicLibrary.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000056#include "llvm/Support/ErrorHandling.h"
Greg Clayton38a61402010-12-02 23:20:03 +000057#include "llvm/Support/Host.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000058#include "llvm/Support/MemoryBuffer.h"
Greg Clayton38a61402010-12-02 23:20:03 +000059#include "llvm/Support/Signals.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000060
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000061// Project includes
Jim Inghama1e541b2016-03-25 01:57:14 +000062#include "ClangDiagnostic.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000063#include "ClangExpressionParser.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000064
65#include "ClangASTSource.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000066#include "ClangExpressionDeclMap.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000067#include "ClangExpressionHelper.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000068#include "ClangModulesDeclVendor.h"
69#include "ClangPersistentVariables.h"
70#include "IRForTarget.h"
71
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000072#include "lldb/Core/Debugger.h"
73#include "lldb/Core/Disassembler.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000074#include "lldb/Core/Module.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000075#include "lldb/Core/StreamFile.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000076#include "lldb/Expression/IRDynamicChecks.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000077#include "lldb/Expression/IRExecutionUnit.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000078#include "lldb/Expression/IRInterpreter.h"
79#include "lldb/Host/File.h"
80#include "lldb/Host/HostInfo.h"
81#include "lldb/Symbol/ClangASTContext.h"
82#include "lldb/Symbol/SymbolVendor.h"
83#include "lldb/Target/ExecutionContext.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000084#include "lldb/Target/Language.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000085#include "lldb/Target/ObjCLanguageRuntime.h"
86#include "lldb/Target/Process.h"
87#include "lldb/Target/Target.h"
Sean Callananbd4dc692016-03-21 22:23:38 +000088#include "lldb/Target/ThreadPlanCallFunction.h"
Zachary Turner666cc0b2017-03-04 01:30:05 +000089#include "lldb/Utility/DataBufferHeap.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000090#include "lldb/Utility/LLDBAssert.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000091#include "lldb/Utility/Log.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000092#include "lldb/Utility/Stream.h"
93#include "lldb/Utility/StreamString.h"
Zachary Turner573ab902017-03-21 18:25:04 +000094#include "lldb/Utility/StringList.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000095
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 {
117 std::vector<ConstString> string_path;
118
119 for (const std::pair<IdentifierInfo *, SourceLocation> &component : path) {
120 string_path.push_back(ConstString(component.first->getName()));
Sean Callananc8278af2014-12-05 01:27:35 +0000121 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000122
123 StreamString error_stream;
124
125 ClangModulesDeclVendor::ModuleVector exported_modules;
126
127 if (!m_decl_vendor.AddModule(string_path, &exported_modules,
128 m_error_stream)) {
129 m_has_errors = true;
Sean Callananc8278af2014-12-05 01:27:35 +0000130 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000131
132 for (ClangModulesDeclVendor::ModuleID module : exported_modules) {
133 m_persistent_vars.AddHandLoadedClangModule(module);
Sean Callananc8278af2014-12-05 01:27:35 +0000134 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000135 }
136
137 bool hasErrors() { return m_has_errors; }
138
Zachary Turnerc1564272016-11-16 21:15:24 +0000139 llvm::StringRef getErrorString() { return m_error_stream.GetString(); }
Sean Callananc8278af2014-12-05 01:27:35 +0000140};
141
Kate Stoneb9c1b512016-09-06 20:57:50 +0000142class ClangDiagnosticManagerAdapter : public clang::DiagnosticConsumer {
Sean Callanan579e70c2016-03-19 00:03:59 +0000143public:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000144 ClangDiagnosticManagerAdapter()
145 : m_passthrough(new clang::TextDiagnosticBuffer) {}
Sean Callanan579e70c2016-03-19 00:03:59 +0000146
Kate Stoneb9c1b512016-09-06 20:57:50 +0000147 ClangDiagnosticManagerAdapter(
148 const std::shared_ptr<clang::TextDiagnosticBuffer> &passthrough)
149 : m_passthrough(passthrough) {}
Sean Callanan579e70c2016-03-19 00:03:59 +0000150
Kate Stoneb9c1b512016-09-06 20:57:50 +0000151 void ResetManager(DiagnosticManager *manager = nullptr) {
152 m_manager = manager;
153 }
Sean Callanan579e70c2016-03-19 00:03:59 +0000154
Kate Stoneb9c1b512016-09-06 20:57:50 +0000155 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
156 const clang::Diagnostic &Info) {
157 if (m_manager) {
158 llvm::SmallVector<char, 32> diag_str;
159 Info.FormatDiagnostic(diag_str);
160 diag_str.push_back('\0');
161 const char *data = diag_str.data();
Sean Callanan579e70c2016-03-19 00:03:59 +0000162
Kate Stoneb9c1b512016-09-06 20:57:50 +0000163 lldb_private::DiagnosticSeverity severity;
164 bool make_new_diagnostic = true;
165
166 switch (DiagLevel) {
167 case DiagnosticsEngine::Level::Fatal:
168 case DiagnosticsEngine::Level::Error:
169 severity = eDiagnosticSeverityError;
170 break;
171 case DiagnosticsEngine::Level::Warning:
172 severity = eDiagnosticSeverityWarning;
173 break;
174 case DiagnosticsEngine::Level::Remark:
175 case DiagnosticsEngine::Level::Ignored:
176 severity = eDiagnosticSeverityRemark;
177 break;
178 case DiagnosticsEngine::Level::Note:
179 m_manager->AppendMessageToDiagnostic(data);
180 make_new_diagnostic = false;
181 }
182 if (make_new_diagnostic) {
183 ClangDiagnostic *new_diagnostic =
184 new ClangDiagnostic(data, severity, Info.getID());
185 m_manager->AddDiagnostic(new_diagnostic);
186
187 // Don't store away warning fixits, since the compiler doesn't have
Adrian Prantl05097242018-04-30 16:49:04 +0000188 // enough context in an expression for the warning to be useful.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000189 // FIXME: Should we try to filter out FixIts that apply to our generated
190 // code, and not the user's expression?
191 if (severity == eDiagnosticSeverityError) {
192 size_t num_fixit_hints = Info.getNumFixItHints();
193 for (size_t i = 0; i < num_fixit_hints; i++) {
194 const clang::FixItHint &fixit = Info.getFixItHint(i);
195 if (!fixit.isNull())
196 new_diagnostic->AddFixitHint(fixit);
197 }
Sean Callanan579e70c2016-03-19 00:03:59 +0000198 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000199 }
Sean Callanan579e70c2016-03-19 00:03:59 +0000200 }
201
Kate Stoneb9c1b512016-09-06 20:57:50 +0000202 m_passthrough->HandleDiagnostic(DiagLevel, Info);
203 }
Sean Callanan579e70c2016-03-19 00:03:59 +0000204
Kate Stoneb9c1b512016-09-06 20:57:50 +0000205 void FlushDiagnostics(DiagnosticsEngine &Diags) {
206 m_passthrough->FlushDiagnostics(Diags);
207 }
Sean Callanan579e70c2016-03-19 00:03:59 +0000208
Kate Stoneb9c1b512016-09-06 20:57:50 +0000209 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
210 return new ClangDiagnosticManagerAdapter(m_passthrough);
211 }
212
213 clang::TextDiagnosticBuffer *GetPassthrough() { return m_passthrough.get(); }
Sean Callanan579e70c2016-03-19 00:03:59 +0000214
215private:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000216 DiagnosticManager *m_manager = nullptr;
217 std::shared_ptr<clang::TextDiagnosticBuffer> m_passthrough;
Sean Callanan579e70c2016-03-19 00:03:59 +0000218};
219
Sean Callanan1a8d4092010-08-27 01:01:44 +0000220//===----------------------------------------------------------------------===//
221// Implementation of ClangExpressionParser
222//===----------------------------------------------------------------------===//
223
Kate Stoneb9c1b512016-09-06 20:57:50 +0000224ClangExpressionParser::ClangExpressionParser(ExecutionContextScope *exe_scope,
225 Expression &expr,
226 bool generate_debug_info)
227 : ExpressionParser(exe_scope, expr, generate_debug_info), m_compiler(),
Adrian Prantl2305c042018-08-30 15:39:08 +0000228 m_pp_callbacks(nullptr) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000229 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
Aidan Dodds1b6785a2016-02-03 12:33:05 +0000230
Adrian Prantl05097242018-04-30 16:49:04 +0000231 // We can't compile expressions without a target. So if the exe_scope is
232 // null or doesn't have a target, then we just need to get out of here. I'll
233 // lldb_assert and not make any of the compiler objects since
Kate Stoneb9c1b512016-09-06 20:57:50 +0000234 // I can't return errors directly from the constructor. Further calls will
235 // check if the compiler was made and
236 // bag out if it wasn't.
Sagar Thakuradc1abe2016-05-13 11:04:47 +0000237
Kate Stoneb9c1b512016-09-06 20:57:50 +0000238 if (!exe_scope) {
239 lldb_assert(exe_scope, "Can't make an expression parser with a null scope.",
240 __FUNCTION__, __FILE__, __LINE__);
241 return;
242 }
Bhushan D. Attarde3592a6e2016-02-18 11:53:28 +0000243
Kate Stoneb9c1b512016-09-06 20:57:50 +0000244 lldb::TargetSP target_sp;
245 target_sp = exe_scope->CalculateTarget();
246 if (!target_sp) {
247 lldb_assert(target_sp.get(),
248 "Can't make an expression parser with a null target.",
249 __FUNCTION__, __FILE__, __LINE__);
250 return;
251 }
Bhushan D. Attarde3592a6e2016-02-18 11:53:28 +0000252
Kate Stoneb9c1b512016-09-06 20:57:50 +0000253 // 1. Create a new compiler instance.
254 m_compiler.reset(new CompilerInstance());
255 lldb::LanguageType frame_lang =
256 expr.Language(); // defaults to lldb::eLanguageTypeUnknown
257 bool overridden_target_opts = false;
258 lldb_private::LanguageRuntime *lang_rt = nullptr;
Aidan Dodds1b6785a2016-02-03 12:33:05 +0000259
Kate Stoneb9c1b512016-09-06 20:57:50 +0000260 std::string abi;
261 ArchSpec target_arch;
262 target_arch = target_sp->GetArchitecture();
Aidan Dodds1b6785a2016-02-03 12:33:05 +0000263
Kate Stoneb9c1b512016-09-06 20:57:50 +0000264 const auto target_machine = target_arch.GetMachine();
Jason Molendaa3329782014-03-29 18:54:20 +0000265
Adrian Prantl05097242018-04-30 16:49:04 +0000266 // If the expression is being evaluated in the context of an existing stack
267 // frame, we introspect to see if the language runtime is available.
Bhushan D. Attarde3592a6e2016-02-18 11:53:28 +0000268
Kate Stoneb9c1b512016-09-06 20:57:50 +0000269 lldb::StackFrameSP frame_sp = exe_scope->CalculateStackFrame();
270 lldb::ProcessSP process_sp = exe_scope->CalculateProcess();
Sagar Thakuradc1abe2016-05-13 11:04:47 +0000271
Adrian Prantl05097242018-04-30 16:49:04 +0000272 // Make sure the user hasn't provided a preferred execution language with
273 // `expression --language X -- ...`
Kate Stoneb9c1b512016-09-06 20:57:50 +0000274 if (frame_sp && frame_lang == lldb::eLanguageTypeUnknown)
275 frame_lang = frame_sp->GetLanguage();
Aidan Dodds1b6785a2016-02-03 12:33:05 +0000276
Kate Stoneb9c1b512016-09-06 20:57:50 +0000277 if (process_sp && frame_lang != lldb::eLanguageTypeUnknown) {
278 lang_rt = process_sp->GetLanguageRuntime(frame_lang);
Aidan Dodds1b6785a2016-02-03 12:33:05 +0000279 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000280 log->Printf("Frame has language of type %s",
281 Language::GetNameForLanguageType(frame_lang));
282 }
Alp Toker5f838642014-07-06 05:36:57 +0000283
Kate Stoneb9c1b512016-09-06 20:57:50 +0000284 // 2. Configure the compiler with a set of default options that are
Adrian Prantl05097242018-04-30 16:49:04 +0000285 // appropriate for most situations.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000286 if (target_arch.IsValid()) {
287 std::string triple = target_arch.GetTriple().str();
288 m_compiler->getTargetOpts().Triple = triple;
289 if (log)
290 log->Printf("Using %s as the target triple",
291 m_compiler->getTargetOpts().Triple.c_str());
292 } else {
293 // If we get here we don't have a valid target and just have to guess.
294 // Sometimes this will be ok to just use the host target triple (when we
Adrian Prantl05097242018-04-30 16:49:04 +0000295 // evaluate say "2+3", but other expressions like breakpoint conditions and
296 // other things that _are_ target specific really shouldn't just be using
297 // the host triple. In such a case the language runtime should expose an
298 // overridden options set (3), below.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000299 m_compiler->getTargetOpts().Triple = llvm::sys::getDefaultTargetTriple();
300 if (log)
301 log->Printf("Using default target triple of %s",
302 m_compiler->getTargetOpts().Triple.c_str());
303 }
Adrian Prantl05097242018-04-30 16:49:04 +0000304 // Now add some special fixes for known architectures: Any arm32 iOS
305 // environment, but not on arm64
Kate Stoneb9c1b512016-09-06 20:57:50 +0000306 if (m_compiler->getTargetOpts().Triple.find("arm64") == std::string::npos &&
307 m_compiler->getTargetOpts().Triple.find("arm") != std::string::npos &&
308 m_compiler->getTargetOpts().Triple.find("ios") != std::string::npos) {
309 m_compiler->getTargetOpts().ABI = "apcs-gnu";
310 }
311 // Supported subsets of x86
312 if (target_machine == llvm::Triple::x86 ||
313 target_machine == llvm::Triple::x86_64) {
314 m_compiler->getTargetOpts().Features.push_back("+sse");
315 m_compiler->getTargetOpts().Features.push_back("+sse2");
316 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000317
Adrian Prantl05097242018-04-30 16:49:04 +0000318 // Set the target CPU to generate code for. This will be empty for any CPU
319 // that doesn't really need to make a special
Kate Stoneb9c1b512016-09-06 20:57:50 +0000320 // CPU string.
321 m_compiler->getTargetOpts().CPU = target_arch.GetClangTargetCPU();
Ewan Crawford7648dd32016-03-10 12:38:55 +0000322
Kate Stoneb9c1b512016-09-06 20:57:50 +0000323 // Set the target ABI
324 abi = GetClangTargetABI(target_arch);
325 if (!abi.empty())
326 m_compiler->getTargetOpts().ABI = abi;
327
328 // 3. Now allow the runtime to provide custom configuration options for the
Adrian Prantl05097242018-04-30 16:49:04 +0000329 // target. In this case, a specialized language runtime is available and we
330 // can query it for extra options. For 99% of use cases, this will not be
331 // needed and should be provided when basic platform detection is not enough.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000332 if (lang_rt)
333 overridden_target_opts =
334 lang_rt->GetOverrideExprOptions(m_compiler->getTargetOpts());
335
336 if (overridden_target_opts)
Pavel Labath6302bf62017-02-13 11:03:17 +0000337 if (log && log->GetVerbose()) {
338 LLDB_LOGV(
339 log, "Using overridden target options for the expression evaluation");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000340
341 auto opts = m_compiler->getTargetOpts();
Pavel Labath6302bf62017-02-13 11:03:17 +0000342 LLDB_LOGV(log, "Triple: '{0}'", opts.Triple);
343 LLDB_LOGV(log, "CPU: '{0}'", opts.CPU);
344 LLDB_LOGV(log, "FPMath: '{0}'", opts.FPMath);
345 LLDB_LOGV(log, "ABI: '{0}'", opts.ABI);
346 LLDB_LOGV(log, "LinkerVersion: '{0}'", opts.LinkerVersion);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000347 StringList::LogDump(log, opts.FeaturesAsWritten, "FeaturesAsWritten");
348 StringList::LogDump(log, opts.Features, "Features");
Sean Callananc7b65062011-11-07 23:35:40 +0000349 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000350
Kate Stoneb9c1b512016-09-06 20:57:50 +0000351 // 4. Create and install the target on the compiler.
352 m_compiler->createDiagnostics();
353 auto target_info = TargetInfo::CreateTargetInfo(
354 m_compiler->getDiagnostics(), m_compiler->getInvocation().TargetOpts);
355 if (log) {
356 log->Printf("Using SIMD alignment: %d", target_info->getSimdDefaultAlign());
357 log->Printf("Target datalayout string: '%s'",
358 target_info->getDataLayout().getStringRepresentation().c_str());
359 log->Printf("Target ABI: '%s'", target_info->getABI().str().c_str());
360 log->Printf("Target vector alignment: %d",
361 target_info->getMaxVectorAlign());
362 }
363 m_compiler->setTarget(target_info);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000364
Kate Stoneb9c1b512016-09-06 20:57:50 +0000365 assert(m_compiler->hasTarget());
Tamas Berghammerdccbfaf2015-03-31 10:21:50 +0000366
Kate Stoneb9c1b512016-09-06 20:57:50 +0000367 // 5. Set language options.
368 lldb::LanguageType language = expr.Language();
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000369
Kate Stoneb9c1b512016-09-06 20:57:50 +0000370 switch (language) {
371 case lldb::eLanguageTypeC:
372 case lldb::eLanguageTypeC89:
373 case lldb::eLanguageTypeC99:
374 case lldb::eLanguageTypeC11:
375 // FIXME: the following language option is a temporary workaround,
376 // to "ask for C, get C++."
Adrian Prantl05097242018-04-30 16:49:04 +0000377 // For now, the expression parser must use C++ anytime the language is a C
378 // family language, because the expression parser uses features of C++ to
379 // capture values.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000380 m_compiler->getLangOpts().CPlusPlus = true;
381 break;
382 case lldb::eLanguageTypeObjC:
383 m_compiler->getLangOpts().ObjC1 = true;
384 m_compiler->getLangOpts().ObjC2 = true;
385 // FIXME: the following language option is a temporary workaround,
386 // to "ask for ObjC, get ObjC++" (see comment above).
387 m_compiler->getLangOpts().CPlusPlus = true;
Davide Italiano89419f82017-12-15 00:50:43 +0000388
389 // Clang now sets as default C++14 as the default standard (with
390 // GNU extensions), so we do the same here to avoid mismatches that
Adrian Prantl05097242018-04-30 16:49:04 +0000391 // cause compiler error when evaluating expressions (e.g. nullptr not found
392 // as it's a C++11 feature). Currently lldb evaluates C++14 as C++11 (see
393 // two lines below) so we decide to be consistent with that, but this could
394 // be re-evaluated in the future.
Davide Italiano89419f82017-12-15 00:50:43 +0000395 m_compiler->getLangOpts().CPlusPlus11 = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000396 break;
397 case lldb::eLanguageTypeC_plus_plus:
398 case lldb::eLanguageTypeC_plus_plus_11:
399 case lldb::eLanguageTypeC_plus_plus_14:
400 m_compiler->getLangOpts().CPlusPlus11 = true;
401 m_compiler->getHeaderSearchOpts().UseLibcxx = true;
402 LLVM_FALLTHROUGH;
403 case lldb::eLanguageTypeC_plus_plus_03:
404 m_compiler->getLangOpts().CPlusPlus = true;
405 // FIXME: the following language option is a temporary workaround,
Adrian Prantl05097242018-04-30 16:49:04 +0000406 // to "ask for C++, get ObjC++". Apple hopes to remove this requirement on
407 // non-Apple platforms, but for now it is needed.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000408 m_compiler->getLangOpts().ObjC1 = true;
409 break;
410 case lldb::eLanguageTypeObjC_plus_plus:
411 case lldb::eLanguageTypeUnknown:
412 default:
413 m_compiler->getLangOpts().ObjC1 = true;
414 m_compiler->getLangOpts().ObjC2 = true;
415 m_compiler->getLangOpts().CPlusPlus = true;
416 m_compiler->getLangOpts().CPlusPlus11 = true;
417 m_compiler->getHeaderSearchOpts().UseLibcxx = true;
418 break;
419 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000420
Kate Stoneb9c1b512016-09-06 20:57:50 +0000421 m_compiler->getLangOpts().Bool = true;
422 m_compiler->getLangOpts().WChar = true;
423 m_compiler->getLangOpts().Blocks = true;
424 m_compiler->getLangOpts().DebuggerSupport =
425 true; // Features specifically for debugger clients
426 if (expr.DesiredResultType() == Expression::eResultTypeId)
427 m_compiler->getLangOpts().DebuggerCastResultToId = true;
428
429 m_compiler->getLangOpts().CharIsSigned =
430 ArchSpec(m_compiler->getTargetOpts().Triple.c_str())
431 .CharIsSignedByDefault();
432
Adrian Prantl05097242018-04-30 16:49:04 +0000433 // Spell checking is a nice feature, but it ends up completing a lot of types
434 // that we didn't strictly speaking need to complete. As a result, we spend a
435 // long time parsing and importing debug information.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000436 m_compiler->getLangOpts().SpellChecking = false;
437
438 if (process_sp && m_compiler->getLangOpts().ObjC1) {
439 if (process_sp->GetObjCLanguageRuntime()) {
440 if (process_sp->GetObjCLanguageRuntime()->GetRuntimeVersion() ==
441 ObjCLanguageRuntime::ObjCRuntimeVersions::eAppleObjC_V2)
442 m_compiler->getLangOpts().ObjCRuntime.set(ObjCRuntime::MacOSX,
443 VersionTuple(10, 7));
444 else
445 m_compiler->getLangOpts().ObjCRuntime.set(ObjCRuntime::FragileMacOSX,
446 VersionTuple(10, 7));
447
448 if (process_sp->GetObjCLanguageRuntime()->HasNewLiteralsAndIndexing())
449 m_compiler->getLangOpts().DebuggerObjCLiteral = true;
Sean Callananc3a16002011-01-17 23:42:46 +0000450 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000451 }
Greg Claytonf83f32d2011-01-15 01:32:14 +0000452
Kate Stoneb9c1b512016-09-06 20:57:50 +0000453 m_compiler->getLangOpts().ThreadsafeStatics = false;
454 m_compiler->getLangOpts().AccessControl =
455 false; // Debuggers get universal access
456 m_compiler->getLangOpts().DollarIdents =
457 true; // $ indicates a persistent variable name
Raphael Isemannd424c2a2018-08-30 20:56:58 +0000458 // We enable all builtin functions beside the builtins from libc/libm (e.g.
459 // 'fopen'). Those libc functions are already correctly handled by LLDB, and
460 // additionally enabling them as expandable builtins is breaking Clang.
461 m_compiler->getLangOpts().NoBuiltin = true;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000462
Kate Stoneb9c1b512016-09-06 20:57:50 +0000463 // Set CodeGen options
464 m_compiler->getCodeGenOpts().EmitDeclMetadata = true;
465 m_compiler->getCodeGenOpts().InstrumentFunctions = false;
466 m_compiler->getCodeGenOpts().DisableFPElim = true;
467 m_compiler->getCodeGenOpts().OmitLeafFramePointer = false;
468 if (generate_debug_info)
469 m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::FullDebugInfo);
470 else
471 m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::NoDebugInfo);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000472
Kate Stoneb9c1b512016-09-06 20:57:50 +0000473 // Disable some warnings.
474 m_compiler->getDiagnostics().setSeverityForGroup(
475 clang::diag::Flavor::WarningOrError, "unused-value",
476 clang::diag::Severity::Ignored, SourceLocation());
477 m_compiler->getDiagnostics().setSeverityForGroup(
478 clang::diag::Flavor::WarningOrError, "odr",
479 clang::diag::Severity::Ignored, SourceLocation());
Alp Toker10933d12014-06-12 11:14:32 +0000480
Kate Stoneb9c1b512016-09-06 20:57:50 +0000481 // Inform the target of the language options
482 //
483 // FIXME: We shouldn't need to do this, the target should be immutable once
484 // created. This complexity should be lifted elsewhere.
485 m_compiler->getTarget().adjust(m_compiler->getLangOpts());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000486
Kate Stoneb9c1b512016-09-06 20:57:50 +0000487 // 6. Set up the diagnostic buffer for reporting errors
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000488
Kate Stoneb9c1b512016-09-06 20:57:50 +0000489 m_compiler->getDiagnostics().setClient(new ClangDiagnosticManagerAdapter);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000490
Kate Stoneb9c1b512016-09-06 20:57:50 +0000491 // 7. Set up the source management objects inside the compiler
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000492
Kate Stoneb9c1b512016-09-06 20:57:50 +0000493 clang::FileSystemOptions file_system_options;
494 m_file_manager.reset(new clang::FileManager(file_system_options));
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000495
Kate Stoneb9c1b512016-09-06 20:57:50 +0000496 if (!m_compiler->hasSourceManager())
497 m_compiler->createSourceManager(*m_file_manager.get());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000498
Kate Stoneb9c1b512016-09-06 20:57:50 +0000499 m_compiler->createFileManager();
500 m_compiler->createPreprocessor(TU_Complete);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000501
Kate Stoneb9c1b512016-09-06 20:57:50 +0000502 if (ClangModulesDeclVendor *decl_vendor =
503 target_sp->GetClangModulesDeclVendor()) {
504 ClangPersistentVariables *clang_persistent_vars =
505 llvm::cast<ClangPersistentVariables>(
506 target_sp->GetPersistentExpressionStateForLanguage(
507 lldb::eLanguageTypeC));
508 std::unique_ptr<PPCallbacks> pp_callbacks(
509 new LLDBPreprocessorCallbacks(*decl_vendor, *clang_persistent_vars));
510 m_pp_callbacks =
511 static_cast<LLDBPreprocessorCallbacks *>(pp_callbacks.get());
512 m_compiler->getPreprocessor().addPPCallbacks(std::move(pp_callbacks));
513 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000514
Adrian Prantl05097242018-04-30 16:49:04 +0000515 // 8. Most of this we get from the CompilerInstance, but we also want to give
516 // the context an ExternalASTSource.
Raphael Isemann778b3082018-08-23 20:40:45 +0000517
518 auto &PP = m_compiler->getPreprocessor();
519 auto &builtin_context = PP.getBuiltinInfo();
520 builtin_context.initializeBuiltins(PP.getIdentifierTable(),
521 m_compiler->getLangOpts());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000522
Raphael Isemann596709d2018-08-27 15:18:33 +0000523 m_compiler->createASTContext();
524 clang::ASTContext &ast_context = m_compiler->getASTContext();
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000525
Kate Stoneb9c1b512016-09-06 20:57:50 +0000526 ClangExpressionHelper *type_system_helper =
527 dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
528 ClangExpressionDeclMap *decl_map = type_system_helper->DeclMap();
Sean Callanan1a8d4092010-08-27 01:01:44 +0000529
Kate Stoneb9c1b512016-09-06 20:57:50 +0000530 if (decl_map) {
531 llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> ast_source(
532 decl_map->CreateProxy());
Raphael Isemann596709d2018-08-27 15:18:33 +0000533 decl_map->InstallASTContext(ast_context, m_compiler->getFileManager());
534 ast_context.setExternalSource(ast_source);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000535 }
536
537 m_ast_context.reset(
538 new ClangASTContext(m_compiler->getTargetOpts().Triple.c_str()));
Raphael Isemann596709d2018-08-27 15:18:33 +0000539 m_ast_context->setASTContext(&ast_context);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000540
541 std::string module_name("$__lldb_module");
542
543 m_llvm_context.reset(new LLVMContext());
544 m_code_generator.reset(CreateLLVMCodeGen(
545 m_compiler->getDiagnostics(), module_name,
546 m_compiler->getHeaderSearchOpts(), m_compiler->getPreprocessorOpts(),
547 m_compiler->getCodeGenOpts(), *m_llvm_context));
Sean Callanan1a8d4092010-08-27 01:01:44 +0000548}
549
Kate Stoneb9c1b512016-09-06 20:57:50 +0000550ClangExpressionParser::~ClangExpressionParser() {}
Sean Callanan1a8d4092010-08-27 01:01:44 +0000551
Raphael Isemann74829732018-08-30 17:29:37 +0000552namespace {
553
554//----------------------------------------------------------------------
555/// @class CodeComplete
556///
557/// A code completion consumer for the clang Sema that is responsible for
558/// creating the completion suggestions when a user requests completion
559/// of an incomplete `expr` invocation.
560//----------------------------------------------------------------------
561class CodeComplete : public CodeCompleteConsumer {
Raphael Isemann39ec6e72018-08-30 19:47:53 +0000562 CodeCompletionTUInfo m_info;
Raphael Isemann74829732018-08-30 17:29:37 +0000563
Raphael Isemann39ec6e72018-08-30 19:47:53 +0000564 std::string m_expr;
565 unsigned m_position = 0;
Raphael Isemannc11a7802018-08-30 21:26:32 +0000566 CompletionRequest &m_request;
Raphael Isemann74829732018-08-30 17:29:37 +0000567
568 /// Returns true if the given character can be used in an identifier.
569 /// This also returns true for numbers because for completion we usually
570 /// just iterate backwards over iterators.
571 ///
572 /// Note: lldb uses '$' in its internal identifiers, so we also allow this.
573 static bool IsIdChar(char c) {
574 return c == '_' || std::isalnum(c) || c == '$';
575 }
576
577 /// Returns true if the given character is used to separate arguments
578 /// in the command line of lldb.
579 static bool IsTokenSeparator(char c) { return c == ' ' || c == '\t'; }
580
581 /// Drops all tokens in front of the expression that are unrelated for
582 /// the completion of the cmd line. 'unrelated' means here that the token
583 /// is not interested for the lldb completion API result.
584 StringRef dropUnrelatedFrontTokens(StringRef cmd) {
585 if (cmd.empty())
586 return cmd;
587
588 // If we are at the start of a word, then all tokens are unrelated to
589 // the current completion logic.
590 if (IsTokenSeparator(cmd.back()))
591 return StringRef();
592
593 // Remove all previous tokens from the string as they are unrelated
594 // to completing the current token.
595 StringRef to_remove = cmd;
596 while (!to_remove.empty() && !IsTokenSeparator(to_remove.back())) {
597 to_remove = to_remove.drop_back();
598 }
599 cmd = cmd.drop_front(to_remove.size());
600
601 return cmd;
602 }
603
604 /// Removes the last identifier token from the given cmd line.
605 StringRef removeLastToken(StringRef cmd) {
606 while (!cmd.empty() && IsIdChar(cmd.back())) {
607 cmd = cmd.drop_back();
608 }
609 return cmd;
610 }
611
612 /// Attemps to merge the given completion from the given position into the
613 /// existing command. Returns the completion string that can be returned to
614 /// the lldb completion API.
615 std::string mergeCompletion(StringRef existing, unsigned pos,
616 StringRef completion) {
617 StringRef existing_command = existing.substr(0, pos);
618 // We rewrite the last token with the completion, so let's drop that
619 // token from the command.
620 existing_command = removeLastToken(existing_command);
621 // We also should remove all previous tokens from the command as they
622 // would otherwise be added to the completion that already has the
623 // completion.
624 existing_command = dropUnrelatedFrontTokens(existing_command);
625 return existing_command.str() + completion.str();
626 }
627
628public:
629 /// Constructs a CodeComplete consumer that can be attached to a Sema.
630 /// @param[out] matches
631 /// The list of matches that the lldb completion API expects as a result.
632 /// This may already contain matches, so it's only allowed to append
633 /// to this variable.
634 /// @param[out] expr
635 /// The whole expression string that we are currently parsing. This
636 /// string needs to be equal to the input the user typed, and NOT the
637 /// final code that Clang is parsing.
638 /// @param[out] position
639 /// The character position of the user cursor in the `expr` parameter.
640 ///
Raphael Isemannc11a7802018-08-30 21:26:32 +0000641 CodeComplete(CompletionRequest &request, std::string expr, unsigned position)
Raphael Isemann74829732018-08-30 17:29:37 +0000642 : CodeCompleteConsumer(CodeCompleteOptions(), false),
Raphael Isemann39ec6e72018-08-30 19:47:53 +0000643 m_info(std::make_shared<GlobalCodeCompletionAllocator>()), m_expr(expr),
Raphael Isemannc11a7802018-08-30 21:26:32 +0000644 m_position(position), m_request(request) {}
Raphael Isemann74829732018-08-30 17:29:37 +0000645
646 /// Deregisters and destroys this code-completion consumer.
647 virtual ~CodeComplete() {}
648
649 /// \name Code-completion filtering
650 /// Check if the result should be filtered out.
651 bool isResultFilteredOut(StringRef Filter,
652 CodeCompletionResult Result) override {
653 // This code is mostly copied from CodeCompleteConsumer.
654 switch (Result.Kind) {
655 case CodeCompletionResult::RK_Declaration:
656 return !(
657 Result.Declaration->getIdentifier() &&
658 Result.Declaration->getIdentifier()->getName().startswith(Filter));
659 case CodeCompletionResult::RK_Keyword:
660 return !StringRef(Result.Keyword).startswith(Filter);
661 case CodeCompletionResult::RK_Macro:
662 return !Result.Macro->getName().startswith(Filter);
663 case CodeCompletionResult::RK_Pattern:
664 return !StringRef(Result.Pattern->getAsString()).startswith(Filter);
665 }
666 // If we trigger this assert or the above switch yields a warning, then
667 // CodeCompletionResult has been enhanced with more kinds of completion
668 // results. Expand the switch above in this case.
669 assert(false && "Unknown completion result type?");
670 // If we reach this, then we should just ignore whatever kind of unknown
671 // result we got back. We probably can't turn it into any kind of useful
672 // completion suggestion with the existing code.
673 return true;
674 }
675
676 /// \name Code-completion callbacks
677 /// Process the finalized code-completion results.
678 void ProcessCodeCompleteResults(Sema &SemaRef, CodeCompletionContext Context,
679 CodeCompletionResult *Results,
680 unsigned NumResults) override {
681
682 // The Sema put the incomplete token we try to complete in here during
683 // lexing, so we need to retrieve it here to know what we are completing.
684 StringRef Filter = SemaRef.getPreprocessor().getCodeCompletionFilter();
685
686 // Iterate over all the results. Filter out results we don't want and
687 // process the rest.
688 for (unsigned I = 0; I != NumResults; ++I) {
689 // Filter the results with the information from the Sema.
690 if (!Filter.empty() && isResultFilteredOut(Filter, Results[I]))
691 continue;
692
693 CodeCompletionResult &R = Results[I];
694 std::string ToInsert;
695 // Handle the different completion kinds that come from the Sema.
696 switch (R.Kind) {
697 case CodeCompletionResult::RK_Declaration: {
698 const NamedDecl *D = R.Declaration;
699 ToInsert = R.Declaration->getNameAsString();
700 // If we have a function decl that has no arguments we want to
701 // complete the empty parantheses for the user. If the function has
702 // arguments, we at least complete the opening bracket.
703 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(D)) {
704 if (F->getNumParams() == 0)
705 ToInsert += "()";
706 else
707 ToInsert += "(";
708 }
Raphael Isemann20892fb2018-08-30 20:19:57 +0000709 // If we try to complete a namespace, then we can directly append
Raphael Isemann74829732018-08-30 17:29:37 +0000710 // the '::'.
711 if (const NamespaceDecl *N = dyn_cast<NamespaceDecl>(D)) {
712 if (!N->isAnonymousNamespace())
713 ToInsert += "::";
714 }
715 break;
716 }
717 case CodeCompletionResult::RK_Keyword:
718 ToInsert = R.Keyword;
719 break;
720 case CodeCompletionResult::RK_Macro:
Raphael Isemann74829732018-08-30 17:29:37 +0000721 ToInsert = R.Macro->getName().str();
722 break;
723 case CodeCompletionResult::RK_Pattern:
724 ToInsert = R.Pattern->getTypedText();
725 break;
726 }
727 // At this point all information is in the ToInsert string.
728
729 // We also filter some internal lldb identifiers here. The user
730 // shouldn't see these.
731 if (StringRef(ToInsert).startswith("$__lldb_"))
732 continue;
733 if (!ToInsert.empty()) {
734 // Merge the suggested Token into the existing command line to comply
735 // with the kind of result the lldb API expects.
736 std::string CompletionSuggestion =
Raphael Isemann39ec6e72018-08-30 19:47:53 +0000737 mergeCompletion(m_expr, m_position, ToInsert);
Raphael Isemannc11a7802018-08-30 21:26:32 +0000738 m_request.AddCompletion(CompletionSuggestion);
Raphael Isemann74829732018-08-30 17:29:37 +0000739 }
740 }
741 }
742
743 /// \param S the semantic-analyzer object for which code-completion is being
744 /// done.
745 ///
746 /// \param CurrentArg the index of the current argument.
747 ///
748 /// \param Candidates an array of overload candidates.
749 ///
750 /// \param NumCandidates the number of overload candidates
751 void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
752 OverloadCandidate *Candidates,
753 unsigned NumCandidates,
754 SourceLocation OpenParLoc) override {
755 // At the moment we don't filter out any overloaded candidates.
756 }
757
758 CodeCompletionAllocator &getAllocator() override {
Raphael Isemann39ec6e72018-08-30 19:47:53 +0000759 return m_info.getAllocator();
Raphael Isemann74829732018-08-30 17:29:37 +0000760 }
761
Raphael Isemann39ec6e72018-08-30 19:47:53 +0000762 CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return m_info; }
Raphael Isemann74829732018-08-30 17:29:37 +0000763};
764} // namespace
765
Raphael Isemannc11a7802018-08-30 21:26:32 +0000766bool ClangExpressionParser::Complete(CompletionRequest &request, unsigned line,
Raphael Isemann74829732018-08-30 17:29:37 +0000767 unsigned pos, unsigned typed_pos) {
768 DiagnosticManager mgr;
769 // We need the raw user expression here because that's what the CodeComplete
770 // class uses to provide completion suggestions.
771 // However, the `Text` method only gives us the transformed expression here.
772 // To actually get the raw user input here, we have to cast our expression to
773 // the LLVMUserExpression which exposes the right API. This should never fail
774 // as we always have a ClangUserExpression whenever we call this.
775 LLVMUserExpression &llvm_expr = *static_cast<LLVMUserExpression *>(&m_expr);
Raphael Isemannc11a7802018-08-30 21:26:32 +0000776 CodeComplete CC(request, llvm_expr.GetUserText(), typed_pos);
Raphael Isemann74829732018-08-30 17:29:37 +0000777 // We don't need a code generator for parsing.
778 m_code_generator.reset();
779 // Start parsing the expression with our custom code completion consumer.
780 ParseInternal(mgr, &CC, line, pos);
781 return true;
782}
783
Kate Stoneb9c1b512016-09-06 20:57:50 +0000784unsigned ClangExpressionParser::Parse(DiagnosticManager &diagnostic_manager) {
Raphael Isemann74829732018-08-30 17:29:37 +0000785 return ParseInternal(diagnostic_manager);
786}
787
788unsigned
789ClangExpressionParser::ParseInternal(DiagnosticManager &diagnostic_manager,
790 CodeCompleteConsumer *completion_consumer,
791 unsigned completion_line,
792 unsigned completion_column) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000793 ClangDiagnosticManagerAdapter *adapter =
794 static_cast<ClangDiagnosticManagerAdapter *>(
795 m_compiler->getDiagnostics().getClient());
796 clang::TextDiagnosticBuffer *diag_buf = adapter->GetPassthrough();
797 diag_buf->FlushDiagnostics(m_compiler->getDiagnostics());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000798
Kate Stoneb9c1b512016-09-06 20:57:50 +0000799 adapter->ResetManager(&diagnostic_manager);
Sean Callanan579e70c2016-03-19 00:03:59 +0000800
Kate Stoneb9c1b512016-09-06 20:57:50 +0000801 const char *expr_text = m_expr.Text();
Rafael Espindola9cb97b62014-05-21 15:08:27 +0000802
Kate Stoneb9c1b512016-09-06 20:57:50 +0000803 clang::SourceManager &source_mgr = m_compiler->getSourceManager();
804 bool created_main_file = false;
Raphael Isemann74829732018-08-30 17:29:37 +0000805
806 // Clang wants to do completion on a real file known by Clang's file manager,
807 // so we have to create one to make this work.
808 // TODO: We probably could also simulate to Clang's file manager that there
809 // is a real file that contains our code.
810 bool should_create_file = completion_consumer != nullptr;
811
812 // We also want a real file on disk if we generate full debug info.
813 should_create_file |= m_compiler->getCodeGenOpts().getDebugInfo() ==
814 codegenoptions::FullDebugInfo;
815
816 if (should_create_file) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000817 int temp_fd = -1;
818 llvm::SmallString<PATH_MAX> result_path;
Pavel Labath60f028f2018-06-19 15:09:07 +0000819 if (FileSpec tmpdir_file_spec = HostInfo::GetProcessTempDir()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000820 tmpdir_file_spec.AppendPathComponent("lldb-%%%%%%.expr");
821 std::string temp_source_path = tmpdir_file_spec.GetPath();
822 llvm::sys::fs::createUniqueFile(temp_source_path, temp_fd, result_path);
823 } else {
824 llvm::sys::fs::createTemporaryFile("lldb", "expr", temp_fd, result_path);
825 }
826
827 if (temp_fd != -1) {
828 lldb_private::File file(temp_fd, true);
829 const size_t expr_text_len = strlen(expr_text);
830 size_t bytes_written = expr_text_len;
831 if (file.Write(expr_text, bytes_written).Success()) {
832 if (bytes_written == expr_text_len) {
833 file.Close();
834 source_mgr.setMainFileID(
835 source_mgr.createFileID(m_file_manager->getFile(result_path),
836 SourceLocation(), SrcMgr::C_User));
837 created_main_file = true;
Greg Clayton23f8c952014-03-24 23:10:19 +0000838 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000839 }
Greg Clayton23f8c952014-03-24 23:10:19 +0000840 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000841 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000842
Kate Stoneb9c1b512016-09-06 20:57:50 +0000843 if (!created_main_file) {
844 std::unique_ptr<MemoryBuffer> memory_buffer =
845 MemoryBuffer::getMemBufferCopy(expr_text, __FUNCTION__);
846 source_mgr.setMainFileID(source_mgr.createFileID(std::move(memory_buffer)));
847 }
848
849 diag_buf->BeginSourceFile(m_compiler->getLangOpts(),
850 &m_compiler->getPreprocessor());
851
852 ClangExpressionHelper *type_system_helper =
853 dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
854
855 ASTConsumer *ast_transformer =
856 type_system_helper->ASTTransformer(m_code_generator.get());
857
858 if (ClangExpressionDeclMap *decl_map = type_system_helper->DeclMap())
859 decl_map->InstallCodeGenerator(m_code_generator.get());
860
Raphael Isemann74829732018-08-30 17:29:37 +0000861 // If we want to parse for code completion, we need to attach our code
862 // completion consumer to the Sema and specify a completion position.
863 // While parsing the Sema will call this consumer with the provided
864 // completion suggestions.
865 if (completion_consumer) {
866 auto main_file = source_mgr.getFileEntryForID(source_mgr.getMainFileID());
867 auto &PP = m_compiler->getPreprocessor();
868 // Lines and columns start at 1 in Clang, but code completion positions are
869 // indexed from 0, so we need to add 1 to the line and column here.
870 ++completion_line;
871 ++completion_column;
872 PP.SetCodeCompletionPoint(main_file, completion_line, completion_column);
873 }
874
Kate Stoneb9c1b512016-09-06 20:57:50 +0000875 if (ast_transformer) {
876 ast_transformer->Initialize(m_compiler->getASTContext());
877 ParseAST(m_compiler->getPreprocessor(), ast_transformer,
Raphael Isemann74829732018-08-30 17:29:37 +0000878 m_compiler->getASTContext(), false, TU_Complete,
879 completion_consumer);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000880 } else {
881 m_code_generator->Initialize(m_compiler->getASTContext());
882 ParseAST(m_compiler->getPreprocessor(), m_code_generator.get(),
Raphael Isemann74829732018-08-30 17:29:37 +0000883 m_compiler->getASTContext(), false, TU_Complete,
884 completion_consumer);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000885 }
886
887 diag_buf->EndSourceFile();
888
889 unsigned num_errors = diag_buf->getNumErrors();
890
891 if (m_pp_callbacks && m_pp_callbacks->hasErrors()) {
892 num_errors++;
Zachary Turnere2411fa2016-11-12 19:12:56 +0000893 diagnostic_manager.PutString(eDiagnosticSeverityError,
894 "while importing modules:");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000895 diagnostic_manager.AppendMessageToDiagnostic(
Zachary Turnerc1564272016-11-16 21:15:24 +0000896 m_pp_callbacks->getErrorString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000897 }
898
899 if (!num_errors) {
900 if (type_system_helper->DeclMap() &&
901 !type_system_helper->DeclMap()->ResolveUnknownTypes()) {
902 diagnostic_manager.Printf(eDiagnosticSeverityError,
903 "Couldn't infer the type of a variable");
904 num_errors++;
Greg Clayton23f8c952014-03-24 23:10:19 +0000905 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000906 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000907
Kate Stoneb9c1b512016-09-06 20:57:50 +0000908 if (!num_errors) {
909 type_system_helper->CommitPersistentDecls();
910 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000911
Kate Stoneb9c1b512016-09-06 20:57:50 +0000912 adapter->ResetManager();
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000913
Kate Stoneb9c1b512016-09-06 20:57:50 +0000914 return num_errors;
Sean Callanan1a8d4092010-08-27 01:01:44 +0000915}
916
Sagar Thakuradc1abe2016-05-13 11:04:47 +0000917std::string
Kate Stoneb9c1b512016-09-06 20:57:50 +0000918ClangExpressionParser::GetClangTargetABI(const ArchSpec &target_arch) {
919 std::string abi;
920
921 if (target_arch.IsMIPS()) {
922 switch (target_arch.GetFlags() & ArchSpec::eMIPSABI_mask) {
923 case ArchSpec::eMIPSABI_N64:
924 abi = "n64";
925 break;
926 case ArchSpec::eMIPSABI_N32:
927 abi = "n32";
928 break;
929 case ArchSpec::eMIPSABI_O32:
930 abi = "o32";
931 break;
932 default:
933 break;
Sagar Thakuradc1abe2016-05-13 11:04:47 +0000934 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000935 }
936 return abi;
Sagar Thakuradc1abe2016-05-13 11:04:47 +0000937}
938
Kate Stoneb9c1b512016-09-06 20:57:50 +0000939bool ClangExpressionParser::RewriteExpression(
940 DiagnosticManager &diagnostic_manager) {
941 clang::SourceManager &source_manager = m_compiler->getSourceManager();
942 clang::edit::EditedSource editor(source_manager, m_compiler->getLangOpts(),
943 nullptr);
944 clang::edit::Commit commit(editor);
945 clang::Rewriter rewriter(source_manager, m_compiler->getLangOpts());
Jim Inghama1e541b2016-03-25 01:57:14 +0000946
Kate Stoneb9c1b512016-09-06 20:57:50 +0000947 class RewritesReceiver : public edit::EditsReceiver {
948 Rewriter &rewrite;
Jim Inghama1e541b2016-03-25 01:57:14 +0000949
Kate Stoneb9c1b512016-09-06 20:57:50 +0000950 public:
951 RewritesReceiver(Rewriter &in_rewrite) : rewrite(in_rewrite) {}
952
953 void insert(SourceLocation loc, StringRef text) override {
954 rewrite.InsertText(loc, text);
Jim Inghama1e541b2016-03-25 01:57:14 +0000955 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000956 void replace(CharSourceRange range, StringRef text) override {
957 rewrite.ReplaceText(range.getBegin(), rewrite.getRangeSize(range), text);
Sean Callananfc55f5d2010-09-21 00:44:12 +0000958 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000959 };
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000960
Kate Stoneb9c1b512016-09-06 20:57:50 +0000961 RewritesReceiver rewrites_receiver(rewriter);
962
963 const DiagnosticList &diagnostics = diagnostic_manager.Diagnostics();
964 size_t num_diags = diagnostics.size();
965 if (num_diags == 0)
Sean Callananfc55f5d2010-09-21 00:44:12 +0000966 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000967
968 for (const Diagnostic *diag : diagnostic_manager.Diagnostics()) {
969 const ClangDiagnostic *diagnostic = llvm::dyn_cast<ClangDiagnostic>(diag);
970 if (diagnostic && diagnostic->HasFixIts()) {
971 for (const FixItHint &fixit : diagnostic->FixIts()) {
972 // This is cobbed from clang::Rewrite::FixItRewriter.
973 if (fixit.CodeToInsert.empty()) {
974 if (fixit.InsertFromRange.isValid()) {
975 commit.insertFromRange(fixit.RemoveRange.getBegin(),
976 fixit.InsertFromRange, /*afterToken=*/false,
977 fixit.BeforePreviousInsertions);
978 } else
979 commit.remove(fixit.RemoveRange);
980 } else {
981 if (fixit.RemoveRange.isTokenRange() ||
982 fixit.RemoveRange.getBegin() != fixit.RemoveRange.getEnd())
983 commit.replace(fixit.RemoveRange, fixit.CodeToInsert);
984 else
985 commit.insert(fixit.RemoveRange.getBegin(), fixit.CodeToInsert,
986 /*afterToken=*/false, fixit.BeforePreviousInsertions);
987 }
988 }
989 }
990 }
991
992 // FIXME - do we want to try to propagate specific errors here?
993 if (!commit.isCommitable())
994 return false;
995 else if (!editor.commit(commit))
996 return false;
997
998 // Now play all the edits, and stash the result in the diagnostic manager.
999 editor.applyRewrites(rewrites_receiver);
1000 RewriteBuffer &main_file_buffer =
1001 rewriter.getEditBuffer(source_manager.getMainFileID());
1002
1003 std::string fixed_expression;
1004 llvm::raw_string_ostream out_stream(fixed_expression);
1005
1006 main_file_buffer.write(out_stream);
1007 out_stream.flush();
1008 diagnostic_manager.SetFixedExpression(fixed_expression);
1009
1010 return true;
Sean Callananfc55f5d2010-09-21 00:44:12 +00001011}
1012
Kate Stoneb9c1b512016-09-06 20:57:50 +00001013static bool FindFunctionInModule(ConstString &mangled_name,
1014 llvm::Module *module, const char *orig_name) {
1015 for (const auto &func : module->getFunctionList()) {
1016 const StringRef &name = func.getName();
1017 if (name.find(orig_name) != StringRef::npos) {
1018 mangled_name.SetString(name);
1019 return true;
Sean Callanan1a8d4092010-08-27 01:01:44 +00001020 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001021 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +00001022
Kate Stoneb9c1b512016-09-06 20:57:50 +00001023 return false;
Sean Callanan1a8d4092010-08-27 01:01:44 +00001024}
Sean Callananbd4dc692016-03-21 22:23:38 +00001025
Zachary Turner97206d52017-05-12 04:51:55 +00001026lldb_private::Status ClangExpressionParser::PrepareForExecution(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001027 lldb::addr_t &func_addr, lldb::addr_t &func_end,
1028 lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx,
1029 bool &can_interpret, ExecutionPolicy execution_policy) {
1030 func_addr = LLDB_INVALID_ADDRESS;
1031 func_end = LLDB_INVALID_ADDRESS;
1032 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
1033
Zachary Turner97206d52017-05-12 04:51:55 +00001034 lldb_private::Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001035
1036 std::unique_ptr<llvm::Module> llvm_module_ap(
1037 m_code_generator->ReleaseModule());
1038
1039 if (!llvm_module_ap.get()) {
1040 err.SetErrorToGenericError();
1041 err.SetErrorString("IR doesn't contain a module");
Sean Callananbd4dc692016-03-21 22:23:38 +00001042 return err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001043 }
1044
1045 ConstString function_name;
1046
1047 if (execution_policy != eExecutionPolicyTopLevel) {
1048 // Find the actual name of the function (it's often mangled somehow)
1049
1050 if (!FindFunctionInModule(function_name, llvm_module_ap.get(),
1051 m_expr.FunctionName())) {
1052 err.SetErrorToGenericError();
1053 err.SetErrorStringWithFormat("Couldn't find %s() in the module",
1054 m_expr.FunctionName());
1055 return err;
1056 } else {
1057 if (log)
1058 log->Printf("Found function %s for %s", function_name.AsCString(),
1059 m_expr.FunctionName());
1060 }
1061 }
1062
1063 SymbolContext sc;
1064
1065 if (lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP()) {
1066 sc = frame_sp->GetSymbolContext(lldb::eSymbolContextEverything);
1067 } else if (lldb::TargetSP target_sp = exe_ctx.GetTargetSP()) {
1068 sc.target_sp = target_sp;
1069 }
1070
1071 LLVMUserExpression::IRPasses custom_passes;
1072 {
1073 auto lang = m_expr.Language();
1074 if (log)
Bruce Mitchener4ebdee02018-05-29 09:10:46 +00001075 log->Printf("%s - Current expression language is %s\n", __FUNCTION__,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001076 Language::GetNameForLanguageType(lang));
Jim Ingham22562152016-11-03 23:42:09 +00001077 lldb::ProcessSP process_sp = exe_ctx.GetProcessSP();
1078 if (process_sp && lang != lldb::eLanguageTypeUnknown) {
1079 auto runtime = process_sp->GetLanguageRuntime(lang);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001080 if (runtime)
1081 runtime->GetIRPasses(custom_passes);
1082 }
1083 }
1084
1085 if (custom_passes.EarlyPasses) {
1086 if (log)
1087 log->Printf("%s - Running Early IR Passes from LanguageRuntime on "
1088 "expression module '%s'",
1089 __FUNCTION__, m_expr.FunctionName());
1090
1091 custom_passes.EarlyPasses->run(*llvm_module_ap);
1092 }
1093
1094 execution_unit_sp.reset(
1095 new IRExecutionUnit(m_llvm_context, // handed off here
1096 llvm_module_ap, // handed off here
1097 function_name, exe_ctx.GetTargetSP(), sc,
1098 m_compiler->getTargetOpts().Features));
1099
1100 ClangExpressionHelper *type_system_helper =
1101 dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
1102 ClangExpressionDeclMap *decl_map =
1103 type_system_helper->DeclMap(); // result can be NULL
1104
1105 if (decl_map) {
1106 Stream *error_stream = NULL;
1107 Target *target = exe_ctx.GetTargetPtr();
1108 error_stream = target->GetDebugger().GetErrorFile().get();
1109
1110 IRForTarget ir_for_target(decl_map, m_expr.NeedsVariableResolution(),
1111 *execution_unit_sp, *error_stream,
1112 function_name.AsCString());
1113
1114 bool ir_can_run =
1115 ir_for_target.runOnModule(*execution_unit_sp->GetModule());
1116
1117 if (!ir_can_run) {
1118 err.SetErrorString(
1119 "The expression could not be prepared to run in the target");
1120 return err;
1121 }
1122
1123 Process *process = exe_ctx.GetProcessPtr();
1124
1125 if (execution_policy != eExecutionPolicyAlways &&
1126 execution_policy != eExecutionPolicyTopLevel) {
Zachary Turner97206d52017-05-12 04:51:55 +00001127 lldb_private::Status interpret_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001128
1129 bool interpret_function_calls =
1130 !process ? false : process->CanInterpretFunctionCalls();
1131 can_interpret = IRInterpreter::CanInterpret(
1132 *execution_unit_sp->GetModule(), *execution_unit_sp->GetFunction(),
1133 interpret_error, interpret_function_calls);
1134
1135 if (!can_interpret && execution_policy == eExecutionPolicyNever) {
1136 err.SetErrorStringWithFormat("Can't run the expression locally: %s",
1137 interpret_error.AsCString());
1138 return err;
1139 }
1140 }
1141
1142 if (!process && execution_policy == eExecutionPolicyAlways) {
1143 err.SetErrorString("Expression needed to run in the target, but the "
1144 "target can't be run");
1145 return err;
1146 }
1147
1148 if (!process && execution_policy == eExecutionPolicyTopLevel) {
1149 err.SetErrorString("Top-level code needs to be inserted into a runnable "
1150 "target, but the target can't be run");
1151 return err;
1152 }
1153
1154 if (execution_policy == eExecutionPolicyAlways ||
1155 (execution_policy != eExecutionPolicyTopLevel && !can_interpret)) {
1156 if (m_expr.NeedsValidation() && process) {
1157 if (!process->GetDynamicCheckers()) {
1158 DynamicCheckerFunctions *dynamic_checkers =
1159 new DynamicCheckerFunctions();
1160
1161 DiagnosticManager install_diagnostics;
1162
1163 if (!dynamic_checkers->Install(install_diagnostics, exe_ctx)) {
1164 if (install_diagnostics.Diagnostics().size())
1165 err.SetErrorString("couldn't install checkers, unknown error");
1166 else
1167 err.SetErrorString(install_diagnostics.GetString().c_str());
1168
1169 return err;
1170 }
1171
1172 process->SetDynamicCheckers(dynamic_checkers);
1173
1174 if (log)
1175 log->Printf("== [ClangUserExpression::Evaluate] Finished "
1176 "installing dynamic checkers ==");
1177 }
1178
1179 IRDynamicChecks ir_dynamic_checks(*process->GetDynamicCheckers(),
1180 function_name.AsCString());
1181
1182 llvm::Module *module = execution_unit_sp->GetModule();
1183 if (!module || !ir_dynamic_checks.runOnModule(*module)) {
1184 err.SetErrorToGenericError();
1185 err.SetErrorString("Couldn't add dynamic checks to the expression");
1186 return err;
1187 }
1188
1189 if (custom_passes.LatePasses) {
1190 if (log)
1191 log->Printf("%s - Running Late IR Passes from LanguageRuntime on "
1192 "expression module '%s'",
1193 __FUNCTION__, m_expr.FunctionName());
1194
1195 custom_passes.LatePasses->run(*module);
1196 }
1197 }
1198 }
1199
1200 if (execution_policy == eExecutionPolicyAlways ||
1201 execution_policy == eExecutionPolicyTopLevel || !can_interpret) {
1202 execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);
1203 }
1204 } else {
1205 execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);
1206 }
1207
1208 return err;
1209}
1210
Zachary Turner97206d52017-05-12 04:51:55 +00001211lldb_private::Status ClangExpressionParser::RunStaticInitializers(
Kate Stoneb9c1b512016-09-06 20:57:50 +00001212 lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx) {
Zachary Turner97206d52017-05-12 04:51:55 +00001213 lldb_private::Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001214
1215 lldbassert(execution_unit_sp.get());
1216 lldbassert(exe_ctx.HasThreadScope());
1217
1218 if (!execution_unit_sp.get()) {
1219 err.SetErrorString(
1220 "can't run static initializers for a NULL execution unit");
1221 return err;
1222 }
1223
1224 if (!exe_ctx.HasThreadScope()) {
1225 err.SetErrorString("can't run static initializers without a thread");
1226 return err;
1227 }
1228
1229 std::vector<lldb::addr_t> static_initializers;
1230
1231 execution_unit_sp->GetStaticInitializers(static_initializers);
1232
1233 for (lldb::addr_t static_initializer : static_initializers) {
1234 EvaluateExpressionOptions options;
1235
1236 lldb::ThreadPlanSP call_static_initializer(new ThreadPlanCallFunction(
1237 exe_ctx.GetThreadRef(), Address(static_initializer), CompilerType(),
1238 llvm::ArrayRef<lldb::addr_t>(), options));
1239
1240 DiagnosticManager execution_errors;
1241 lldb::ExpressionResults results =
1242 exe_ctx.GetThreadRef().GetProcess()->RunThreadPlan(
1243 exe_ctx, call_static_initializer, options, execution_errors);
1244
1245 if (results != lldb::eExpressionCompleted) {
1246 err.SetErrorStringWithFormat("couldn't run static initializer: %s",
1247 execution_errors.GetString().c_str());
1248 return err;
1249 }
1250 }
1251
1252 return err;
Sean Callananbd4dc692016-03-21 22:23:38 +00001253}