blob: 4e20be79f68b713f6016566866f81662ce9668e3 [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
12// Other libraries and framework includes
Sean Callanan1a8d4092010-08-27 01:01:44 +000013#include "clang/AST/ASTContext.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000014#include "clang/AST/ASTDiagnostic.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000015#include "clang/AST/ExternalASTSource.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000016#include "clang/Basic/DiagnosticIDs.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000017#include "clang/Basic/FileManager.h"
Jim Ingham151c0322015-09-15 21:13:50 +000018#include "clang/Basic/SourceLocation.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000019#include "clang/Basic/TargetInfo.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000020#include "clang/Basic/Version.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000021#include "clang/CodeGen/CodeGenAction.h"
22#include "clang/CodeGen/ModuleBuilder.h"
Jim Inghama1e541b2016-03-25 01:57:14 +000023#include "clang/Edit/Commit.h"
Jim Inghama1e541b2016-03-25 01:57:14 +000024#include "clang/Edit/EditedSource.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000025#include "clang/Edit/EditsReceiver.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000026#include "clang/Frontend/CompilerInstance.h"
27#include "clang/Frontend/CompilerInvocation.h"
28#include "clang/Frontend/FrontendActions.h"
29#include "clang/Frontend/FrontendDiagnostic.h"
30#include "clang/Frontend/FrontendPluginRegistry.h"
31#include "clang/Frontend/TextDiagnosticBuffer.h"
32#include "clang/Frontend/TextDiagnosticPrinter.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000033#include "clang/Lex/Preprocessor.h"
Sean Callanane2ef6e32010-09-23 03:01:22 +000034#include "clang/Parse/ParseAST.h"
Jim Inghama1e541b2016-03-25 01:57:14 +000035#include "clang/Rewrite/Core/Rewriter.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000036#include "clang/Rewrite/Frontend/FrontendActions.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000037#include "clang/Sema/SemaConsumer.h"
38
39#include "llvm/ADT/StringRef.h"
40#include "llvm/ExecutionEngine/ExecutionEngine.h"
Sean Callanan3d654b32012-09-24 22:25:51 +000041#include "llvm/Support/Debug.h"
Rafael Espindola4609ea82013-06-26 14:10:56 +000042#include "llvm/Support/FileSystem.h"
Sean Callanan880e6802011-10-07 23:18:13 +000043#include "llvm/Support/TargetSelect.h"
Greg Clayton70b57652011-05-15 01:25:55 +000044
Greg Claytonc9a078a2016-03-24 23:50:03 +000045#pragma clang diagnostic push
46#pragma clang diagnostic ignored "-Wglobal-constructors"
Ed Mastea09ed032014-03-18 18:55:06 +000047#include "llvm/ExecutionEngine/MCJIT.h"
Greg Claytonc9a078a2016-03-24 23:50:03 +000048#pragma clang diagnostic pop
49
Chandler Carruth1e157582013-01-02 12:20:07 +000050#include "llvm/IR/LLVMContext.h"
51#include "llvm/IR/Module.h"
Greg Clayton38a61402010-12-02 23:20:03 +000052#include "llvm/Support/DynamicLibrary.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000053#include "llvm/Support/ErrorHandling.h"
Greg Clayton38a61402010-12-02 23:20:03 +000054#include "llvm/Support/Host.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000055#include "llvm/Support/MemoryBuffer.h"
Greg Clayton38a61402010-12-02 23:20:03 +000056#include "llvm/Support/Signals.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000057
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000058// Project includes
Jim Inghama1e541b2016-03-25 01:57:14 +000059#include "ClangDiagnostic.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000060#include "ClangExpressionParser.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000061
62#include "ClangASTSource.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000063#include "ClangExpressionDeclMap.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000064#include "ClangExpressionHelper.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000065#include "ClangModulesDeclVendor.h"
66#include "ClangPersistentVariables.h"
67#include "IRForTarget.h"
68
69#include "lldb/Core/ArchSpec.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000070#include "lldb/Core/Debugger.h"
71#include "lldb/Core/Disassembler.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000072#include "lldb/Core/Module.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000073#include "lldb/Core/StreamFile.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000074#include "lldb/Expression/IRDynamicChecks.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000075#include "lldb/Expression/IRExecutionUnit.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000076#include "lldb/Expression/IRInterpreter.h"
77#include "lldb/Host/File.h"
78#include "lldb/Host/HostInfo.h"
79#include "lldb/Symbol/ClangASTContext.h"
80#include "lldb/Symbol/SymbolVendor.h"
81#include "lldb/Target/ExecutionContext.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000082#include "lldb/Target/Language.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000083#include "lldb/Target/ObjCLanguageRuntime.h"
84#include "lldb/Target/Process.h"
85#include "lldb/Target/Target.h"
Sean Callananbd4dc692016-03-21 22:23:38 +000086#include "lldb/Target/ThreadPlanCallFunction.h"
Zachary Turner666cc0b2017-03-04 01:30:05 +000087#include "lldb/Utility/DataBufferHeap.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000088#include "lldb/Utility/LLDBAssert.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000089#include "lldb/Utility/Log.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000090#include "lldb/Utility/Stream.h"
91#include "lldb/Utility/StreamString.h"
Zachary Turner573ab902017-03-21 18:25:04 +000092#include "lldb/Utility/StringList.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000093
Sean Callanan1a8d4092010-08-27 01:01:44 +000094using namespace clang;
95using namespace llvm;
96using namespace lldb_private;
97
98//===----------------------------------------------------------------------===//
99// Utility Methods for Clang
100//===----------------------------------------------------------------------===//
101
Kate Stoneb9c1b512016-09-06 20:57:50 +0000102class ClangExpressionParser::LLDBPreprocessorCallbacks : public PPCallbacks {
103 ClangModulesDeclVendor &m_decl_vendor;
104 ClangPersistentVariables &m_persistent_vars;
105 StreamString m_error_stream;
106 bool m_has_errors = false;
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +0000107
Sean Callananc8278af2014-12-05 01:27:35 +0000108public:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000109 LLDBPreprocessorCallbacks(ClangModulesDeclVendor &decl_vendor,
110 ClangPersistentVariables &persistent_vars)
111 : m_decl_vendor(decl_vendor), m_persistent_vars(persistent_vars) {}
112
113 void moduleImport(SourceLocation import_location, clang::ModuleIdPath path,
114 const clang::Module * /*null*/) override {
115 std::vector<ConstString> string_path;
116
117 for (const std::pair<IdentifierInfo *, SourceLocation> &component : path) {
118 string_path.push_back(ConstString(component.first->getName()));
Sean Callananc8278af2014-12-05 01:27:35 +0000119 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000120
121 StreamString error_stream;
122
123 ClangModulesDeclVendor::ModuleVector exported_modules;
124
125 if (!m_decl_vendor.AddModule(string_path, &exported_modules,
126 m_error_stream)) {
127 m_has_errors = true;
Sean Callananc8278af2014-12-05 01:27:35 +0000128 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000129
130 for (ClangModulesDeclVendor::ModuleID module : exported_modules) {
131 m_persistent_vars.AddHandLoadedClangModule(module);
Sean Callananc8278af2014-12-05 01:27:35 +0000132 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000133 }
134
135 bool hasErrors() { return m_has_errors; }
136
Zachary Turnerc1564272016-11-16 21:15:24 +0000137 llvm::StringRef getErrorString() { return m_error_stream.GetString(); }
Sean Callananc8278af2014-12-05 01:27:35 +0000138};
139
Kate Stoneb9c1b512016-09-06 20:57:50 +0000140class ClangDiagnosticManagerAdapter : public clang::DiagnosticConsumer {
Sean Callanan579e70c2016-03-19 00:03:59 +0000141public:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000142 ClangDiagnosticManagerAdapter()
143 : m_passthrough(new clang::TextDiagnosticBuffer) {}
Sean Callanan579e70c2016-03-19 00:03:59 +0000144
Kate Stoneb9c1b512016-09-06 20:57:50 +0000145 ClangDiagnosticManagerAdapter(
146 const std::shared_ptr<clang::TextDiagnosticBuffer> &passthrough)
147 : m_passthrough(passthrough) {}
Sean Callanan579e70c2016-03-19 00:03:59 +0000148
Kate Stoneb9c1b512016-09-06 20:57:50 +0000149 void ResetManager(DiagnosticManager *manager = nullptr) {
150 m_manager = manager;
151 }
Sean Callanan579e70c2016-03-19 00:03:59 +0000152
Kate Stoneb9c1b512016-09-06 20:57:50 +0000153 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
154 const clang::Diagnostic &Info) {
155 if (m_manager) {
156 llvm::SmallVector<char, 32> diag_str;
157 Info.FormatDiagnostic(diag_str);
158 diag_str.push_back('\0');
159 const char *data = diag_str.data();
Sean Callanan579e70c2016-03-19 00:03:59 +0000160
Kate Stoneb9c1b512016-09-06 20:57:50 +0000161 lldb_private::DiagnosticSeverity severity;
162 bool make_new_diagnostic = true;
163
164 switch (DiagLevel) {
165 case DiagnosticsEngine::Level::Fatal:
166 case DiagnosticsEngine::Level::Error:
167 severity = eDiagnosticSeverityError;
168 break;
169 case DiagnosticsEngine::Level::Warning:
170 severity = eDiagnosticSeverityWarning;
171 break;
172 case DiagnosticsEngine::Level::Remark:
173 case DiagnosticsEngine::Level::Ignored:
174 severity = eDiagnosticSeverityRemark;
175 break;
176 case DiagnosticsEngine::Level::Note:
177 m_manager->AppendMessageToDiagnostic(data);
178 make_new_diagnostic = false;
179 }
180 if (make_new_diagnostic) {
181 ClangDiagnostic *new_diagnostic =
182 new ClangDiagnostic(data, severity, Info.getID());
183 m_manager->AddDiagnostic(new_diagnostic);
184
185 // Don't store away warning fixits, since the compiler doesn't have
186 // enough
187 // context in an expression for the warning to be useful.
188 // FIXME: Should we try to filter out FixIts that apply to our generated
189 // code, and not the user's expression?
190 if (severity == eDiagnosticSeverityError) {
191 size_t num_fixit_hints = Info.getNumFixItHints();
192 for (size_t i = 0; i < num_fixit_hints; i++) {
193 const clang::FixItHint &fixit = Info.getFixItHint(i);
194 if (!fixit.isNull())
195 new_diagnostic->AddFixitHint(fixit);
196 }
Sean Callanan579e70c2016-03-19 00:03:59 +0000197 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000198 }
Sean Callanan579e70c2016-03-19 00:03:59 +0000199 }
200
Kate Stoneb9c1b512016-09-06 20:57:50 +0000201 m_passthrough->HandleDiagnostic(DiagLevel, Info);
202 }
Sean Callanan579e70c2016-03-19 00:03:59 +0000203
Kate Stoneb9c1b512016-09-06 20:57:50 +0000204 void FlushDiagnostics(DiagnosticsEngine &Diags) {
205 m_passthrough->FlushDiagnostics(Diags);
206 }
Sean Callanan579e70c2016-03-19 00:03:59 +0000207
Kate Stoneb9c1b512016-09-06 20:57:50 +0000208 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
209 return new ClangDiagnosticManagerAdapter(m_passthrough);
210 }
211
212 clang::TextDiagnosticBuffer *GetPassthrough() { return m_passthrough.get(); }
Sean Callanan579e70c2016-03-19 00:03:59 +0000213
214private:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000215 DiagnosticManager *m_manager = nullptr;
216 std::shared_ptr<clang::TextDiagnosticBuffer> m_passthrough;
Sean Callanan579e70c2016-03-19 00:03:59 +0000217};
218
Sean Callanan1a8d4092010-08-27 01:01:44 +0000219//===----------------------------------------------------------------------===//
220// Implementation of ClangExpressionParser
221//===----------------------------------------------------------------------===//
222
Kate Stoneb9c1b512016-09-06 20:57:50 +0000223ClangExpressionParser::ClangExpressionParser(ExecutionContextScope *exe_scope,
224 Expression &expr,
225 bool generate_debug_info)
226 : ExpressionParser(exe_scope, expr, generate_debug_info), m_compiler(),
227 m_code_generator(), m_pp_callbacks(nullptr) {
228 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
Aidan Dodds1b6785a2016-02-03 12:33:05 +0000229
Kate Stoneb9c1b512016-09-06 20:57:50 +0000230 // We can't compile expressions without a target. So if the exe_scope is null
231 // or doesn't have a target,
232 // then we just need to get out of here. I'll lldb_assert and not make any of
233 // the compiler objects since
234 // 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
Kate Stoneb9c1b512016-09-06 20:57:50 +0000266 // If the expression is being evaluated in the context of an existing
267 // stack 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
Kate Stoneb9c1b512016-09-06 20:57:50 +0000272 // Make sure the user hasn't provided a preferred execution language
273 // with `expression --language X -- ...`
274 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
285 // appropriate
286 // for most situations.
287 if (target_arch.IsValid()) {
288 std::string triple = target_arch.GetTriple().str();
289 m_compiler->getTargetOpts().Triple = triple;
290 if (log)
291 log->Printf("Using %s as the target triple",
292 m_compiler->getTargetOpts().Triple.c_str());
293 } else {
294 // If we get here we don't have a valid target and just have to guess.
295 // Sometimes this will be ok to just use the host target triple (when we
296 // evaluate say "2+3", but other
297 // expressions like breakpoint conditions and other things that _are_ target
298 // specific really shouldn't just be
299 // using the host triple. In such a case the language runtime should expose
300 // an overridden options set (3),
301 // below.
302 m_compiler->getTargetOpts().Triple = llvm::sys::getDefaultTargetTriple();
303 if (log)
304 log->Printf("Using default target triple of %s",
305 m_compiler->getTargetOpts().Triple.c_str());
306 }
307 // Now add some special fixes for known architectures:
308 // Any arm32 iOS environment, but not on arm64
309 if (m_compiler->getTargetOpts().Triple.find("arm64") == std::string::npos &&
310 m_compiler->getTargetOpts().Triple.find("arm") != std::string::npos &&
311 m_compiler->getTargetOpts().Triple.find("ios") != std::string::npos) {
312 m_compiler->getTargetOpts().ABI = "apcs-gnu";
313 }
314 // Supported subsets of x86
315 if (target_machine == llvm::Triple::x86 ||
316 target_machine == llvm::Triple::x86_64) {
317 m_compiler->getTargetOpts().Features.push_back("+sse");
318 m_compiler->getTargetOpts().Features.push_back("+sse2");
319 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000320
Kate Stoneb9c1b512016-09-06 20:57:50 +0000321 // Set the target CPU to generate code for.
322 // This will be empty for any CPU that doesn't really need to make a special
323 // CPU string.
324 m_compiler->getTargetOpts().CPU = target_arch.GetClangTargetCPU();
Ewan Crawford7648dd32016-03-10 12:38:55 +0000325
Kate Stoneb9c1b512016-09-06 20:57:50 +0000326 // Set the target ABI
327 abi = GetClangTargetABI(target_arch);
328 if (!abi.empty())
329 m_compiler->getTargetOpts().ABI = abi;
330
331 // 3. Now allow the runtime to provide custom configuration options for the
332 // target.
333 // In this case, a specialized language runtime is available and we can query
334 // it for extra options.
335 // For 99% of use cases, this will not be needed and should be provided when
336 // basic platform detection is not enough.
337 if (lang_rt)
338 overridden_target_opts =
339 lang_rt->GetOverrideExprOptions(m_compiler->getTargetOpts());
340
341 if (overridden_target_opts)
Pavel Labath6302bf62017-02-13 11:03:17 +0000342 if (log && log->GetVerbose()) {
343 LLDB_LOGV(
344 log, "Using overridden target options for the expression evaluation");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000345
346 auto opts = m_compiler->getTargetOpts();
Pavel Labath6302bf62017-02-13 11:03:17 +0000347 LLDB_LOGV(log, "Triple: '{0}'", opts.Triple);
348 LLDB_LOGV(log, "CPU: '{0}'", opts.CPU);
349 LLDB_LOGV(log, "FPMath: '{0}'", opts.FPMath);
350 LLDB_LOGV(log, "ABI: '{0}'", opts.ABI);
351 LLDB_LOGV(log, "LinkerVersion: '{0}'", opts.LinkerVersion);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000352 StringList::LogDump(log, opts.FeaturesAsWritten, "FeaturesAsWritten");
353 StringList::LogDump(log, opts.Features, "Features");
354 StringList::LogDump(log, opts.Reciprocals, "Reciprocals");
Sean Callananc7b65062011-11-07 23:35:40 +0000355 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000356
Kate Stoneb9c1b512016-09-06 20:57:50 +0000357 // 4. Create and install the target on the compiler.
358 m_compiler->createDiagnostics();
359 auto target_info = TargetInfo::CreateTargetInfo(
360 m_compiler->getDiagnostics(), m_compiler->getInvocation().TargetOpts);
361 if (log) {
362 log->Printf("Using SIMD alignment: %d", target_info->getSimdDefaultAlign());
363 log->Printf("Target datalayout string: '%s'",
364 target_info->getDataLayout().getStringRepresentation().c_str());
365 log->Printf("Target ABI: '%s'", target_info->getABI().str().c_str());
366 log->Printf("Target vector alignment: %d",
367 target_info->getMaxVectorAlign());
368 }
369 m_compiler->setTarget(target_info);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000370
Kate Stoneb9c1b512016-09-06 20:57:50 +0000371 assert(m_compiler->hasTarget());
Tamas Berghammerdccbfaf2015-03-31 10:21:50 +0000372
Kate Stoneb9c1b512016-09-06 20:57:50 +0000373 // 5. Set language options.
374 lldb::LanguageType language = expr.Language();
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000375
Kate Stoneb9c1b512016-09-06 20:57:50 +0000376 switch (language) {
377 case lldb::eLanguageTypeC:
378 case lldb::eLanguageTypeC89:
379 case lldb::eLanguageTypeC99:
380 case lldb::eLanguageTypeC11:
381 // FIXME: the following language option is a temporary workaround,
382 // to "ask for C, get C++."
383 // For now, the expression parser must use C++ anytime the
384 // language is a C family language, because the expression parser
385 // uses features of C++ to capture values.
386 m_compiler->getLangOpts().CPlusPlus = true;
387 break;
388 case lldb::eLanguageTypeObjC:
389 m_compiler->getLangOpts().ObjC1 = true;
390 m_compiler->getLangOpts().ObjC2 = true;
391 // FIXME: the following language option is a temporary workaround,
392 // to "ask for ObjC, get ObjC++" (see comment above).
393 m_compiler->getLangOpts().CPlusPlus = true;
394 break;
395 case lldb::eLanguageTypeC_plus_plus:
396 case lldb::eLanguageTypeC_plus_plus_11:
397 case lldb::eLanguageTypeC_plus_plus_14:
398 m_compiler->getLangOpts().CPlusPlus11 = true;
399 m_compiler->getHeaderSearchOpts().UseLibcxx = true;
400 LLVM_FALLTHROUGH;
401 case lldb::eLanguageTypeC_plus_plus_03:
402 m_compiler->getLangOpts().CPlusPlus = true;
403 // FIXME: the following language option is a temporary workaround,
404 // to "ask for C++, get ObjC++". Apple hopes to remove this requirement
405 // on non-Apple platforms, but for now it is needed.
406 m_compiler->getLangOpts().ObjC1 = true;
407 break;
408 case lldb::eLanguageTypeObjC_plus_plus:
409 case lldb::eLanguageTypeUnknown:
410 default:
411 m_compiler->getLangOpts().ObjC1 = true;
412 m_compiler->getLangOpts().ObjC2 = true;
413 m_compiler->getLangOpts().CPlusPlus = true;
414 m_compiler->getLangOpts().CPlusPlus11 = true;
415 m_compiler->getHeaderSearchOpts().UseLibcxx = true;
416 break;
417 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000418
Kate Stoneb9c1b512016-09-06 20:57:50 +0000419 m_compiler->getLangOpts().Bool = true;
420 m_compiler->getLangOpts().WChar = true;
421 m_compiler->getLangOpts().Blocks = true;
422 m_compiler->getLangOpts().DebuggerSupport =
423 true; // Features specifically for debugger clients
424 if (expr.DesiredResultType() == Expression::eResultTypeId)
425 m_compiler->getLangOpts().DebuggerCastResultToId = true;
426
427 m_compiler->getLangOpts().CharIsSigned =
428 ArchSpec(m_compiler->getTargetOpts().Triple.c_str())
429 .CharIsSignedByDefault();
430
431 // Spell checking is a nice feature, but it ends up completing a
432 // lot of types that we didn't strictly speaking need to complete.
433 // As a result, we spend a long time parsing and importing debug
434 // information.
435 m_compiler->getLangOpts().SpellChecking = false;
436
437 if (process_sp && m_compiler->getLangOpts().ObjC1) {
438 if (process_sp->GetObjCLanguageRuntime()) {
439 if (process_sp->GetObjCLanguageRuntime()->GetRuntimeVersion() ==
440 ObjCLanguageRuntime::ObjCRuntimeVersions::eAppleObjC_V2)
441 m_compiler->getLangOpts().ObjCRuntime.set(ObjCRuntime::MacOSX,
442 VersionTuple(10, 7));
443 else
444 m_compiler->getLangOpts().ObjCRuntime.set(ObjCRuntime::FragileMacOSX,
445 VersionTuple(10, 7));
446
447 if (process_sp->GetObjCLanguageRuntime()->HasNewLiteralsAndIndexing())
448 m_compiler->getLangOpts().DebuggerObjCLiteral = true;
Sean Callananc3a16002011-01-17 23:42:46 +0000449 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000450 }
Greg Claytonf83f32d2011-01-15 01:32:14 +0000451
Kate Stoneb9c1b512016-09-06 20:57:50 +0000452 m_compiler->getLangOpts().ThreadsafeStatics = false;
453 m_compiler->getLangOpts().AccessControl =
454 false; // Debuggers get universal access
455 m_compiler->getLangOpts().DollarIdents =
456 true; // $ indicates a persistent variable name
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000457
Kate Stoneb9c1b512016-09-06 20:57:50 +0000458 // Set CodeGen options
459 m_compiler->getCodeGenOpts().EmitDeclMetadata = true;
460 m_compiler->getCodeGenOpts().InstrumentFunctions = false;
461 m_compiler->getCodeGenOpts().DisableFPElim = true;
462 m_compiler->getCodeGenOpts().OmitLeafFramePointer = false;
463 if (generate_debug_info)
464 m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::FullDebugInfo);
465 else
466 m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::NoDebugInfo);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000467
Kate Stoneb9c1b512016-09-06 20:57:50 +0000468 // Disable some warnings.
469 m_compiler->getDiagnostics().setSeverityForGroup(
470 clang::diag::Flavor::WarningOrError, "unused-value",
471 clang::diag::Severity::Ignored, SourceLocation());
472 m_compiler->getDiagnostics().setSeverityForGroup(
473 clang::diag::Flavor::WarningOrError, "odr",
474 clang::diag::Severity::Ignored, SourceLocation());
Alp Toker10933d12014-06-12 11:14:32 +0000475
Kate Stoneb9c1b512016-09-06 20:57:50 +0000476 // Inform the target of the language options
477 //
478 // FIXME: We shouldn't need to do this, the target should be immutable once
479 // created. This complexity should be lifted elsewhere.
480 m_compiler->getTarget().adjust(m_compiler->getLangOpts());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000481
Kate Stoneb9c1b512016-09-06 20:57:50 +0000482 // 6. Set up the diagnostic buffer for reporting errors
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000483
Kate Stoneb9c1b512016-09-06 20:57:50 +0000484 m_compiler->getDiagnostics().setClient(new ClangDiagnosticManagerAdapter);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000485
Kate Stoneb9c1b512016-09-06 20:57:50 +0000486 // 7. Set up the source management objects inside the compiler
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000487
Kate Stoneb9c1b512016-09-06 20:57:50 +0000488 clang::FileSystemOptions file_system_options;
489 m_file_manager.reset(new clang::FileManager(file_system_options));
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000490
Kate Stoneb9c1b512016-09-06 20:57:50 +0000491 if (!m_compiler->hasSourceManager())
492 m_compiler->createSourceManager(*m_file_manager.get());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000493
Kate Stoneb9c1b512016-09-06 20:57:50 +0000494 m_compiler->createFileManager();
495 m_compiler->createPreprocessor(TU_Complete);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000496
Kate Stoneb9c1b512016-09-06 20:57:50 +0000497 if (ClangModulesDeclVendor *decl_vendor =
498 target_sp->GetClangModulesDeclVendor()) {
499 ClangPersistentVariables *clang_persistent_vars =
500 llvm::cast<ClangPersistentVariables>(
501 target_sp->GetPersistentExpressionStateForLanguage(
502 lldb::eLanguageTypeC));
503 std::unique_ptr<PPCallbacks> pp_callbacks(
504 new LLDBPreprocessorCallbacks(*decl_vendor, *clang_persistent_vars));
505 m_pp_callbacks =
506 static_cast<LLDBPreprocessorCallbacks *>(pp_callbacks.get());
507 m_compiler->getPreprocessor().addPPCallbacks(std::move(pp_callbacks));
508 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000509
Kate Stoneb9c1b512016-09-06 20:57:50 +0000510 // 8. Most of this we get from the CompilerInstance, but we
511 // also want to give the context an ExternalASTSource.
512 m_selector_table.reset(new SelectorTable());
513 m_builtin_context.reset(new Builtin::Context());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000514
Kate Stoneb9c1b512016-09-06 20:57:50 +0000515 std::unique_ptr<clang::ASTContext> ast_context(
516 new ASTContext(m_compiler->getLangOpts(), m_compiler->getSourceManager(),
517 m_compiler->getPreprocessor().getIdentifierTable(),
518 *m_selector_table.get(), *m_builtin_context.get()));
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000519
Kate Stoneb9c1b512016-09-06 20:57:50 +0000520 ast_context->InitBuiltinTypes(m_compiler->getTarget());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000521
Kate Stoneb9c1b512016-09-06 20:57:50 +0000522 ClangExpressionHelper *type_system_helper =
523 dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
524 ClangExpressionDeclMap *decl_map = type_system_helper->DeclMap();
Sean Callanan1a8d4092010-08-27 01:01:44 +0000525
Kate Stoneb9c1b512016-09-06 20:57:50 +0000526 if (decl_map) {
527 llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> ast_source(
528 decl_map->CreateProxy());
529 decl_map->InstallASTContext(ast_context.get());
530 ast_context->setExternalSource(ast_source);
531 }
532
533 m_ast_context.reset(
534 new ClangASTContext(m_compiler->getTargetOpts().Triple.c_str()));
535 m_ast_context->setASTContext(ast_context.get());
536 m_compiler->setASTContext(ast_context.release());
537
538 std::string module_name("$__lldb_module");
539
540 m_llvm_context.reset(new LLVMContext());
541 m_code_generator.reset(CreateLLVMCodeGen(
542 m_compiler->getDiagnostics(), module_name,
543 m_compiler->getHeaderSearchOpts(), m_compiler->getPreprocessorOpts(),
544 m_compiler->getCodeGenOpts(), *m_llvm_context));
Sean Callanan1a8d4092010-08-27 01:01:44 +0000545}
546
Kate Stoneb9c1b512016-09-06 20:57:50 +0000547ClangExpressionParser::~ClangExpressionParser() {}
Sean Callanan1a8d4092010-08-27 01:01:44 +0000548
Kate Stoneb9c1b512016-09-06 20:57:50 +0000549unsigned ClangExpressionParser::Parse(DiagnosticManager &diagnostic_manager) {
550 ClangDiagnosticManagerAdapter *adapter =
551 static_cast<ClangDiagnosticManagerAdapter *>(
552 m_compiler->getDiagnostics().getClient());
553 clang::TextDiagnosticBuffer *diag_buf = adapter->GetPassthrough();
554 diag_buf->FlushDiagnostics(m_compiler->getDiagnostics());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000555
Kate Stoneb9c1b512016-09-06 20:57:50 +0000556 adapter->ResetManager(&diagnostic_manager);
Sean Callanan579e70c2016-03-19 00:03:59 +0000557
Kate Stoneb9c1b512016-09-06 20:57:50 +0000558 const char *expr_text = m_expr.Text();
Rafael Espindola9cb97b62014-05-21 15:08:27 +0000559
Kate Stoneb9c1b512016-09-06 20:57:50 +0000560 clang::SourceManager &source_mgr = m_compiler->getSourceManager();
561 bool created_main_file = false;
562 if (m_compiler->getCodeGenOpts().getDebugInfo() ==
563 codegenoptions::FullDebugInfo) {
564 int temp_fd = -1;
565 llvm::SmallString<PATH_MAX> result_path;
566 FileSpec tmpdir_file_spec;
567 if (HostInfo::GetLLDBPath(lldb::ePathTypeLLDBTempSystemDir,
568 tmpdir_file_spec)) {
569 tmpdir_file_spec.AppendPathComponent("lldb-%%%%%%.expr");
570 std::string temp_source_path = tmpdir_file_spec.GetPath();
571 llvm::sys::fs::createUniqueFile(temp_source_path, temp_fd, result_path);
572 } else {
573 llvm::sys::fs::createTemporaryFile("lldb", "expr", temp_fd, result_path);
574 }
575
576 if (temp_fd != -1) {
577 lldb_private::File file(temp_fd, true);
578 const size_t expr_text_len = strlen(expr_text);
579 size_t bytes_written = expr_text_len;
580 if (file.Write(expr_text, bytes_written).Success()) {
581 if (bytes_written == expr_text_len) {
582 file.Close();
583 source_mgr.setMainFileID(
584 source_mgr.createFileID(m_file_manager->getFile(result_path),
585 SourceLocation(), SrcMgr::C_User));
586 created_main_file = true;
Greg Clayton23f8c952014-03-24 23:10:19 +0000587 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000588 }
Greg Clayton23f8c952014-03-24 23:10:19 +0000589 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000590 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000591
Kate Stoneb9c1b512016-09-06 20:57:50 +0000592 if (!created_main_file) {
593 std::unique_ptr<MemoryBuffer> memory_buffer =
594 MemoryBuffer::getMemBufferCopy(expr_text, __FUNCTION__);
595 source_mgr.setMainFileID(source_mgr.createFileID(std::move(memory_buffer)));
596 }
597
598 diag_buf->BeginSourceFile(m_compiler->getLangOpts(),
599 &m_compiler->getPreprocessor());
600
601 ClangExpressionHelper *type_system_helper =
602 dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
603
604 ASTConsumer *ast_transformer =
605 type_system_helper->ASTTransformer(m_code_generator.get());
606
607 if (ClangExpressionDeclMap *decl_map = type_system_helper->DeclMap())
608 decl_map->InstallCodeGenerator(m_code_generator.get());
609
610 if (ast_transformer) {
611 ast_transformer->Initialize(m_compiler->getASTContext());
612 ParseAST(m_compiler->getPreprocessor(), ast_transformer,
613 m_compiler->getASTContext());
614 } else {
615 m_code_generator->Initialize(m_compiler->getASTContext());
616 ParseAST(m_compiler->getPreprocessor(), m_code_generator.get(),
617 m_compiler->getASTContext());
618 }
619
620 diag_buf->EndSourceFile();
621
622 unsigned num_errors = diag_buf->getNumErrors();
623
624 if (m_pp_callbacks && m_pp_callbacks->hasErrors()) {
625 num_errors++;
Zachary Turnere2411fa2016-11-12 19:12:56 +0000626 diagnostic_manager.PutString(eDiagnosticSeverityError,
627 "while importing modules:");
Kate Stoneb9c1b512016-09-06 20:57:50 +0000628 diagnostic_manager.AppendMessageToDiagnostic(
Zachary Turnerc1564272016-11-16 21:15:24 +0000629 m_pp_callbacks->getErrorString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000630 }
631
632 if (!num_errors) {
633 if (type_system_helper->DeclMap() &&
634 !type_system_helper->DeclMap()->ResolveUnknownTypes()) {
635 diagnostic_manager.Printf(eDiagnosticSeverityError,
636 "Couldn't infer the type of a variable");
637 num_errors++;
Greg Clayton23f8c952014-03-24 23:10:19 +0000638 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000639 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000640
Kate Stoneb9c1b512016-09-06 20:57:50 +0000641 if (!num_errors) {
642 type_system_helper->CommitPersistentDecls();
643 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000644
Kate Stoneb9c1b512016-09-06 20:57:50 +0000645 adapter->ResetManager();
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000646
Kate Stoneb9c1b512016-09-06 20:57:50 +0000647 return num_errors;
Sean Callanan1a8d4092010-08-27 01:01:44 +0000648}
649
Sagar Thakuradc1abe2016-05-13 11:04:47 +0000650std::string
Kate Stoneb9c1b512016-09-06 20:57:50 +0000651ClangExpressionParser::GetClangTargetABI(const ArchSpec &target_arch) {
652 std::string abi;
653
654 if (target_arch.IsMIPS()) {
655 switch (target_arch.GetFlags() & ArchSpec::eMIPSABI_mask) {
656 case ArchSpec::eMIPSABI_N64:
657 abi = "n64";
658 break;
659 case ArchSpec::eMIPSABI_N32:
660 abi = "n32";
661 break;
662 case ArchSpec::eMIPSABI_O32:
663 abi = "o32";
664 break;
665 default:
666 break;
Sagar Thakuradc1abe2016-05-13 11:04:47 +0000667 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000668 }
669 return abi;
Sagar Thakuradc1abe2016-05-13 11:04:47 +0000670}
671
Kate Stoneb9c1b512016-09-06 20:57:50 +0000672bool ClangExpressionParser::RewriteExpression(
673 DiagnosticManager &diagnostic_manager) {
674 clang::SourceManager &source_manager = m_compiler->getSourceManager();
675 clang::edit::EditedSource editor(source_manager, m_compiler->getLangOpts(),
676 nullptr);
677 clang::edit::Commit commit(editor);
678 clang::Rewriter rewriter(source_manager, m_compiler->getLangOpts());
Jim Inghama1e541b2016-03-25 01:57:14 +0000679
Kate Stoneb9c1b512016-09-06 20:57:50 +0000680 class RewritesReceiver : public edit::EditsReceiver {
681 Rewriter &rewrite;
Jim Inghama1e541b2016-03-25 01:57:14 +0000682
Kate Stoneb9c1b512016-09-06 20:57:50 +0000683 public:
684 RewritesReceiver(Rewriter &in_rewrite) : rewrite(in_rewrite) {}
685
686 void insert(SourceLocation loc, StringRef text) override {
687 rewrite.InsertText(loc, text);
Jim Inghama1e541b2016-03-25 01:57:14 +0000688 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000689 void replace(CharSourceRange range, StringRef text) override {
690 rewrite.ReplaceText(range.getBegin(), rewrite.getRangeSize(range), text);
Sean Callananfc55f5d2010-09-21 00:44:12 +0000691 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000692 };
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000693
Kate Stoneb9c1b512016-09-06 20:57:50 +0000694 RewritesReceiver rewrites_receiver(rewriter);
695
696 const DiagnosticList &diagnostics = diagnostic_manager.Diagnostics();
697 size_t num_diags = diagnostics.size();
698 if (num_diags == 0)
Sean Callananfc55f5d2010-09-21 00:44:12 +0000699 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000700
701 for (const Diagnostic *diag : diagnostic_manager.Diagnostics()) {
702 const ClangDiagnostic *diagnostic = llvm::dyn_cast<ClangDiagnostic>(diag);
703 if (diagnostic && diagnostic->HasFixIts()) {
704 for (const FixItHint &fixit : diagnostic->FixIts()) {
705 // This is cobbed from clang::Rewrite::FixItRewriter.
706 if (fixit.CodeToInsert.empty()) {
707 if (fixit.InsertFromRange.isValid()) {
708 commit.insertFromRange(fixit.RemoveRange.getBegin(),
709 fixit.InsertFromRange, /*afterToken=*/false,
710 fixit.BeforePreviousInsertions);
711 } else
712 commit.remove(fixit.RemoveRange);
713 } else {
714 if (fixit.RemoveRange.isTokenRange() ||
715 fixit.RemoveRange.getBegin() != fixit.RemoveRange.getEnd())
716 commit.replace(fixit.RemoveRange, fixit.CodeToInsert);
717 else
718 commit.insert(fixit.RemoveRange.getBegin(), fixit.CodeToInsert,
719 /*afterToken=*/false, fixit.BeforePreviousInsertions);
720 }
721 }
722 }
723 }
724
725 // FIXME - do we want to try to propagate specific errors here?
726 if (!commit.isCommitable())
727 return false;
728 else if (!editor.commit(commit))
729 return false;
730
731 // Now play all the edits, and stash the result in the diagnostic manager.
732 editor.applyRewrites(rewrites_receiver);
733 RewriteBuffer &main_file_buffer =
734 rewriter.getEditBuffer(source_manager.getMainFileID());
735
736 std::string fixed_expression;
737 llvm::raw_string_ostream out_stream(fixed_expression);
738
739 main_file_buffer.write(out_stream);
740 out_stream.flush();
741 diagnostic_manager.SetFixedExpression(fixed_expression);
742
743 return true;
Sean Callananfc55f5d2010-09-21 00:44:12 +0000744}
745
Kate Stoneb9c1b512016-09-06 20:57:50 +0000746static bool FindFunctionInModule(ConstString &mangled_name,
747 llvm::Module *module, const char *orig_name) {
748 for (const auto &func : module->getFunctionList()) {
749 const StringRef &name = func.getName();
750 if (name.find(orig_name) != StringRef::npos) {
751 mangled_name.SetString(name);
752 return true;
Sean Callanan1a8d4092010-08-27 01:01:44 +0000753 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000754 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000755
Kate Stoneb9c1b512016-09-06 20:57:50 +0000756 return false;
Sean Callanan1a8d4092010-08-27 01:01:44 +0000757}
Sean Callananbd4dc692016-03-21 22:23:38 +0000758
Zachary Turner97206d52017-05-12 04:51:55 +0000759lldb_private::Status ClangExpressionParser::PrepareForExecution(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000760 lldb::addr_t &func_addr, lldb::addr_t &func_end,
761 lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx,
762 bool &can_interpret, ExecutionPolicy execution_policy) {
763 func_addr = LLDB_INVALID_ADDRESS;
764 func_end = LLDB_INVALID_ADDRESS;
765 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
766
Zachary Turner97206d52017-05-12 04:51:55 +0000767 lldb_private::Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000768
769 std::unique_ptr<llvm::Module> llvm_module_ap(
770 m_code_generator->ReleaseModule());
771
772 if (!llvm_module_ap.get()) {
773 err.SetErrorToGenericError();
774 err.SetErrorString("IR doesn't contain a module");
Sean Callananbd4dc692016-03-21 22:23:38 +0000775 return err;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000776 }
777
778 ConstString function_name;
779
780 if (execution_policy != eExecutionPolicyTopLevel) {
781 // Find the actual name of the function (it's often mangled somehow)
782
783 if (!FindFunctionInModule(function_name, llvm_module_ap.get(),
784 m_expr.FunctionName())) {
785 err.SetErrorToGenericError();
786 err.SetErrorStringWithFormat("Couldn't find %s() in the module",
787 m_expr.FunctionName());
788 return err;
789 } else {
790 if (log)
791 log->Printf("Found function %s for %s", function_name.AsCString(),
792 m_expr.FunctionName());
793 }
794 }
795
796 SymbolContext sc;
797
798 if (lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP()) {
799 sc = frame_sp->GetSymbolContext(lldb::eSymbolContextEverything);
800 } else if (lldb::TargetSP target_sp = exe_ctx.GetTargetSP()) {
801 sc.target_sp = target_sp;
802 }
803
804 LLVMUserExpression::IRPasses custom_passes;
805 {
806 auto lang = m_expr.Language();
807 if (log)
808 log->Printf("%s - Currrent expression language is %s\n", __FUNCTION__,
809 Language::GetNameForLanguageType(lang));
Jim Ingham22562152016-11-03 23:42:09 +0000810 lldb::ProcessSP process_sp = exe_ctx.GetProcessSP();
811 if (process_sp && lang != lldb::eLanguageTypeUnknown) {
812 auto runtime = process_sp->GetLanguageRuntime(lang);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000813 if (runtime)
814 runtime->GetIRPasses(custom_passes);
815 }
816 }
817
818 if (custom_passes.EarlyPasses) {
819 if (log)
820 log->Printf("%s - Running Early IR Passes from LanguageRuntime on "
821 "expression module '%s'",
822 __FUNCTION__, m_expr.FunctionName());
823
824 custom_passes.EarlyPasses->run(*llvm_module_ap);
825 }
826
827 execution_unit_sp.reset(
828 new IRExecutionUnit(m_llvm_context, // handed off here
829 llvm_module_ap, // handed off here
830 function_name, exe_ctx.GetTargetSP(), sc,
831 m_compiler->getTargetOpts().Features));
832
833 ClangExpressionHelper *type_system_helper =
834 dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
835 ClangExpressionDeclMap *decl_map =
836 type_system_helper->DeclMap(); // result can be NULL
837
838 if (decl_map) {
839 Stream *error_stream = NULL;
840 Target *target = exe_ctx.GetTargetPtr();
841 error_stream = target->GetDebugger().GetErrorFile().get();
842
843 IRForTarget ir_for_target(decl_map, m_expr.NeedsVariableResolution(),
844 *execution_unit_sp, *error_stream,
845 function_name.AsCString());
846
847 bool ir_can_run =
848 ir_for_target.runOnModule(*execution_unit_sp->GetModule());
849
850 if (!ir_can_run) {
851 err.SetErrorString(
852 "The expression could not be prepared to run in the target");
853 return err;
854 }
855
856 Process *process = exe_ctx.GetProcessPtr();
857
858 if (execution_policy != eExecutionPolicyAlways &&
859 execution_policy != eExecutionPolicyTopLevel) {
Zachary Turner97206d52017-05-12 04:51:55 +0000860 lldb_private::Status interpret_error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000861
862 bool interpret_function_calls =
863 !process ? false : process->CanInterpretFunctionCalls();
864 can_interpret = IRInterpreter::CanInterpret(
865 *execution_unit_sp->GetModule(), *execution_unit_sp->GetFunction(),
866 interpret_error, interpret_function_calls);
867
868 if (!can_interpret && execution_policy == eExecutionPolicyNever) {
869 err.SetErrorStringWithFormat("Can't run the expression locally: %s",
870 interpret_error.AsCString());
871 return err;
872 }
873 }
874
875 if (!process && execution_policy == eExecutionPolicyAlways) {
876 err.SetErrorString("Expression needed to run in the target, but the "
877 "target can't be run");
878 return err;
879 }
880
881 if (!process && execution_policy == eExecutionPolicyTopLevel) {
882 err.SetErrorString("Top-level code needs to be inserted into a runnable "
883 "target, but the target can't be run");
884 return err;
885 }
886
887 if (execution_policy == eExecutionPolicyAlways ||
888 (execution_policy != eExecutionPolicyTopLevel && !can_interpret)) {
889 if (m_expr.NeedsValidation() && process) {
890 if (!process->GetDynamicCheckers()) {
891 DynamicCheckerFunctions *dynamic_checkers =
892 new DynamicCheckerFunctions();
893
894 DiagnosticManager install_diagnostics;
895
896 if (!dynamic_checkers->Install(install_diagnostics, exe_ctx)) {
897 if (install_diagnostics.Diagnostics().size())
898 err.SetErrorString("couldn't install checkers, unknown error");
899 else
900 err.SetErrorString(install_diagnostics.GetString().c_str());
901
902 return err;
903 }
904
905 process->SetDynamicCheckers(dynamic_checkers);
906
907 if (log)
908 log->Printf("== [ClangUserExpression::Evaluate] Finished "
909 "installing dynamic checkers ==");
910 }
911
912 IRDynamicChecks ir_dynamic_checks(*process->GetDynamicCheckers(),
913 function_name.AsCString());
914
915 llvm::Module *module = execution_unit_sp->GetModule();
916 if (!module || !ir_dynamic_checks.runOnModule(*module)) {
917 err.SetErrorToGenericError();
918 err.SetErrorString("Couldn't add dynamic checks to the expression");
919 return err;
920 }
921
922 if (custom_passes.LatePasses) {
923 if (log)
924 log->Printf("%s - Running Late IR Passes from LanguageRuntime on "
925 "expression module '%s'",
926 __FUNCTION__, m_expr.FunctionName());
927
928 custom_passes.LatePasses->run(*module);
929 }
930 }
931 }
932
933 if (execution_policy == eExecutionPolicyAlways ||
934 execution_policy == eExecutionPolicyTopLevel || !can_interpret) {
935 execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);
936 }
937 } else {
938 execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);
939 }
940
941 return err;
942}
943
Zachary Turner97206d52017-05-12 04:51:55 +0000944lldb_private::Status ClangExpressionParser::RunStaticInitializers(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000945 lldb::IRExecutionUnitSP &execution_unit_sp, ExecutionContext &exe_ctx) {
Zachary Turner97206d52017-05-12 04:51:55 +0000946 lldb_private::Status err;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000947
948 lldbassert(execution_unit_sp.get());
949 lldbassert(exe_ctx.HasThreadScope());
950
951 if (!execution_unit_sp.get()) {
952 err.SetErrorString(
953 "can't run static initializers for a NULL execution unit");
954 return err;
955 }
956
957 if (!exe_ctx.HasThreadScope()) {
958 err.SetErrorString("can't run static initializers without a thread");
959 return err;
960 }
961
962 std::vector<lldb::addr_t> static_initializers;
963
964 execution_unit_sp->GetStaticInitializers(static_initializers);
965
966 for (lldb::addr_t static_initializer : static_initializers) {
967 EvaluateExpressionOptions options;
968
969 lldb::ThreadPlanSP call_static_initializer(new ThreadPlanCallFunction(
970 exe_ctx.GetThreadRef(), Address(static_initializer), CompilerType(),
971 llvm::ArrayRef<lldb::addr_t>(), options));
972
973 DiagnosticManager execution_errors;
974 lldb::ExpressionResults results =
975 exe_ctx.GetThreadRef().GetProcess()->RunThreadPlan(
976 exe_ctx, call_static_initializer, options, execution_errors);
977
978 if (results != lldb::eExpressionCompleted) {
979 err.SetErrorStringWithFormat("couldn't run static initializer: %s",
980 execution_errors.GetString().c_str());
981 return err;
982 }
983 }
984
985 return err;
Sean Callananbd4dc692016-03-21 22:23:38 +0000986}