blob: 763fc738598c488584f65ace2b122d0d74da7a70 [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"
Jim Inghama1e541b2016-03-25 01:57:14 +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"
24#include "clang/Edit/EditsReceiver.h"
25#include "clang/Edit/EditedSource.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"
Sean Callanan3d654b32012-09-24 22:25:51 +000035#include "clang/Rewrite/Frontend/FrontendActions.h"
Jim Inghama1e541b2016-03-25 01:57:14 +000036#include "clang/Rewrite/Core/Rewriter.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000037#include "clang/Sema/SemaConsumer.h"
Sean Callananfb0b7582011-03-15 00:17:19 +000038#include "clang/StaticAnalyzer/Frontend/FrontendActions.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000039
40#include "llvm/ADT/StringRef.h"
41#include "llvm/ExecutionEngine/ExecutionEngine.h"
Sean Callanan3d654b32012-09-24 22:25:51 +000042#include "llvm/Support/Debug.h"
Rafael Espindola4609ea82013-06-26 14:10:56 +000043#include "llvm/Support/FileSystem.h"
Sean Callanan880e6802011-10-07 23:18:13 +000044#include "llvm/Support/TargetSelect.h"
Greg Clayton70b57652011-05-15 01:25:55 +000045
Greg Claytonc9a078a2016-03-24 23:50:03 +000046#pragma clang diagnostic push
47#pragma clang diagnostic ignored "-Wglobal-constructors"
Ed Mastea09ed032014-03-18 18:55:06 +000048#include "llvm/ExecutionEngine/MCJIT.h"
Greg Claytonc9a078a2016-03-24 23:50:03 +000049#pragma clang diagnostic pop
50
Chandler Carruth1e157582013-01-02 12:20:07 +000051#include "llvm/IR/LLVMContext.h"
52#include "llvm/IR/Module.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000053#include "llvm/Support/ErrorHandling.h"
54#include "llvm/Support/MemoryBuffer.h"
Greg Clayton38a61402010-12-02 23:20:03 +000055#include "llvm/Support/DynamicLibrary.h"
56#include "llvm/Support/Host.h"
57#include "llvm/Support/Signals.h"
Sean Callanan1a8d4092010-08-27 01:01:44 +000058
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000059// Project includes
60#include "ClangExpressionParser.h"
Jim Inghama1e541b2016-03-25 01:57:14 +000061#include "ClangDiagnostic.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000062
63#include "ClangASTSource.h"
64#include "ClangExpressionHelper.h"
65#include "ClangExpressionDeclMap.h"
66#include "ClangModulesDeclVendor.h"
67#include "ClangPersistentVariables.h"
68#include "IRForTarget.h"
69
70#include "lldb/Core/ArchSpec.h"
71#include "lldb/Core/DataBufferHeap.h"
72#include "lldb/Core/Debugger.h"
73#include "lldb/Core/Disassembler.h"
74#include "lldb/Core/Log.h"
75#include "lldb/Core/Module.h"
76#include "lldb/Core/Stream.h"
77#include "lldb/Core/StreamFile.h"
78#include "lldb/Core/StreamString.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000079#include "lldb/Core/StringList.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000080#include "lldb/Expression/IRDynamicChecks.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000081#include "lldb/Expression/IRExecutionUnit.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000082#include "lldb/Expression/IRInterpreter.h"
83#include "lldb/Host/File.h"
84#include "lldb/Host/HostInfo.h"
85#include "lldb/Symbol/ClangASTContext.h"
86#include "lldb/Symbol/SymbolVendor.h"
87#include "lldb/Target/ExecutionContext.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000088#include "lldb/Target/Language.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000089#include "lldb/Target/ObjCLanguageRuntime.h"
90#include "lldb/Target/Process.h"
91#include "lldb/Target/Target.h"
Sean Callananbd4dc692016-03-21 22:23:38 +000092#include "lldb/Target/ThreadPlanCallFunction.h"
Sean Callanan579e70c2016-03-19 00:03:59 +000093#include "lldb/Utility/LLDBAssert.h"
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +000094
Sean Callanan1a8d4092010-08-27 01:01:44 +000095using namespace clang;
96using namespace llvm;
97using namespace lldb_private;
98
99//===----------------------------------------------------------------------===//
100// Utility Methods for Clang
101//===----------------------------------------------------------------------===//
102
Sean Callanan1a8d4092010-08-27 01:01:44 +0000103
Sean Callananc8278af2014-12-05 01:27:35 +0000104class ClangExpressionParser::LLDBPreprocessorCallbacks : public PPCallbacks
105{
Sean Callananf0c5aeb2015-04-20 16:31:29 +0000106 ClangModulesDeclVendor &m_decl_vendor;
107 ClangPersistentVariables &m_persistent_vars;
108 StreamString m_error_stream;
109 bool m_has_errors = false;
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +0000110
Sean Callananc8278af2014-12-05 01:27:35 +0000111public:
Sean Callananf0c5aeb2015-04-20 16:31:29 +0000112 LLDBPreprocessorCallbacks(ClangModulesDeclVendor &decl_vendor,
113 ClangPersistentVariables &persistent_vars) :
114 m_decl_vendor(decl_vendor),
115 m_persistent_vars(persistent_vars)
Sean Callananc8278af2014-12-05 01:27:35 +0000116 {
117 }
118
Eugene Zelenko4c3f2b92015-10-21 01:03:30 +0000119 void
120 moduleImport(SourceLocation import_location,
121 clang::ModuleIdPath path,
122 const clang::Module * /*null*/) override
Sean Callananc8278af2014-12-05 01:27:35 +0000123 {
Sean Callananf0c5aeb2015-04-20 16:31:29 +0000124 std::vector<ConstString> string_path;
Sean Callananc8278af2014-12-05 01:27:35 +0000125
126 for (const std::pair<IdentifierInfo *, SourceLocation> &component : path)
127 {
Sean Callananf0c5aeb2015-04-20 16:31:29 +0000128 string_path.push_back(ConstString(component.first->getName()));
Sean Callananc8278af2014-12-05 01:27:35 +0000129 }
130
131 StreamString error_stream;
132
Sean Callananf0c5aeb2015-04-20 16:31:29 +0000133 ClangModulesDeclVendor::ModuleVector exported_modules;
134
135 if (!m_decl_vendor.AddModule(string_path, &exported_modules, m_error_stream))
Sean Callananc8278af2014-12-05 01:27:35 +0000136 {
137 m_has_errors = true;
138 }
Sean Callananf0c5aeb2015-04-20 16:31:29 +0000139
140 for (ClangModulesDeclVendor::ModuleID module : exported_modules)
141 {
142 m_persistent_vars.AddHandLoadedClangModule(module);
143 }
Sean Callananc8278af2014-12-05 01:27:35 +0000144 }
145
146 bool hasErrors()
147 {
148 return m_has_errors;
149 }
150
151 const std::string &getErrorString()
152 {
153 return m_error_stream.GetString();
154 }
155};
156
Sean Callanan579e70c2016-03-19 00:03:59 +0000157class ClangDiagnosticManagerAdapter : public clang::DiagnosticConsumer
158{
159public:
160 ClangDiagnosticManagerAdapter() : m_passthrough(new clang::TextDiagnosticBuffer) {}
161
162 ClangDiagnosticManagerAdapter(const std::shared_ptr<clang::TextDiagnosticBuffer> &passthrough)
163 : m_passthrough(passthrough)
164 {
165 }
166
167 void
168 ResetManager(DiagnosticManager *manager = nullptr)
169 {
170 m_manager = manager;
171 }
172
173 void
174 HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, const clang::Diagnostic &Info)
175 {
176 if (m_manager)
177 {
178 llvm::SmallVector<char, 32> diag_str;
179 Info.FormatDiagnostic(diag_str);
180 diag_str.push_back('\0');
181 const char *data = diag_str.data();
182
Jim Inghama1e541b2016-03-25 01:57:14 +0000183 DiagnosticSeverity severity;
184 bool make_new_diagnostic = true;
185
Sean Callanan579e70c2016-03-19 00:03:59 +0000186 switch (DiagLevel)
187 {
188 case DiagnosticsEngine::Level::Fatal:
189 case DiagnosticsEngine::Level::Error:
Jim Inghama1e541b2016-03-25 01:57:14 +0000190 severity = eDiagnosticSeverityError;
Sean Callanan579e70c2016-03-19 00:03:59 +0000191 break;
192 case DiagnosticsEngine::Level::Warning:
Jim Inghama1e541b2016-03-25 01:57:14 +0000193 severity = eDiagnosticSeverityWarning;
Sean Callanan579e70c2016-03-19 00:03:59 +0000194 break;
195 case DiagnosticsEngine::Level::Remark:
196 case DiagnosticsEngine::Level::Ignored:
Jim Inghama1e541b2016-03-25 01:57:14 +0000197 severity = eDiagnosticSeverityRemark;
Sean Callanan579e70c2016-03-19 00:03:59 +0000198 break;
199 case DiagnosticsEngine::Level::Note:
200 m_manager->AppendMessageToDiagnostic(data);
Jim Inghama1e541b2016-03-25 01:57:14 +0000201 make_new_diagnostic = false;
202 }
203 if (make_new_diagnostic)
204 {
205 ClangDiagnostic *new_diagnostic = new ClangDiagnostic(data, severity, Info.getID());
206 m_manager->AddDiagnostic(new_diagnostic);
207
208 // Don't store away warning fixits, since the compiler doesn't have enough
209 // context in an expression for the warning to be useful.
210 // FIXME: Should we try to filter out FixIts that apply to our generated
211 // code, and not the user's expression?
212 if (severity == eDiagnosticSeverityError)
213 {
214 size_t num_fixit_hints = Info.getNumFixItHints();
215 for (int i = 0; i < num_fixit_hints; i++)
216 {
217 const clang::FixItHint &fixit = Info.getFixItHint(i);
218 if (!fixit.isNull())
219 new_diagnostic->AddFixitHint(fixit);
220 }
221 }
Sean Callanan579e70c2016-03-19 00:03:59 +0000222 }
223 }
Jim Inghama1e541b2016-03-25 01:57:14 +0000224
Sean Callanan579e70c2016-03-19 00:03:59 +0000225 m_passthrough->HandleDiagnostic(DiagLevel, Info);
226 }
227
228 void
229 FlushDiagnostics(DiagnosticsEngine &Diags)
230 {
231 m_passthrough->FlushDiagnostics(Diags);
232 }
233
234 DiagnosticConsumer *
235 clone(DiagnosticsEngine &Diags) const
236 {
237 return new ClangDiagnosticManagerAdapter(m_passthrough);
238 }
239
240 clang::TextDiagnosticBuffer *
241 GetPassthrough()
242 {
243 return m_passthrough.get();
244 }
245
246private:
247 DiagnosticManager *m_manager = nullptr;
248 std::shared_ptr<clang::TextDiagnosticBuffer> m_passthrough;
249};
250
Sean Callananbd4dc692016-03-21 22:23:38 +0000251class LoggingDiagnosticConsumer : public clang::DiagnosticConsumer
252{
253public:
254 LoggingDiagnosticConsumer ()
255 {
256 m_log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
257 m_passthrough.reset(new clang::TextDiagnosticBuffer);
258 }
259
260 LoggingDiagnosticConsumer (const std::shared_ptr<clang::TextDiagnosticBuffer> &passthrough)
261 {
262 m_log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
263 m_passthrough = passthrough;
264 }
265
266 void HandleDiagnostic (DiagnosticsEngine::Level DiagLevel, const clang::Diagnostic &Info)
267 {
268 if (m_log)
269 {
270 llvm::SmallVector<char, 32> diag_str;
271 Info.FormatDiagnostic(diag_str);
272 diag_str.push_back('\0');
273 const char *data = diag_str.data();
274 m_log->Printf("[clang] COMPILER DIAGNOSTIC: %s", data);
275
276 lldbassert(Info.getID() != clang::diag::err_unsupported_ast_node && "'log enable lldb expr' to investigate.");
277 }
278
279 m_passthrough->HandleDiagnostic(DiagLevel, Info);
280 }
281
282 void FlushDiagnostics (DiagnosticsEngine &Diags)
283 {
284 m_passthrough->FlushDiagnostics(Diags);
285 }
286
287 DiagnosticConsumer *clone (DiagnosticsEngine &Diags) const
288 {
289 return new LoggingDiagnosticConsumer (m_passthrough);
290 }
291
292 clang::TextDiagnosticBuffer *GetPassthrough()
293 {
294 return m_passthrough.get();
295 }
296private:
297 Log * m_log;
298 std::shared_ptr<clang::TextDiagnosticBuffer> m_passthrough;
299};
300
Sean Callanan1a8d4092010-08-27 01:01:44 +0000301//===----------------------------------------------------------------------===//
302// Implementation of ClangExpressionParser
303//===----------------------------------------------------------------------===//
304
Greg Clayton514487e2011-02-15 21:59:32 +0000305ClangExpressionParser::ClangExpressionParser (ExecutionContextScope *exe_scope,
Jim Ingham151c0322015-09-15 21:13:50 +0000306 Expression &expr,
Greg Clayton23f8c952014-03-24 23:10:19 +0000307 bool generate_debug_info) :
Jim Ingham151c0322015-09-15 21:13:50 +0000308 ExpressionParser (exe_scope, expr, generate_debug_info),
Sean Callanan1a8d4092010-08-27 01:01:44 +0000309 m_compiler (),
Zachary Turner22ac8712014-12-05 22:54:56 +0000310 m_code_generator (),
311 m_pp_callbacks(nullptr)
Sean Callanan1a8d4092010-08-27 01:01:44 +0000312{
Aidan Dodds1b6785a2016-02-03 12:33:05 +0000313 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
314
Sean Callanan1a8d4092010-08-27 01:01:44 +0000315 // 1. Create a new compiler instance.
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000316 m_compiler.reset(new CompilerInstance());
Ewan Crawford7648dd32016-03-10 12:38:55 +0000317 lldb::LanguageType frame_lang = expr.Language(); // defaults to lldb::eLanguageTypeUnknown
Aidan Dodds1b6785a2016-02-03 12:33:05 +0000318 bool overridden_target_opts = false;
319 lldb_private::LanguageRuntime *lang_rt = nullptr;
Sean Callanan3d654b32012-09-24 22:25:51 +0000320 lldb::TargetSP target_sp;
321 if (exe_scope)
322 target_sp = exe_scope->CalculateTarget();
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000323
Bhushan D. Attarde3592a6e2016-02-18 11:53:28 +0000324 ArchSpec target_arch;
325 if (target_sp)
326 target_arch = target_sp->GetArchitecture();
327
328 const auto target_machine = target_arch.GetMachine();
329
Aidan Dodds1b6785a2016-02-03 12:33:05 +0000330 // If the expression is being evaluated in the context of an existing
331 // stack frame, we introspect to see if the language runtime is available.
332 auto frame = exe_scope->CalculateStackFrame();
333
334 // Make sure the user hasn't provided a preferred execution language
335 // with `expression --language X -- ...`
Ewan Crawford7648dd32016-03-10 12:38:55 +0000336 if (frame && frame_lang == lldb::eLanguageTypeUnknown)
337 frame_lang = frame->GetLanguage();
Aidan Dodds1b6785a2016-02-03 12:33:05 +0000338
Ewan Crawford7648dd32016-03-10 12:38:55 +0000339 if (frame_lang != lldb::eLanguageTypeUnknown)
Aidan Dodds1b6785a2016-02-03 12:33:05 +0000340 {
Ewan Crawford7648dd32016-03-10 12:38:55 +0000341 lang_rt = exe_scope->CalculateProcess()->GetLanguageRuntime(frame_lang);
Aidan Dodds1b6785a2016-02-03 12:33:05 +0000342 if (log)
Ewan Crawford7648dd32016-03-10 12:38:55 +0000343 log->Printf("Frame has language of type %s", Language::GetNameForLanguageType(frame_lang));
Aidan Dodds1b6785a2016-02-03 12:33:05 +0000344 }
345
346 // 2. Configure the compiler with a set of default options that are appropriate
347 // for most situations.
Bhushan D. Attarde3592a6e2016-02-18 11:53:28 +0000348 if (target_sp && target_arch.IsValid())
Sean Callanan3d654b32012-09-24 22:25:51 +0000349 {
Bhushan D. Attarde3592a6e2016-02-18 11:53:28 +0000350 std::string triple = target_arch.GetTriple().str();
Sean Callanan3d654b32012-09-24 22:25:51 +0000351 m_compiler->getTargetOpts().Triple = triple;
Aidan Dodds1b6785a2016-02-03 12:33:05 +0000352 if (log)
353 log->Printf("Using %s as the target triple", m_compiler->getTargetOpts().Triple.c_str());
Sean Callanan3d654b32012-09-24 22:25:51 +0000354 }
355 else
356 {
Aidan Dodds1b6785a2016-02-03 12:33:05 +0000357 // If we get here we don't have a valid target and just have to guess.
358 // Sometimes this will be ok to just use the host target triple (when we evaluate say "2+3", but other
359 // expressions like breakpoint conditions and other things that _are_ target specific really shouldn't just be
360 // using the host triple. In such a case the language runtime should expose an overridden options set (3),
361 // below.
Sean Callanan3d654b32012-09-24 22:25:51 +0000362 m_compiler->getTargetOpts().Triple = llvm::sys::getDefaultTargetTriple();
Aidan Dodds1b6785a2016-02-03 12:33:05 +0000363 if (log)
364 log->Printf("Using default target triple of %s", m_compiler->getTargetOpts().Triple.c_str());
Sean Callanan3d654b32012-09-24 22:25:51 +0000365 }
Aidan Dodds1b6785a2016-02-03 12:33:05 +0000366 // Now add some special fixes for known architectures:
Jason Molendaa3329782014-03-29 18:54:20 +0000367 // Any arm32 iOS environment, but not on arm64
Sean Callanan60400ec2014-06-23 21:00:25 +0000368 if (m_compiler->getTargetOpts().Triple.find("arm64") == std::string::npos &&
369 m_compiler->getTargetOpts().Triple.find("arm") != std::string::npos &&
370 m_compiler->getTargetOpts().Triple.find("ios") != std::string::npos)
Jason Molendaa3329782014-03-29 18:54:20 +0000371 {
Sean Callanan3d654b32012-09-24 22:25:51 +0000372 m_compiler->getTargetOpts().ABI = "apcs-gnu";
Jason Molendaa3329782014-03-29 18:54:20 +0000373 }
Aidan Dodds1b6785a2016-02-03 12:33:05 +0000374 // Supported subsets of x86
Bhushan D. Attarde3592a6e2016-02-18 11:53:28 +0000375 if (target_machine == llvm::Triple::x86 ||
376 target_machine == llvm::Triple::x86_64)
Aidan Dodds1b6785a2016-02-03 12:33:05 +0000377 {
378 m_compiler->getTargetOpts().Features.push_back("+sse");
379 m_compiler->getTargetOpts().Features.push_back("+sse2");
380 }
Jason Molendaa3329782014-03-29 18:54:20 +0000381
Bhushan D. Attarde3592a6e2016-02-18 11:53:28 +0000382 // Set the target CPU to generate code for.
383 // This will be empty for any CPU that doesn't really need to make a special CPU string.
384 m_compiler->getTargetOpts().CPU = target_arch.GetClangTargetCPU();
385
Aidan Dodds1b6785a2016-02-03 12:33:05 +0000386 // 3. Now allow the runtime to provide custom configuration options for the target.
387 // In this case, a specialized language runtime is available and we can query it for extra options.
388 // For 99% of use cases, this will not be needed and should be provided when basic platform detection is not enough.
389 if (lang_rt)
390 overridden_target_opts = lang_rt->GetOverrideExprOptions(m_compiler->getTargetOpts());
391
392 if (overridden_target_opts)
393 if (log)
394 {
395 log->Debug("Using overridden target options for the expression evaluation");
396
397 auto opts = m_compiler->getTargetOpts();
398 log->Debug("Triple: '%s'", opts.Triple.c_str());
399 log->Debug("CPU: '%s'", opts.CPU.c_str());
400 log->Debug("FPMath: '%s'", opts.FPMath.c_str());
401 log->Debug("ABI: '%s'", opts.ABI.c_str());
402 log->Debug("LinkerVersion: '%s'", opts.LinkerVersion.c_str());
403 StringList::LogDump(log, opts.FeaturesAsWritten, "FeaturesAsWritten");
404 StringList::LogDump(log, opts.Features, "Features");
405 StringList::LogDump(log, opts.Reciprocals, "Reciprocals");
406 }
407
408 // 4. Create and install the target on the compiler.
Sean Callananb1de8dd2013-01-22 02:20:20 +0000409 m_compiler->createDiagnostics();
Aidan Dodds1b6785a2016-02-03 12:33:05 +0000410 auto target_info = TargetInfo::CreateTargetInfo(m_compiler->getDiagnostics(), m_compiler->getInvocation().TargetOpts);
411 if (log)
412 {
413 log->Printf("Using SIMD alignment: %d", target_info->getSimdDefaultAlign());
James Y Knightdc395b92016-03-04 19:30:53 +0000414 log->Printf("Target datalayout string: '%s'", target_info->getDataLayout().getStringRepresentation().c_str());
Aidan Dodds1b6785a2016-02-03 12:33:05 +0000415 log->Printf("Target ABI: '%s'", target_info->getABI().str().c_str());
416 log->Printf("Target vector alignment: %d", target_info->getMaxVectorAlign());
417 }
418 m_compiler->setTarget(target_info);
Alp Toker5f838642014-07-06 05:36:57 +0000419
Sean Callanan3d654b32012-09-24 22:25:51 +0000420 assert (m_compiler->hasTarget());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000421
Aidan Dodds1b6785a2016-02-03 12:33:05 +0000422 // 5. Set language options.
Ewan Crawford7648dd32016-03-10 12:38:55 +0000423 lldb::LanguageType language = expr.Language();
424
425 switch (language)
Sean Callananc7b65062011-11-07 23:35:40 +0000426 {
427 case lldb::eLanguageTypeC:
Dawn Perchik009d1102015-09-04 01:02:30 +0000428 case lldb::eLanguageTypeC89:
429 case lldb::eLanguageTypeC99:
430 case lldb::eLanguageTypeC11:
431 // FIXME: the following language option is a temporary workaround,
432 // to "ask for C, get C++."
433 // For now, the expression parser must use C++ anytime the
434 // language is a C family language, because the expression parser
435 // uses features of C++ to capture values.
436 m_compiler->getLangOpts().CPlusPlus = true;
Sean Callananc7b65062011-11-07 23:35:40 +0000437 break;
438 case lldb::eLanguageTypeObjC:
439 m_compiler->getLangOpts().ObjC1 = true;
440 m_compiler->getLangOpts().ObjC2 = true;
Dawn Perchik009d1102015-09-04 01:02:30 +0000441 // FIXME: the following language option is a temporary workaround,
442 // to "ask for ObjC, get ObjC++" (see comment above).
443 m_compiler->getLangOpts().CPlusPlus = true;
Sean Callananc7b65062011-11-07 23:35:40 +0000444 break;
445 case lldb::eLanguageTypeC_plus_plus:
Dawn Perchik009d1102015-09-04 01:02:30 +0000446 case lldb::eLanguageTypeC_plus_plus_11:
447 case lldb::eLanguageTypeC_plus_plus_14:
Chandler Carruth38336a12013-01-02 12:55:00 +0000448 m_compiler->getLangOpts().CPlusPlus11 = true;
Jim Ingham26c7bf92014-10-11 00:38:27 +0000449 m_compiler->getHeaderSearchOpts().UseLibcxx = true;
Jason Molenda62e06812016-02-16 04:14:33 +0000450 LLVM_FALLTHROUGH;
Dawn Perchik009d1102015-09-04 01:02:30 +0000451 case lldb::eLanguageTypeC_plus_plus_03:
452 m_compiler->getLangOpts().CPlusPlus = true;
453 // FIXME: the following language option is a temporary workaround,
454 // to "ask for C++, get ObjC++". Apple hopes to remove this requirement
455 // on non-Apple platforms, but for now it is needed.
456 m_compiler->getLangOpts().ObjC1 = true;
Sean Callananc7b65062011-11-07 23:35:40 +0000457 break;
458 case lldb::eLanguageTypeObjC_plus_plus:
Dawn Perchik009d1102015-09-04 01:02:30 +0000459 case lldb::eLanguageTypeUnknown:
Sean Callananc7b65062011-11-07 23:35:40 +0000460 default:
461 m_compiler->getLangOpts().ObjC1 = true;
462 m_compiler->getLangOpts().ObjC2 = true;
463 m_compiler->getLangOpts().CPlusPlus = true;
Chandler Carruth38336a12013-01-02 12:55:00 +0000464 m_compiler->getLangOpts().CPlusPlus11 = true;
Jim Ingham26c7bf92014-10-11 00:38:27 +0000465 m_compiler->getHeaderSearchOpts().UseLibcxx = true;
Sean Callananc7b65062011-11-07 23:35:40 +0000466 break;
467 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000468
Sean Callananaa0f9cb2012-10-17 22:09:59 +0000469 m_compiler->getLangOpts().Bool = true;
470 m_compiler->getLangOpts().WChar = true;
Sean Callananeeb43842013-04-01 22:12:37 +0000471 m_compiler->getLangOpts().Blocks = true;
Sean Callanan226b70c2012-03-08 02:39:03 +0000472 m_compiler->getLangOpts().DebuggerSupport = true; // Features specifically for debugger clients
Jim Ingham151c0322015-09-15 21:13:50 +0000473 if (expr.DesiredResultType() == Expression::eResultTypeId)
Sean Callanan226b70c2012-03-08 02:39:03 +0000474 m_compiler->getLangOpts().DebuggerCastResultToId = true;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000475
Tamas Berghammerdccbfaf2015-03-31 10:21:50 +0000476 m_compiler->getLangOpts().CharIsSigned =
477 ArchSpec(m_compiler->getTargetOpts().Triple.c_str()).CharIsSignedByDefault();
478
Sean Callanan0765c822012-04-17 00:49:48 +0000479 // Spell checking is a nice feature, but it ends up completing a
480 // lot of types that we didn't strictly speaking need to complete.
481 // As a result, we spend a long time parsing and importing debug
482 // information.
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000483 m_compiler->getLangOpts().SpellChecking = false;
484
Greg Claytond9e416c2012-02-18 05:35:26 +0000485 lldb::ProcessSP process_sp;
Greg Clayton514487e2011-02-15 21:59:32 +0000486 if (exe_scope)
Greg Claytond9e416c2012-02-18 05:35:26 +0000487 process_sp = exe_scope->CalculateProcess();
Greg Clayton514487e2011-02-15 21:59:32 +0000488
Greg Claytond9e416c2012-02-18 05:35:26 +0000489 if (process_sp && m_compiler->getLangOpts().ObjC1)
Sean Callananc3a16002011-01-17 23:42:46 +0000490 {
Greg Claytond9e416c2012-02-18 05:35:26 +0000491 if (process_sp->GetObjCLanguageRuntime())
Sean Callananc3a16002011-01-17 23:42:46 +0000492 {
Enrico Granata15a67f492015-09-23 20:12:19 +0000493 if (process_sp->GetObjCLanguageRuntime()->GetRuntimeVersion() == ObjCLanguageRuntime::ObjCRuntimeVersions::eAppleObjC_V2)
Sean Callanan3d654b32012-09-24 22:25:51 +0000494 m_compiler->getLangOpts().ObjCRuntime.set(ObjCRuntime::MacOSX, VersionTuple(10, 7));
495 else
496 m_compiler->getLangOpts().ObjCRuntime.set(ObjCRuntime::FragileMacOSX, VersionTuple(10, 7));
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000497
Sean Callanan226b70c2012-03-08 02:39:03 +0000498 if (process_sp->GetObjCLanguageRuntime()->HasNewLiteralsAndIndexing())
Sean Callanan226b70c2012-03-08 02:39:03 +0000499 m_compiler->getLangOpts().DebuggerObjCLiteral = true;
Sean Callananc3a16002011-01-17 23:42:46 +0000500 }
501 }
Greg Claytonf83f32d2011-01-15 01:32:14 +0000502
Sean Callanan1a8d4092010-08-27 01:01:44 +0000503 m_compiler->getLangOpts().ThreadsafeStatics = false;
504 m_compiler->getLangOpts().AccessControl = false; // Debuggers get universal access
505 m_compiler->getLangOpts().DollarIdents = true; // $ indicates a persistent variable name
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000506
Sean Callanan1a8d4092010-08-27 01:01:44 +0000507 // Set CodeGen options
508 m_compiler->getCodeGenOpts().EmitDeclMetadata = true;
509 m_compiler->getCodeGenOpts().InstrumentFunctions = false;
Greg Claytonbc3122e2013-11-04 19:50:49 +0000510 m_compiler->getCodeGenOpts().DisableFPElim = true;
511 m_compiler->getCodeGenOpts().OmitLeafFramePointer = false;
Greg Clayton23f8c952014-03-24 23:10:19 +0000512 if (generate_debug_info)
Pavel Labathe03bd652016-02-02 13:07:27 +0000513 m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::FullDebugInfo);
Greg Clayton23f8c952014-03-24 23:10:19 +0000514 else
Pavel Labathe03bd652016-02-02 13:07:27 +0000515 m_compiler->getCodeGenOpts().setDebugInfo(codegenoptions::NoDebugInfo);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000516
Sean Callanan1a8d4092010-08-27 01:01:44 +0000517 // Disable some warnings.
Hafiz Abid Qadeer101e4902014-08-07 12:54:20 +0000518 m_compiler->getDiagnostics().setSeverityForGroup(clang::diag::Flavor::WarningOrError,
Alp Toker10933d12014-06-12 11:14:32 +0000519 "unused-value", clang::diag::Severity::Ignored, SourceLocation());
Hafiz Abid Qadeer101e4902014-08-07 12:54:20 +0000520 m_compiler->getDiagnostics().setSeverityForGroup(clang::diag::Flavor::WarningOrError,
Alp Toker10933d12014-06-12 11:14:32 +0000521 "odr", clang::diag::Severity::Ignored, SourceLocation());
522
Sean Callanan1a8d4092010-08-27 01:01:44 +0000523 // Inform the target of the language options
524 //
525 // FIXME: We shouldn't need to do this, the target should be immutable once
526 // created. This complexity should be lifted elsewhere.
Sylvestre Ledru3cc9d632014-07-06 17:50:36 +0000527 m_compiler->getTarget().adjust(m_compiler->getLangOpts());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000528
Aidan Dodds1b6785a2016-02-03 12:33:05 +0000529 // 6. Set up the diagnostic buffer for reporting errors
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000530
Sean Callanan579e70c2016-03-19 00:03:59 +0000531 m_compiler->getDiagnostics().setClient(new ClangDiagnosticManagerAdapter);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000532
Aidan Dodds1b6785a2016-02-03 12:33:05 +0000533 // 7. Set up the source management objects inside the compiler
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000534
Greg Clayton38a61402010-12-02 23:20:03 +0000535 clang::FileSystemOptions file_system_options;
536 m_file_manager.reset(new clang::FileManager(file_system_options));
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000537
Sean Callanan1a8d4092010-08-27 01:01:44 +0000538 if (!m_compiler->hasSourceManager())
Greg Clayton38a61402010-12-02 23:20:03 +0000539 m_compiler->createSourceManager(*m_file_manager.get());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000540
Sean Callanan1a8d4092010-08-27 01:01:44 +0000541 m_compiler->createFileManager();
Ben Langmuir9f0bac52014-03-07 08:31:36 +0000542 m_compiler->createPreprocessor(TU_Complete);
Sean Callananc8278af2014-12-05 01:27:35 +0000543
544 if (ClangModulesDeclVendor *decl_vendor = target_sp->GetClangModulesDeclVendor())
545 {
Sean Callananb92bd752015-10-01 16:28:02 +0000546 ClangPersistentVariables *clang_persistent_vars = llvm::cast<ClangPersistentVariables>(target_sp->GetPersistentExpressionStateForLanguage(lldb::eLanguageTypeC));
Sean Callanan8f1f9a12015-09-30 19:57:57 +0000547 std::unique_ptr<PPCallbacks> pp_callbacks(new LLDBPreprocessorCallbacks(*decl_vendor, *clang_persistent_vars));
Sean Callananc8278af2014-12-05 01:27:35 +0000548 m_pp_callbacks = static_cast<LLDBPreprocessorCallbacks*>(pp_callbacks.get());
549 m_compiler->getPreprocessor().addPPCallbacks(std::move(pp_callbacks));
550 }
551
Aidan Dodds1b6785a2016-02-03 12:33:05 +0000552 // 8. Most of this we get from the CompilerInstance, but we
Sean Callanan1a8d4092010-08-27 01:01:44 +0000553 // also want to give the context an ExternalASTSource.
Sean Callanan6abfabf2010-11-19 20:20:02 +0000554 m_selector_table.reset(new SelectorTable());
Sean Callanan880e6802011-10-07 23:18:13 +0000555 m_builtin_context.reset(new Builtin::Context());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000556
Greg Clayton7b0992d2013-04-18 22:45:39 +0000557 std::unique_ptr<clang::ASTContext> ast_context(new ASTContext(m_compiler->getLangOpts(),
Sean Callananf0c5aeb2015-04-20 16:31:29 +0000558 m_compiler->getSourceManager(),
559 m_compiler->getPreprocessor().getIdentifierTable(),
560 *m_selector_table.get(),
561 *m_builtin_context.get()));
Sean Callananc8278af2014-12-05 01:27:35 +0000562
Alp Tokercf55e882014-05-03 15:05:45 +0000563 ast_context->InitBuiltinTypes(m_compiler->getTarget());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000564
Jim Ingham151c0322015-09-15 21:13:50 +0000565 ClangExpressionHelper *type_system_helper = dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
566 ClangExpressionDeclMap *decl_map = type_system_helper->DeclMap();
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000567
Sean Callanan1a8d4092010-08-27 01:01:44 +0000568 if (decl_map)
569 {
Sylvestre Ledru7ba631f2014-02-27 10:46:57 +0000570 llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> ast_source(decl_map->CreateProxy());
Sean Callananeddeb3b2011-10-28 23:38:38 +0000571 decl_map->InstallASTContext(ast_context.get());
Sean Callanan1a8d4092010-08-27 01:01:44 +0000572 ast_context->setExternalSource(ast_source);
573 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000574
Greg Claytond8d4a572015-08-11 21:38:15 +0000575 m_ast_context.reset(new ClangASTContext(m_compiler->getTargetOpts().Triple.c_str()));
576 m_ast_context->setASTContext(ast_context.get());
Sean Callanan1a8d4092010-08-27 01:01:44 +0000577 m_compiler->setASTContext(ast_context.release());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000578
Greg Clayton7b462cc2010-10-15 22:48:33 +0000579 std::string module_name("$__lldb_module");
Sean Callanan1a8d4092010-08-27 01:01:44 +0000580
Sean Callananfb0b7582011-03-15 00:17:19 +0000581 m_llvm_context.reset(new LLVMContext());
Sean Callanan1a8d4092010-08-27 01:01:44 +0000582 m_code_generator.reset(CreateLLVMCodeGen(m_compiler->getDiagnostics(),
583 module_name,
Tamas Berghammer0b736f12015-06-30 09:26:52 +0000584 m_compiler->getHeaderSearchOpts(),
585 m_compiler->getPreprocessorOpts(),
Sean Callanan1a8d4092010-08-27 01:01:44 +0000586 m_compiler->getCodeGenOpts(),
Sean Callananfb0b7582011-03-15 00:17:19 +0000587 *m_llvm_context));
Sean Callanan1a8d4092010-08-27 01:01:44 +0000588}
589
590ClangExpressionParser::~ClangExpressionParser()
591{
592}
593
594unsigned
Sean Callanan579e70c2016-03-19 00:03:59 +0000595ClangExpressionParser::Parse(DiagnosticManager &diagnostic_manager)
Sean Callanan1a8d4092010-08-27 01:01:44 +0000596{
Sean Callanan579e70c2016-03-19 00:03:59 +0000597 ClangDiagnosticManagerAdapter *adapter =
598 static_cast<ClangDiagnosticManagerAdapter *>(m_compiler->getDiagnostics().getClient());
599 clang::TextDiagnosticBuffer *diag_buf = adapter->GetPassthrough();
Ewan Crawford615a8072016-02-19 17:55:10 +0000600 diag_buf->FlushDiagnostics(m_compiler->getDiagnostics());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000601
Sean Callanan579e70c2016-03-19 00:03:59 +0000602 adapter->ResetManager(&diagnostic_manager);
603
Greg Clayton23f8c952014-03-24 23:10:19 +0000604 const char *expr_text = m_expr.Text();
Rafael Espindola9cb97b62014-05-21 15:08:27 +0000605
Ewan Crawford615a8072016-02-19 17:55:10 +0000606 clang::SourceManager &source_mgr = m_compiler->getSourceManager();
Greg Clayton23f8c952014-03-24 23:10:19 +0000607 bool created_main_file = false;
Pavel Labathe03bd652016-02-02 13:07:27 +0000608 if (m_compiler->getCodeGenOpts().getDebugInfo() == codegenoptions::FullDebugInfo)
Greg Clayton23f8c952014-03-24 23:10:19 +0000609 {
Zachary Turnercb5742b2014-10-20 17:46:56 +0000610 int temp_fd = -1;
611 llvm::SmallString<PATH_MAX> result_path;
Greg Clayton23f8c952014-03-24 23:10:19 +0000612 FileSpec tmpdir_file_spec;
Zachary Turner42ff0ad2014-08-21 17:29:12 +0000613 if (HostInfo::GetLLDBPath(lldb::ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
Greg Clayton23f8c952014-03-24 23:10:19 +0000614 {
Zachary Turnercb5742b2014-10-20 17:46:56 +0000615 tmpdir_file_spec.AppendPathComponent("lldb-%%%%%%.expr");
Ewan Crawford615a8072016-02-19 17:55:10 +0000616 std::string temp_source_path = tmpdir_file_spec.GetPath();
Zachary Turnercb5742b2014-10-20 17:46:56 +0000617 llvm::sys::fs::createUniqueFile(temp_source_path, temp_fd, result_path);
Greg Clayton23f8c952014-03-24 23:10:19 +0000618 }
619 else
620 {
Zachary Turnercb5742b2014-10-20 17:46:56 +0000621 llvm::sys::fs::createTemporaryFile("lldb", "expr", temp_fd, result_path);
Greg Clayton23f8c952014-03-24 23:10:19 +0000622 }
Ewan Crawford615a8072016-02-19 17:55:10 +0000623
Jason Molendabc464ee2014-10-16 23:10:03 +0000624 if (temp_fd != -1)
Greg Clayton23f8c952014-03-24 23:10:19 +0000625 {
Ewan Crawford615a8072016-02-19 17:55:10 +0000626 lldb_private::File file(temp_fd, true);
Greg Clayton23f8c952014-03-24 23:10:19 +0000627 const size_t expr_text_len = strlen(expr_text);
628 size_t bytes_written = expr_text_len;
629 if (file.Write(expr_text, bytes_written).Success())
630 {
631 if (bytes_written == expr_text_len)
632 {
633 file.Close();
Ewan Crawford615a8072016-02-19 17:55:10 +0000634 source_mgr.setMainFileID(source_mgr.createFileID(m_file_manager->getFile(result_path),
635 SourceLocation(), SrcMgr::C_User));
Greg Clayton23f8c952014-03-24 23:10:19 +0000636 created_main_file = true;
637 }
638 }
639 }
640 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000641
Greg Clayton23f8c952014-03-24 23:10:19 +0000642 if (!created_main_file)
643 {
Rafael Espindola2443e702014-08-27 20:09:08 +0000644 std::unique_ptr<MemoryBuffer> memory_buffer = MemoryBuffer::getMemBufferCopy(expr_text, __FUNCTION__);
Ewan Crawford615a8072016-02-19 17:55:10 +0000645 source_mgr.setMainFileID(source_mgr.createFileID(std::move(memory_buffer)));
Greg Clayton23f8c952014-03-24 23:10:19 +0000646 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000647
Sean Callanane2ef6e32010-09-23 03:01:22 +0000648 diag_buf->BeginSourceFile(m_compiler->getLangOpts(), &m_compiler->getPreprocessor());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000649
Jim Ingham151c0322015-09-15 21:13:50 +0000650 ClangExpressionHelper *type_system_helper = dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000651
Jim Ingham151c0322015-09-15 21:13:50 +0000652 ASTConsumer *ast_transformer = type_system_helper->ASTTransformer(m_code_generator.get());
653
654 if (ClangExpressionDeclMap *decl_map = type_system_helper->DeclMap())
Sean Callanan80c97592015-05-01 00:47:29 +0000655 decl_map->InstallCodeGenerator(m_code_generator.get());
Chaoren Lin57998de2015-08-19 01:24:57 +0000656
Sean Callanan1a8d4092010-08-27 01:01:44 +0000657 if (ast_transformer)
Chaoren Lin57998de2015-08-19 01:24:57 +0000658 {
659 ast_transformer->Initialize(m_compiler->getASTContext());
Sean Callanan1a8d4092010-08-27 01:01:44 +0000660 ParseAST(m_compiler->getPreprocessor(), ast_transformer, m_compiler->getASTContext());
Chaoren Lin57998de2015-08-19 01:24:57 +0000661 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000662 else
Chaoren Lin57998de2015-08-19 01:24:57 +0000663 {
664 m_code_generator->Initialize(m_compiler->getASTContext());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000665 ParseAST(m_compiler->getPreprocessor(), m_code_generator.get(), m_compiler->getASTContext());
Chaoren Lin57998de2015-08-19 01:24:57 +0000666 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000667
Sean Callanane2ef6e32010-09-23 03:01:22 +0000668 diag_buf->EndSourceFile();
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000669
Ewan Crawford615a8072016-02-19 17:55:10 +0000670 unsigned num_errors = diag_buf->getNumErrors();
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000671
Zachary Turner22ac8712014-12-05 22:54:56 +0000672 if (m_pp_callbacks && m_pp_callbacks->hasErrors())
Sean Callananc8278af2014-12-05 01:27:35 +0000673 {
674 num_errors++;
Sean Callanan579e70c2016-03-19 00:03:59 +0000675 diagnostic_manager.PutCString(eDiagnosticSeverityError, "while importing modules:");
676 diagnostic_manager.AppendMessageToDiagnostic(m_pp_callbacks->getErrorString().c_str());
Sean Callananc8278af2014-12-05 01:27:35 +0000677 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000678
Sean Callanan77502262011-05-12 23:54:16 +0000679 if (!num_errors)
680 {
Jim Ingham151c0322015-09-15 21:13:50 +0000681 if (type_system_helper->DeclMap() && !type_system_helper->DeclMap()->ResolveUnknownTypes())
Sean Callanan77502262011-05-12 23:54:16 +0000682 {
Sean Callanan579e70c2016-03-19 00:03:59 +0000683 diagnostic_manager.Printf(eDiagnosticSeverityError, "Couldn't infer the type of a variable");
Sean Callanan77502262011-05-12 23:54:16 +0000684 num_errors++;
685 }
686 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000687
Sean Callanan00294b32016-03-22 21:05:51 +0000688 if (!num_errors)
689 {
690 type_system_helper->CommitPersistentDecls();
691 }
692
Sean Callanan579e70c2016-03-19 00:03:59 +0000693 adapter->ResetManager();
694
Sean Callanan1a8d4092010-08-27 01:01:44 +0000695 return num_errors;
696}
697
Jim Inghama1e541b2016-03-25 01:57:14 +0000698bool
699ClangExpressionParser::RewriteExpression(DiagnosticManager &diagnostic_manager)
700{
701 clang::SourceManager &source_manager = m_compiler->getSourceManager();
702 clang::edit::EditedSource editor(source_manager, m_compiler->getLangOpts(), nullptr);
703 clang::edit::Commit commit(editor);
704 clang::Rewriter rewriter(source_manager, m_compiler->getLangOpts());
705
706 class RewritesReceiver : public edit::EditsReceiver {
707 Rewriter &rewrite;
708
709 public:
710 RewritesReceiver(Rewriter &in_rewrite) : rewrite(in_rewrite) { }
711
712 void insert(SourceLocation loc, StringRef text) override {
713 rewrite.InsertText(loc, text);
714 }
715 void replace(CharSourceRange range, StringRef text) override {
716 rewrite.ReplaceText(range.getBegin(), rewrite.getRangeSize(range), text);
717 }
718 };
719
720 RewritesReceiver rewrites_receiver(rewriter);
721
722 const DiagnosticList &diagnostics = diagnostic_manager.Diagnostics();
723 size_t num_diags = diagnostics.size();
724 if (num_diags == 0)
725 return false;
726
727 for (const Diagnostic *diag : diagnostic_manager.Diagnostics())
728 {
729 const ClangDiagnostic *diagnostic = llvm::dyn_cast<ClangDiagnostic>(diag);
730 if (diagnostic && diagnostic->HasFixIts())
731 {
732 for (const FixItHint &fixit : diagnostic->FixIts())
733 {
734 // This is cobbed from clang::Rewrite::FixItRewriter.
735 if (fixit.CodeToInsert.empty())
736 {
737 if (fixit.InsertFromRange.isValid())
738 {
739 commit.insertFromRange(fixit.RemoveRange.getBegin(),
740 fixit.InsertFromRange, /*afterToken=*/false,
741 fixit.BeforePreviousInsertions);
742 }
743 else
744 commit.remove(fixit.RemoveRange);
745 }
746 else
747 {
748 if (fixit.RemoveRange.isTokenRange() ||
749 fixit.RemoveRange.getBegin() != fixit.RemoveRange.getEnd())
750 commit.replace(fixit.RemoveRange, fixit.CodeToInsert);
751 else
752 commit.insert(fixit.RemoveRange.getBegin(), fixit.CodeToInsert,
753 /*afterToken=*/false, fixit.BeforePreviousInsertions);
754 }
755 }
756 }
757 }
758
759 // FIXME - do we want to try to propagate specific errors here?
760 if (!commit.isCommitable())
761 return false;
762 else if (!editor.commit(commit))
763 return false;
764
765 // Now play all the edits, and stash the result in the diagnostic manager.
766 editor.applyRewrites(rewrites_receiver);
767 RewriteBuffer &main_file_buffer = rewriter.getEditBuffer(source_manager.getMainFileID());
768
769 std::string fixed_expression;
770 llvm::raw_string_ostream out_stream(fixed_expression);
771
772 main_file_buffer.write(out_stream);
773 out_stream.flush();
774 diagnostic_manager.SetFixedExpression(fixed_expression);
775
776 return true;
777}
778
Sean Callanan8dfb68e2013-03-19 00:10:07 +0000779static bool FindFunctionInModule (ConstString &mangled_name,
Sean Callananfc55f5d2010-09-21 00:44:12 +0000780 llvm::Module *module,
781 const char *orig_name)
782{
Aidan Doddsb1298472016-02-25 13:07:04 +0000783 for (const auto &func : module->getFunctionList())
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000784 {
Aidan Doddsb1298472016-02-25 13:07:04 +0000785 const StringRef &name = func.getName();
786 if (name.find(orig_name) != StringRef::npos)
Sean Callananfc55f5d2010-09-21 00:44:12 +0000787 {
Aidan Doddsb1298472016-02-25 13:07:04 +0000788 mangled_name.SetString(name);
Sean Callananfc55f5d2010-09-21 00:44:12 +0000789 return true;
790 }
791 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000792
Sean Callananfc55f5d2010-09-21 00:44:12 +0000793 return false;
794}
795
Sean Callanan1a8d4092010-08-27 01:01:44 +0000796Error
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000797ClangExpressionParser::PrepareForExecution (lldb::addr_t &func_addr,
Sean Callanan5a1af4e2013-04-05 02:22:57 +0000798 lldb::addr_t &func_end,
Jim Inghamc29e6982015-11-05 01:50:42 +0000799 lldb::IRExecutionUnitSP &execution_unit_sp,
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000800 ExecutionContext &exe_ctx,
Sean Callanan1582ee62013-04-18 22:06:33 +0000801 bool &can_interpret,
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000802 ExecutionPolicy execution_policy)
Sean Callanan1a8d4092010-08-27 01:01:44 +0000803{
Greg Clayton22a939a2011-01-19 23:00:49 +0000804 func_addr = LLDB_INVALID_ADDRESS;
805 func_end = LLDB_INVALID_ADDRESS;
Greg Clayton5160ce52013-03-27 23:08:40 +0000806 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callananfc55f5d2010-09-21 00:44:12 +0000807
Sean Callanan1a8d4092010-08-27 01:01:44 +0000808 Error err;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000809
Greg Clayton23f8c952014-03-24 23:10:19 +0000810 std::unique_ptr<llvm::Module> llvm_module_ap (m_code_generator->ReleaseModule());
Sean Callanan1a8d4092010-08-27 01:01:44 +0000811
Greg Clayton23f8c952014-03-24 23:10:19 +0000812 if (!llvm_module_ap.get())
Sean Callanan1a8d4092010-08-27 01:01:44 +0000813 {
814 err.SetErrorToGenericError();
815 err.SetErrorString("IR doesn't contain a module");
816 return err;
817 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000818
Sean Callanan8dfb68e2013-03-19 00:10:07 +0000819 ConstString function_name;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000820
Sean Callanan00294b32016-03-22 21:05:51 +0000821 if (execution_policy != eExecutionPolicyTopLevel)
Sean Callananfc55f5d2010-09-21 00:44:12 +0000822 {
Sean Callanan00294b32016-03-22 21:05:51 +0000823 // Find the actual name of the function (it's often mangled somehow)
824
825 if (!FindFunctionInModule(function_name, llvm_module_ap.get(), m_expr.FunctionName()))
826 {
827 err.SetErrorToGenericError();
828 err.SetErrorStringWithFormat("Couldn't find %s() in the module", m_expr.FunctionName());
829 return err;
830 }
831 else
832 {
833 if (log)
834 log->Printf("Found function %s for %s", function_name.AsCString(), m_expr.FunctionName());
835 }
Sean Callananfc55f5d2010-09-21 00:44:12 +0000836 }
Sean Callanan00294b32016-03-22 21:05:51 +0000837
Sean Callananb2814802016-02-12 21:11:25 +0000838 SymbolContext sc;
Sean Callanan00294b32016-03-22 21:05:51 +0000839
Sean Callananb2814802016-02-12 21:11:25 +0000840 if (lldb::StackFrameSP frame_sp = exe_ctx.GetFrameSP())
841 {
842 sc = frame_sp->GetSymbolContext(lldb::eSymbolContextEverything);
843 }
844 else if (lldb::TargetSP target_sp = exe_ctx.GetTargetSP())
845 {
846 sc.target_sp = target_sp;
847 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000848
Greg Clayton23f8c952014-03-24 23:10:19 +0000849 execution_unit_sp.reset(new IRExecutionUnit (m_llvm_context, // handed off here
850 llvm_module_ap, // handed off here
851 function_name,
852 exe_ctx.GetTargetSP(),
Sean Callananb2814802016-02-12 21:11:25 +0000853 sc,
Greg Clayton23f8c952014-03-24 23:10:19 +0000854 m_compiler->getTargetOpts().Features));
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000855
Jim Ingham151c0322015-09-15 21:13:50 +0000856 ClangExpressionHelper *type_system_helper = dyn_cast<ClangExpressionHelper>(m_expr.GetTypeSystemHelper());
857 ClangExpressionDeclMap *decl_map = type_system_helper->DeclMap(); // result can be NULL
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000858
Sean Callanan1a8d4092010-08-27 01:01:44 +0000859 if (decl_map)
860 {
Sean Callanan3989fb92011-01-27 01:07:04 +0000861 Stream *error_stream = NULL;
Greg Claytonc14ee322011-09-22 04:58:26 +0000862 Target *target = exe_ctx.GetTargetPtr();
863 if (target)
Greg Clayton44d93782014-01-27 23:43:24 +0000864 error_stream = target->GetDebugger().GetErrorFile().get();
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000865
Sean Callanan00294b32016-03-22 21:05:51 +0000866 IRForTarget ir_for_target(decl_map, m_expr.NeedsVariableResolution(), *execution_unit_sp, error_stream,
Sean Callanan8dfb68e2013-03-19 00:10:07 +0000867 function_name.AsCString());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000868
Greg Clayton23f8c952014-03-24 23:10:19 +0000869 bool ir_can_run = ir_for_target.runOnModule(*execution_unit_sp->GetModule());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000870
Greg Claytonc14ee322011-09-22 04:58:26 +0000871 Process *process = exe_ctx.GetProcessPtr();
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000872
Sean Callanan00294b32016-03-22 21:05:51 +0000873 if (execution_policy != eExecutionPolicyAlways && execution_policy != eExecutionPolicyTopLevel)
874 {
875 Error interpret_error;
Ewan Crawford90ff7912015-07-14 10:56:58 +0000876
Sean Callanan00294b32016-03-22 21:05:51 +0000877 bool interpret_function_calls = !process ? false : process->CanInterpretFunctionCalls();
878 can_interpret =
879 IRInterpreter::CanInterpret(*execution_unit_sp->GetModule(), *execution_unit_sp->GetFunction(),
880 interpret_error, interpret_function_calls);
881
882 if (!can_interpret && execution_policy == eExecutionPolicyNever)
883 {
884 err.SetErrorStringWithFormat("Can't run the expression locally: %s", interpret_error.AsCString());
885 return err;
886 }
887 }
Ewan Crawford90ff7912015-07-14 10:56:58 +0000888
Sean Callanan1582ee62013-04-18 22:06:33 +0000889 if (!ir_can_run)
Sean Callanan3bfdaa22011-09-15 02:13:07 +0000890 {
Sean Callanan3d654b32012-09-24 22:25:51 +0000891 err.SetErrorString("The expression could not be prepared to run in the target");
Sean Callanan3d654b32012-09-24 22:25:51 +0000892 return err;
893 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000894
Sean Callanan1582ee62013-04-18 22:06:33 +0000895 if (!process && execution_policy == eExecutionPolicyAlways)
896 {
897 err.SetErrorString("Expression needed to run in the target, but the target can't be run");
898 return err;
899 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000900
Sean Callanan00294b32016-03-22 21:05:51 +0000901 if (!process && execution_policy == eExecutionPolicyTopLevel)
902 {
903 err.SetErrorString(
904 "Top-level code needs to be inserted into a runnable target, but the target can't be run");
905 return err;
906 }
907
908 if (execution_policy == eExecutionPolicyAlways ||
909 (execution_policy != eExecutionPolicyTopLevel && !can_interpret))
Sean Callanan1582ee62013-04-18 22:06:33 +0000910 {
Sean Callanane8cde682013-05-18 00:38:20 +0000911 if (m_expr.NeedsValidation() && process)
912 {
913 if (!process->GetDynamicCheckers())
Sean Callanan90539452011-09-20 23:01:51 +0000914 {
Sean Callanane8cde682013-05-18 00:38:20 +0000915 DynamicCheckerFunctions *dynamic_checkers = new DynamicCheckerFunctions();
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000916
Sean Callanan579e70c2016-03-19 00:03:59 +0000917 DiagnosticManager install_diagnostics;
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000918
Sean Callanan579e70c2016-03-19 00:03:59 +0000919 if (!dynamic_checkers->Install(install_diagnostics, exe_ctx))
Sean Callanane8cde682013-05-18 00:38:20 +0000920 {
Sean Callanan579e70c2016-03-19 00:03:59 +0000921 if (install_diagnostics.Diagnostics().size())
922 err.SetErrorString("couldn't install checkers, unknown error");
Sean Callanane8cde682013-05-18 00:38:20 +0000923 else
Sean Callanan579e70c2016-03-19 00:03:59 +0000924 err.SetErrorString(install_diagnostics.GetString().c_str());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000925
Sean Callanane8cde682013-05-18 00:38:20 +0000926 return err;
927 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000928
Sean Callanane8cde682013-05-18 00:38:20 +0000929 process->SetDynamicCheckers(dynamic_checkers);
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000930
Sean Callanane8cde682013-05-18 00:38:20 +0000931 if (log)
932 log->Printf("== [ClangUserExpression::Evaluate] Finished installing dynamic checkers ==");
Sean Callanan90539452011-09-20 23:01:51 +0000933 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000934
Sean Callanan1582ee62013-04-18 22:06:33 +0000935 IRDynamicChecks ir_dynamic_checks(*process->GetDynamicCheckers(), function_name.AsCString());
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000936
Greg Clayton23f8c952014-03-24 23:10:19 +0000937 if (!ir_dynamic_checks.runOnModule(*execution_unit_sp->GetModule()))
Sean Callanan1582ee62013-04-18 22:06:33 +0000938 {
939 err.SetErrorToGenericError();
940 err.SetErrorString("Couldn't add dynamic checks to the expression");
941 return err;
942 }
Sean Callanan90539452011-09-20 23:01:51 +0000943 }
Sean Callanan00294b32016-03-22 21:05:51 +0000944 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000945
Sean Callanan00294b32016-03-22 21:05:51 +0000946 if (execution_policy == eExecutionPolicyAlways || execution_policy == eExecutionPolicyTopLevel ||
947 !can_interpret)
948 {
Greg Clayton23f8c952014-03-24 23:10:19 +0000949 execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);
Sean Callanan9e6ed532010-09-13 21:34:21 +0000950 }
Sean Callanan1a8d4092010-08-27 01:01:44 +0000951 }
Sean Callanan1582ee62013-04-18 22:06:33 +0000952 else
953 {
Greg Clayton23f8c952014-03-24 23:10:19 +0000954 execution_unit_sp->GetRunnableInfo(err, func_addr, func_end);
Sean Callanan1582ee62013-04-18 22:06:33 +0000955 }
Sylvestre Ledruceab3ac2014-07-06 17:54:58 +0000956
Sean Callanan1a8d4092010-08-27 01:01:44 +0000957 return err;
958}
Sean Callananbd4dc692016-03-21 22:23:38 +0000959
960Error
961ClangExpressionParser::RunStaticInitializers (lldb::IRExecutionUnitSP &execution_unit_sp,
962 ExecutionContext &exe_ctx)
963{
964 Error err;
965
966 lldbassert(execution_unit_sp.get());
967 lldbassert(exe_ctx.HasThreadScope());
968
969 if (!execution_unit_sp.get())
970 {
971 err.SetErrorString ("can't run static initializers for a NULL execution unit");
972 return err;
973 }
974
975 if (!exe_ctx.HasThreadScope())
976 {
977 err.SetErrorString ("can't run static initializers without a thread");
978 return err;
979 }
980
981 std::vector<lldb::addr_t> static_initializers;
982
983 execution_unit_sp->GetStaticInitializers(static_initializers);
984
985 for (lldb::addr_t static_initializer : static_initializers)
986 {
987 EvaluateExpressionOptions options;
988
989 lldb::ThreadPlanSP call_static_initializer(new ThreadPlanCallFunction(exe_ctx.GetThreadRef(),
990 Address(static_initializer),
991 CompilerType(),
992 llvm::ArrayRef<lldb::addr_t>(),
993 options));
994
995 DiagnosticManager execution_errors;
996 lldb::ExpressionResults results = exe_ctx.GetThreadRef().GetProcess()->RunThreadPlan(exe_ctx, call_static_initializer, options, execution_errors);
997
998 if (results != lldb::eExpressionCompleted)
999 {
1000 err.SetErrorStringWithFormat ("couldn't run static initializer: %s", execution_errors.GetString().c_str());
1001 return err;
1002 }
1003 }
1004
1005 return err;
1006}