blob: 921dc00c7f425d0e74b2c3e5dca53cb9de639521 [file] [log] [blame]
Sean Callanan65dafa82010-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
10#include "lldb/Expression/ClangExpressionParser.h"
11
12#include "lldb/Core/ArchSpec.h"
13#include "lldb/Core/DataBufferHeap.h"
Sean Callanan97c924e2011-01-27 01:07:04 +000014#include "lldb/Core/Debugger.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000015#include "lldb/Core/Disassembler.h"
16#include "lldb/Core/Stream.h"
Sean Callananf18d91c2010-09-01 00:58:00 +000017#include "lldb/Core/StreamString.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000018#include "lldb/Expression/ClangASTSource.h"
19#include "lldb/Expression/ClangExpression.h"
Sean Callananfb3058e2011-05-12 23:54:16 +000020#include "lldb/Expression/ClangExpressionDeclMap.h"
Sean Callananf18d91c2010-09-01 00:58:00 +000021#include "lldb/Expression/IRDynamicChecks.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000022#include "lldb/Expression/RecordingMemoryManager.h"
23#include "lldb/Target/ExecutionContext.h"
Sean Callananc7674af2011-01-17 23:42:46 +000024#include "lldb/Target/ObjCLanguageRuntime.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000025#include "lldb/Target/Process.h"
26#include "lldb/Target/Target.h"
27
28#include "clang/AST/ASTContext.h"
29#include "clang/AST/ExternalASTSource.h"
30#include "clang/Basic/FileManager.h"
31#include "clang/Basic/TargetInfo.h"
32#include "clang/Basic/Version.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000033#include "clang/CodeGen/CodeGenAction.h"
34#include "clang/CodeGen/ModuleBuilder.h"
35#include "clang/Driver/CC1Options.h"
36#include "clang/Driver/OptTable.h"
37#include "clang/Frontend/CompilerInstance.h"
38#include "clang/Frontend/CompilerInvocation.h"
39#include "clang/Frontend/FrontendActions.h"
40#include "clang/Frontend/FrontendDiagnostic.h"
41#include "clang/Frontend/FrontendPluginRegistry.h"
42#include "clang/Frontend/TextDiagnosticBuffer.h"
43#include "clang/Frontend/TextDiagnosticPrinter.h"
44#include "clang/Frontend/VerifyDiagnosticsClient.h"
45#include "clang/Lex/Preprocessor.h"
Sean Callanan47a5c4c2010-09-23 03:01:22 +000046#include "clang/Parse/ParseAST.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000047#include "clang/Rewrite/FrontendActions.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000048#include "clang/Sema/SemaConsumer.h"
Sean Callanan279584c2011-03-15 00:17:19 +000049#include "clang/StaticAnalyzer/Frontend/FrontendActions.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000050
51#include "llvm/ADT/StringRef.h"
52#include "llvm/ExecutionEngine/ExecutionEngine.h"
Greg Clayton2f085c62011-05-15 01:25:55 +000053
Peter Collingbournec3f55732011-06-03 20:40:12 +000054#if !defined(__APPLE__)
55#define USE_STANDARD_JIT
56#endif
57
Greg Clayton2f085c62011-05-15 01:25:55 +000058#if defined (USE_STANDARD_JIT)
Sean Callanan65dafa82010-08-27 01:01:44 +000059#include "llvm/ExecutionEngine/JIT.h"
Greg Clayton2f085c62011-05-15 01:25:55 +000060#else
61#include "llvm/ExecutionEngine/MCJIT.h"
62#endif
Sean Callanan65dafa82010-08-27 01:01:44 +000063#include "llvm/LLVMContext.h"
Sean Callanan279584c2011-03-15 00:17:19 +000064#include "llvm/Module.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000065#include "llvm/Support/ErrorHandling.h"
66#include "llvm/Support/MemoryBuffer.h"
Greg Clayton22defe82010-12-02 23:20:03 +000067#include "llvm/Support/DynamicLibrary.h"
68#include "llvm/Support/Host.h"
69#include "llvm/Support/Signals.h"
Sean Callanan65dafa82010-08-27 01:01:44 +000070#include "llvm/Target/TargetRegistry.h"
71#include "llvm/Target/TargetSelect.h"
72
73using namespace clang;
74using namespace llvm;
75using namespace lldb_private;
76
77//===----------------------------------------------------------------------===//
78// Utility Methods for Clang
79//===----------------------------------------------------------------------===//
80
81std::string GetBuiltinIncludePath(const char *Argv0) {
82 llvm::sys::Path P =
83 llvm::sys::Path::GetMainExecutable(Argv0,
84 (void*)(intptr_t) GetBuiltinIncludePath);
85
86 if (!P.isEmpty()) {
87 P.eraseComponent(); // Remove /clang from foo/bin/clang
88 P.eraseComponent(); // Remove /bin from foo/bin
89
90 // Get foo/lib/clang/<version>/include
91 P.appendComponent("lib");
92 P.appendComponent("clang");
93 P.appendComponent(CLANG_VERSION_STRING);
94 P.appendComponent("include");
95 }
96
97 return P.str();
98}
99
100
101//===----------------------------------------------------------------------===//
102// Main driver for Clang
103//===----------------------------------------------------------------------===//
104
105static void LLVMErrorHandler(void *UserData, const std::string &Message) {
106 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
107
108 Diags.Report(diag::err_fe_error_backend) << Message;
109
110 // We cannot recover from llvm errors.
111 exit(1);
112}
113
114static FrontendAction *CreateFrontendBaseAction(CompilerInstance &CI) {
115 using namespace clang::frontend;
116
117 switch (CI.getFrontendOpts().ProgramAction) {
118 default:
119 llvm_unreachable("Invalid program action!");
120
121 case ASTDump: return new ASTDumpAction();
122 case ASTPrint: return new ASTPrintAction();
Sean Callanan279584c2011-03-15 00:17:19 +0000123 case ASTDumpXML: return new ASTDumpXMLAction();
Sean Callanan65dafa82010-08-27 01:01:44 +0000124 case ASTView: return new ASTViewAction();
Sean Callanan65dafa82010-08-27 01:01:44 +0000125 case DumpRawTokens: return new DumpRawTokensAction();
126 case DumpTokens: return new DumpTokensAction();
127 case EmitAssembly: return new EmitAssemblyAction();
128 case EmitBC: return new EmitBCAction();
129 case EmitHTML: return new HTMLPrintAction();
130 case EmitLLVM: return new EmitLLVMAction();
131 case EmitLLVMOnly: return new EmitLLVMOnlyAction();
132 case EmitCodeGenOnly: return new EmitCodeGenOnlyAction();
133 case EmitObj: return new EmitObjAction();
134 case FixIt: return new FixItAction();
135 case GeneratePCH: return new GeneratePCHAction();
136 case GeneratePTH: return new GeneratePTHAction();
Sean Callanan65dafa82010-08-27 01:01:44 +0000137 case InitOnly: return new InitOnlyAction();
138 case ParseSyntaxOnly: return new SyntaxOnlyAction();
139
140 case PluginAction: {
141 for (FrontendPluginRegistry::iterator it =
142 FrontendPluginRegistry::begin(), ie = FrontendPluginRegistry::end();
143 it != ie; ++it) {
144 if (it->getName() == CI.getFrontendOpts().ActionName) {
145 llvm::OwningPtr<PluginASTAction> P(it->instantiate());
146 if (!P->ParseArgs(CI, CI.getFrontendOpts().PluginArgs))
147 return 0;
148 return P.take();
149 }
150 }
151
152 CI.getDiagnostics().Report(diag::err_fe_invalid_plugin_name)
153 << CI.getFrontendOpts().ActionName;
154 return 0;
155 }
156
157 case PrintDeclContext: return new DeclContextPrintAction();
158 case PrintPreamble: return new PrintPreambleAction();
159 case PrintPreprocessedInput: return new PrintPreprocessedAction();
160 case RewriteMacros: return new RewriteMacrosAction();
161 case RewriteObjC: return new RewriteObjCAction();
162 case RewriteTest: return new RewriteTestAction();
Sean Callananad293092011-01-18 23:32:05 +0000163 //case RunAnalysis: return new AnalysisAction();
Sean Callanan65dafa82010-08-27 01:01:44 +0000164 case RunPreprocessorOnly: return new PreprocessOnlyAction();
165 }
166}
167
168static FrontendAction *CreateFrontendAction(CompilerInstance &CI) {
169 // Create the underlying action.
170 FrontendAction *Act = CreateFrontendBaseAction(CI);
171 if (!Act)
172 return 0;
173
174 // If there are any AST files to merge, create a frontend action
175 // adaptor to perform the merge.
176 if (!CI.getFrontendOpts().ASTMergeFiles.empty())
177 Act = new ASTMergeAction(Act, &CI.getFrontendOpts().ASTMergeFiles[0],
178 CI.getFrontendOpts().ASTMergeFiles.size());
179
180 return Act;
181}
182
183//===----------------------------------------------------------------------===//
184// Implementation of ClangExpressionParser
185//===----------------------------------------------------------------------===//
186
Greg Clayton395fc332011-02-15 21:59:32 +0000187ClangExpressionParser::ClangExpressionParser (ExecutionContextScope *exe_scope,
188 ClangExpression &expr) :
189 m_expr (expr),
Sean Callanan65dafa82010-08-27 01:01:44 +0000190 m_compiler (),
191 m_code_generator (NULL),
192 m_execution_engine (),
193 m_jitted_functions ()
194{
195 // Initialize targets first, so that --version shows registered targets.
196 static struct InitializeLLVM {
197 InitializeLLVM() {
198 llvm::InitializeAllTargets();
199 llvm::InitializeAllAsmPrinters();
Sean Callanan9b6898f2011-07-30 02:42:06 +0000200 llvm::InitializeAllTargetMCs();
Sean Callanan65dafa82010-08-27 01:01:44 +0000201 }
202 } InitializeLLVM;
Greg Clayton395fc332011-02-15 21:59:32 +0000203
Sean Callanan65dafa82010-08-27 01:01:44 +0000204 // 1. Create a new compiler instance.
205 m_compiler.reset(new CompilerInstance());
Sean Callanan65dafa82010-08-27 01:01:44 +0000206
207 // 2. Set options.
208
209 // Parse expressions as Objective C++ regardless of context.
210 // Our hook into Clang's lookup mechanism only works in C++.
211 m_compiler->getLangOpts().CPlusPlus = true;
Greg Claytonf51ed302011-01-15 01:32:14 +0000212
213 // Setup objective C
Sean Callanan65dafa82010-08-27 01:01:44 +0000214 m_compiler->getLangOpts().ObjC1 = true;
Greg Claytonf51ed302011-01-15 01:32:14 +0000215 m_compiler->getLangOpts().ObjC2 = true;
Sean Callananc7674af2011-01-17 23:42:46 +0000216
Greg Clayton395fc332011-02-15 21:59:32 +0000217 Process *process = NULL;
218 if (exe_scope)
219 process = exe_scope->CalculateProcess();
220
Sean Callananc7674af2011-01-17 23:42:46 +0000221 if (process)
222 {
223 if (process->GetObjCLanguageRuntime())
224 {
Greg Claytonb3448432011-03-24 21:19:54 +0000225 if (process->GetObjCLanguageRuntime()->GetRuntimeVersion() == eAppleObjC_V2)
Sean Callananc7674af2011-01-17 23:42:46 +0000226 {
227 m_compiler->getLangOpts().ObjCNonFragileABI = true; // NOT i386
228 m_compiler->getLangOpts().ObjCNonFragileABI2 = true; // NOT i386
229 }
230 }
231 }
Greg Claytonf51ed302011-01-15 01:32:14 +0000232
Sean Callanan65dafa82010-08-27 01:01:44 +0000233 m_compiler->getLangOpts().ThreadsafeStatics = false;
234 m_compiler->getLangOpts().AccessControl = false; // Debuggers get universal access
235 m_compiler->getLangOpts().DollarIdents = true; // $ indicates a persistent variable name
Sean Callanan24312442011-08-23 21:20:51 +0000236 //m_compiler->getLangOpts().DebuggerSupport = true; // Features specifically for debugger clients
Sean Callanan65dafa82010-08-27 01:01:44 +0000237
238 // Set CodeGen options
239 m_compiler->getCodeGenOpts().EmitDeclMetadata = true;
240 m_compiler->getCodeGenOpts().InstrumentFunctions = false;
241
242 // Disable some warnings.
243 m_compiler->getDiagnosticOpts().Warnings.push_back("no-unused-value");
244
245 // Set the target triple.
Greg Clayton395fc332011-02-15 21:59:32 +0000246 Target *target = NULL;
247 if (exe_scope)
248 target = exe_scope->CalculateTarget();
249
250 // TODO: figure out what to really do when we don't have a valid target.
251 // Sometimes this will be ok to just use the host target triple (when we
252 // evaluate say "2+3", but other expressions like breakpoint conditions
253 // and other things that _are_ target specific really shouldn't just be
254 // using the host triple. This needs to be fixed in a better way.
255 if (target && target->GetArchitecture().IsValid())
Sean Callanan2a8c3382011-04-14 02:01:31 +0000256 {
257 std::string triple = target->GetArchitecture().GetTriple().str();
258
259 int dash_count = 0;
Johnny Chen2bc9eb32011-07-19 19:48:13 +0000260 for (size_t i = 0; i < triple.size(); ++i)
Sean Callanan2a8c3382011-04-14 02:01:31 +0000261 {
262 if (triple[i] == '-')
263 dash_count++;
264 if (dash_count == 3)
265 {
266 triple.resize(i);
267 break;
268 }
269 }
270
271 m_compiler->getTargetOpts().Triple = triple;
272 }
Greg Clayton395fc332011-02-15 21:59:32 +0000273 else
Sean Callanan2a8c3382011-04-14 02:01:31 +0000274 {
Greg Clayton395fc332011-02-15 21:59:32 +0000275 m_compiler->getTargetOpts().Triple = llvm::sys::getHostTriple();
Sean Callanan2a8c3382011-04-14 02:01:31 +0000276 }
277
Sean Callanan65dafa82010-08-27 01:01:44 +0000278 // 3. Set up various important bits of infrastructure.
279 m_compiler->createDiagnostics(0, 0);
280
281 // Create the target instance.
282 m_compiler->setTarget(TargetInfo::CreateTargetInfo(m_compiler->getDiagnostics(),
283 m_compiler->getTargetOpts()));
284
285 assert (m_compiler->hasTarget());
286
287 // Inform the target of the language options
288 //
289 // FIXME: We shouldn't need to do this, the target should be immutable once
290 // created. This complexity should be lifted elsewhere.
291 m_compiler->getTarget().setForcedLangOptions(m_compiler->getLangOpts());
292
293 // 4. Set up the diagnostic buffer for reporting errors
294
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000295 m_compiler->getDiagnostics().setClient(new clang::TextDiagnosticBuffer);
Sean Callanan65dafa82010-08-27 01:01:44 +0000296
297 // 5. Set up the source management objects inside the compiler
298
Greg Clayton22defe82010-12-02 23:20:03 +0000299 clang::FileSystemOptions file_system_options;
300 m_file_manager.reset(new clang::FileManager(file_system_options));
Sean Callanan8a3b0a82010-11-18 02:56:27 +0000301
Sean Callanan65dafa82010-08-27 01:01:44 +0000302 if (!m_compiler->hasSourceManager())
Greg Clayton22defe82010-12-02 23:20:03 +0000303 m_compiler->createSourceManager(*m_file_manager.get());
Sean Callanan65dafa82010-08-27 01:01:44 +0000304
305 m_compiler->createFileManager();
306 m_compiler->createPreprocessor();
307
308 // 6. Most of this we get from the CompilerInstance, but we
309 // also want to give the context an ExternalASTSource.
Sean Callananee8fc722010-11-19 20:20:02 +0000310 m_selector_table.reset(new SelectorTable());
Sean Callanan65dafa82010-08-27 01:01:44 +0000311 m_builtin_context.reset(new Builtin::Context(m_compiler->getTarget()));
312
313 std::auto_ptr<clang::ASTContext> ast_context(new ASTContext(m_compiler->getLangOpts(),
314 m_compiler->getSourceManager(),
315 m_compiler->getTarget(),
316 m_compiler->getPreprocessor().getIdentifierTable(),
Sean Callananee8fc722010-11-19 20:20:02 +0000317 *m_selector_table.get(),
Sean Callanan65dafa82010-08-27 01:01:44 +0000318 *m_builtin_context.get(),
319 0));
320
321 ClangExpressionDeclMap *decl_map = m_expr.DeclMap();
322
323 if (decl_map)
324 {
325 OwningPtr<clang::ExternalASTSource> ast_source(new ClangASTSource(*ast_context, *decl_map));
326 ast_context->setExternalSource(ast_source);
327 }
328
329 m_compiler->setASTContext(ast_context.release());
330
Greg Clayton8de27c72010-10-15 22:48:33 +0000331 std::string module_name("$__lldb_module");
Sean Callanan65dafa82010-08-27 01:01:44 +0000332
Sean Callanan279584c2011-03-15 00:17:19 +0000333 m_llvm_context.reset(new LLVMContext());
Sean Callanan65dafa82010-08-27 01:01:44 +0000334 m_code_generator.reset(CreateLLVMCodeGen(m_compiler->getDiagnostics(),
335 module_name,
336 m_compiler->getCodeGenOpts(),
Sean Callanan279584c2011-03-15 00:17:19 +0000337 *m_llvm_context));
Sean Callanan65dafa82010-08-27 01:01:44 +0000338}
339
340ClangExpressionParser::~ClangExpressionParser()
341{
342}
343
344unsigned
345ClangExpressionParser::Parse (Stream &stream)
346{
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000347 TextDiagnosticBuffer *diag_buf = static_cast<TextDiagnosticBuffer*>(m_compiler->getDiagnostics().getClient());
348
349 diag_buf->FlushDiagnostics (m_compiler->getDiagnostics());
Sean Callanan65dafa82010-08-27 01:01:44 +0000350
351 MemoryBuffer *memory_buffer = MemoryBuffer::getMemBufferCopy(m_expr.Text(), __FUNCTION__);
352 FileID memory_buffer_file_id = m_compiler->getSourceManager().createMainFileIDForMemBuffer (memory_buffer);
353
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000354 diag_buf->BeginSourceFile(m_compiler->getLangOpts(), &m_compiler->getPreprocessor());
Sean Callanan65dafa82010-08-27 01:01:44 +0000355
356 ASTConsumer *ast_transformer = m_expr.ASTTransformer(m_code_generator.get());
357
358 if (ast_transformer)
359 ParseAST(m_compiler->getPreprocessor(), ast_transformer, m_compiler->getASTContext());
360 else
361 ParseAST(m_compiler->getPreprocessor(), m_code_generator.get(), m_compiler->getASTContext());
362
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000363 diag_buf->EndSourceFile();
Sean Callananfb3058e2011-05-12 23:54:16 +0000364
Sean Callanan65dafa82010-08-27 01:01:44 +0000365 TextDiagnosticBuffer::const_iterator diag_iterator;
366
367 int num_errors = 0;
Sean Callanan7617c292010-11-01 20:28:09 +0000368
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000369 for (diag_iterator = diag_buf->warn_begin();
370 diag_iterator != diag_buf->warn_end();
Sean Callanan65dafa82010-08-27 01:01:44 +0000371 ++diag_iterator)
372 stream.Printf("warning: %s\n", (*diag_iterator).second.c_str());
373
374 num_errors = 0;
375
Sean Callanan47a5c4c2010-09-23 03:01:22 +0000376 for (diag_iterator = diag_buf->err_begin();
377 diag_iterator != diag_buf->err_end();
Sean Callanan65dafa82010-08-27 01:01:44 +0000378 ++diag_iterator)
379 {
380 num_errors++;
381 stream.Printf("error: %s\n", (*diag_iterator).second.c_str());
382 }
383
Sean Callanan7617c292010-11-01 20:28:09 +0000384 for (diag_iterator = diag_buf->note_begin();
385 diag_iterator != diag_buf->note_end();
386 ++diag_iterator)
387 stream.Printf("note: %s\n", (*diag_iterator).second.c_str());
388
Sean Callananfb3058e2011-05-12 23:54:16 +0000389 if (!num_errors)
390 {
391 if (m_expr.DeclMap() && !m_expr.DeclMap()->ResolveUnknownTypes())
392 {
393 stream.Printf("error: Couldn't infer the type of a variable\n");
394 num_errors++;
395 }
396 }
397
Sean Callanan65dafa82010-08-27 01:01:44 +0000398 return num_errors;
399}
400
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000401static bool FindFunctionInModule (std::string &mangled_name,
402 llvm::Module *module,
403 const char *orig_name)
404{
405 for (llvm::Module::iterator fi = module->getFunctionList().begin(), fe = module->getFunctionList().end();
406 fi != fe;
407 ++fi)
408 {
409 if (fi->getName().str().find(orig_name) != std::string::npos)
410 {
411 mangled_name = fi->getName().str();
412 return true;
413 }
414 }
415
416 return false;
417}
418
Sean Callanan65dafa82010-08-27 01:01:44 +0000419Error
Sean Callanan47dc4572011-09-15 02:13:07 +0000420ClangExpressionParser::PrepareForExecution (lldb::addr_t &func_allocation_addr,
421 lldb::addr_t &func_addr,
422 lldb::addr_t &func_end,
423 ExecutionContext &exe_ctx,
424 IRForTarget::StaticDataAllocator *data_allocator,
425 bool &evaluated_statically,
426 lldb::ClangExpressionVariableSP &const_result,
427 ExecutionPolicy execution_policy)
Sean Callanan65dafa82010-08-27 01:01:44 +0000428{
Greg Claytond0882d02011-01-19 23:00:49 +0000429 func_allocation_addr = LLDB_INVALID_ADDRESS;
430 func_addr = LLDB_INVALID_ADDRESS;
431 func_end = LLDB_INVALID_ADDRESS;
Greg Claytone005f2c2010-11-06 01:53:30 +0000432 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000433
Sean Callanan65dafa82010-08-27 01:01:44 +0000434 Error err;
435
436 llvm::Module *module = m_code_generator->ReleaseModule();
437
438 if (!module)
439 {
440 err.SetErrorToGenericError();
441 err.SetErrorString("IR doesn't contain a module");
442 return err;
443 }
444
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000445 // Find the actual name of the function (it's often mangled somehow)
446
447 std::string function_name;
448
449 if (!FindFunctionInModule(function_name, module, m_expr.FunctionName()))
450 {
451 err.SetErrorToGenericError();
452 err.SetErrorStringWithFormat("Couldn't find %s() in the module", m_expr.FunctionName());
453 return err;
454 }
455 else
456 {
Enrico Granata4c3fb4b2011-07-19 18:03:25 +0000457 if (log)
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000458 log->Printf("Found function %s for %s", function_name.c_str(), m_expr.FunctionName());
459 }
460
Sean Callanan65dafa82010-08-27 01:01:44 +0000461 ClangExpressionDeclMap *decl_map = m_expr.DeclMap(); // result can be NULL
462
463 if (decl_map)
464 {
Sean Callanan97c924e2011-01-27 01:07:04 +0000465 Stream *error_stream = NULL;
466
467 if (exe_ctx.target)
468 error_stream = &exe_ctx.target->GetDebugger().GetErrorStream();
469
Sean Callanan47dc4572011-09-15 02:13:07 +0000470 IRForTarget ir_for_target(decl_map,
Sean Callanane8a59a82010-09-13 21:34:21 +0000471 m_expr.NeedsVariableResolution(),
Sean Callanan47dc4572011-09-15 02:13:07 +0000472 execution_policy,
Sean Callanan05a5a1b2010-12-16 03:17:46 +0000473 const_result,
Sean Callananc0492742011-05-23 21:40:23 +0000474 data_allocator,
Sean Callanan97c924e2011-01-27 01:07:04 +0000475 error_stream,
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000476 function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000477
478 if (!ir_for_target.runOnModule(*module))
479 {
480 err.SetErrorToGenericError();
Sean Callanan47dc4572011-09-15 02:13:07 +0000481 err.SetErrorString("Couldn't prepare the expression for execution in the target");
Sean Callanan65dafa82010-08-27 01:01:44 +0000482 return err;
483 }
Sean Callananf18d91c2010-09-01 00:58:00 +0000484
Sean Callanan47dc4572011-09-15 02:13:07 +0000485 if (execution_policy != eExecutionPolicyAlways && ir_for_target.interpretSuccess())
Sean Callanan696cf5f2011-05-07 01:06:41 +0000486 {
Sean Callanan47dc4572011-09-15 02:13:07 +0000487 evaluated_statically = true;
Sean Callanan696cf5f2011-05-07 01:06:41 +0000488 err.Clear();
489 return err;
490 }
491
Sean Callanan47dc4572011-09-15 02:13:07 +0000492 if (!exe_ctx.process || execution_policy == eExecutionPolicyNever)
493 {
494 err.SetErrorToGenericError();
495 err.SetErrorString("Execution needed to run in the target, but the target can't be run");
496 return err;
497 }
498
499 if (m_expr.NeedsValidation() && exe_ctx.process && exe_ctx.process->GetDynamicCheckers())
Sean Callananf18d91c2010-09-01 00:58:00 +0000500 {
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000501 IRDynamicChecks ir_dynamic_checks(*exe_ctx.process->GetDynamicCheckers(), function_name.c_str());
Sean Callanane8a59a82010-09-13 21:34:21 +0000502
503 if (!ir_dynamic_checks.runOnModule(*module))
504 {
505 err.SetErrorToGenericError();
506 err.SetErrorString("Couldn't add dynamic checks to the expression");
507 return err;
508 }
509 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000510 }
511
Greg Claytond0882d02011-01-19 23:00:49 +0000512 // llvm will own this pointer when llvm::ExecutionEngine::createJIT is called
513 // below so we don't need to free it.
514 RecordingMemoryManager *jit_memory_manager = new RecordingMemoryManager();
Sean Callanan65dafa82010-08-27 01:01:44 +0000515
516 std::string error_string;
Sean Callanan9b6898f2011-07-30 02:42:06 +0000517
Greg Clayton2f085c62011-05-15 01:25:55 +0000518#if defined (USE_STANDARD_JIT)
Sean Callanan65dafa82010-08-27 01:01:44 +0000519 m_execution_engine.reset(llvm::ExecutionEngine::createJIT (module,
520 &error_string,
Greg Claytond0882d02011-01-19 23:00:49 +0000521 jit_memory_manager,
Sean Callananc2c6f772010-10-26 00:31:56 +0000522 CodeGenOpt::Less,
Sean Callanan65dafa82010-08-27 01:01:44 +0000523 true,
Peter Collingbournec4d4fb52011-07-30 22:42:24 +0000524 Reloc::Default,
Sean Callanan65dafa82010-08-27 01:01:44 +0000525 CodeModel::Small));
Greg Clayton2f085c62011-05-15 01:25:55 +0000526#else
527 EngineBuilder builder(module);
528 builder.setEngineKind(EngineKind::JIT)
529 .setErrorStr(&error_string)
Sean Callanan9b6898f2011-07-30 02:42:06 +0000530 .setRelocationModel(llvm::Reloc::PIC_)
Greg Clayton2f085c62011-05-15 01:25:55 +0000531 .setJITMemoryManager(jit_memory_manager)
532 .setOptLevel(CodeGenOpt::Less)
533 .setAllocateGVsWithCode(true)
534 .setCodeModel(CodeModel::Small)
Sean Callanan9b6898f2011-07-30 02:42:06 +0000535 .setUseMCJIT(true);
Greg Clayton2f085c62011-05-15 01:25:55 +0000536 m_execution_engine.reset(builder.create());
537#endif
Sean Callanan9ac3a962010-11-02 23:20:00 +0000538
Sean Callanan65dafa82010-08-27 01:01:44 +0000539 if (!m_execution_engine.get())
540 {
541 err.SetErrorToGenericError();
542 err.SetErrorStringWithFormat("Couldn't JIT the function: %s", error_string.c_str());
543 return err;
544 }
545
546 m_execution_engine->DisableLazyCompilation();
547
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000548 llvm::Function *function = module->getFunction (function_name.c_str());
Sean Callanan65dafa82010-08-27 01:01:44 +0000549
550 // We don't actually need the function pointer here, this just forces it to get resolved.
551
552 void *fun_ptr = m_execution_engine->getPointerToFunction(function);
553
554 // Errors usually cause failures in the JIT, but if we're lucky we get here.
555
556 if (!fun_ptr)
557 {
558 err.SetErrorToGenericError();
559 err.SetErrorString("Couldn't JIT the function");
560 return err;
561 }
562
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000563 m_jitted_functions.push_back (ClangExpressionParser::JittedFunction(function_name.c_str(), (lldb::addr_t)fun_ptr));
Sean Callanan65dafa82010-08-27 01:01:44 +0000564
565 ExecutionContext &exc_context(exe_ctx);
566
567 if (exc_context.process == NULL)
568 {
569 err.SetErrorToGenericError();
570 err.SetErrorString("Couldn't write the JIT compiled code into the target because there is no target");
571 return err;
572 }
573
574 // Look over the regions allocated for the function compiled. The JIT
575 // tries to allocate the functions & stubs close together, so we should try to
576 // write them that way too...
577 // For now I only write functions with no stubs, globals, exception tables,
578 // etc. So I only need to write the functions.
579
580 size_t alloc_size = 0;
581
Greg Claytond0882d02011-01-19 23:00:49 +0000582 std::map<uint8_t *, uint8_t *>::iterator fun_pos = jit_memory_manager->m_functions.begin();
583 std::map<uint8_t *, uint8_t *>::iterator fun_end = jit_memory_manager->m_functions.end();
Greg Clayton9d2b3212011-05-15 23:56:52 +0000584
Sean Callanan65dafa82010-08-27 01:01:44 +0000585 for (; fun_pos != fun_end; ++fun_pos)
Greg Clayton9d2b3212011-05-15 23:56:52 +0000586 {
587 size_t mem_size = fun_pos->second - fun_pos->first;
588 if (log)
589 log->Printf ("JIT memory: [%p - %p) size = %zu", fun_pos->first, fun_pos->second, mem_size);
590 alloc_size += mem_size;
591 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000592
593 Error alloc_error;
Greg Claytond0882d02011-01-19 23:00:49 +0000594 func_allocation_addr = exc_context.process->AllocateMemory (alloc_size,
595 lldb::ePermissionsReadable|lldb::ePermissionsExecutable,
596 alloc_error);
Sean Callanan65dafa82010-08-27 01:01:44 +0000597
Greg Claytond0882d02011-01-19 23:00:49 +0000598 if (func_allocation_addr == LLDB_INVALID_ADDRESS)
Sean Callanan65dafa82010-08-27 01:01:44 +0000599 {
600 err.SetErrorToGenericError();
601 err.SetErrorStringWithFormat("Couldn't allocate memory for the JITted function: %s", alloc_error.AsCString("unknown error"));
602 return err;
603 }
604
Greg Claytond0882d02011-01-19 23:00:49 +0000605 lldb::addr_t cursor = func_allocation_addr;
Sean Callanan65dafa82010-08-27 01:01:44 +0000606
Greg Claytond0882d02011-01-19 23:00:49 +0000607 for (fun_pos = jit_memory_manager->m_functions.begin(); fun_pos != fun_end; fun_pos++)
Sean Callanan65dafa82010-08-27 01:01:44 +0000608 {
609 lldb::addr_t lstart = (lldb::addr_t) (*fun_pos).first;
610 lldb::addr_t lend = (lldb::addr_t) (*fun_pos).second;
611 size_t size = lend - lstart;
612
613 Error write_error;
614
615 if (exc_context.process->WriteMemory(cursor, (void *) lstart, size, write_error) != size)
616 {
617 err.SetErrorToGenericError();
Greg Claytonc0fa5332011-05-22 22:46:53 +0000618 err.SetErrorStringWithFormat("Couldn't copy JIT code for function into the target: %s", write_error.AsCString("unknown error"));
Sean Callanan65dafa82010-08-27 01:01:44 +0000619 return err;
620 }
621
Greg Claytond0882d02011-01-19 23:00:49 +0000622 jit_memory_manager->AddToLocalToRemoteMap (lstart, size, cursor);
Sean Callanan65dafa82010-08-27 01:01:44 +0000623 cursor += size;
624 }
625
626 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
627
628 for (pos = m_jitted_functions.begin(); pos != end; pos++)
629 {
Greg Claytond0882d02011-01-19 23:00:49 +0000630 (*pos).m_remote_addr = jit_memory_manager->GetRemoteAddressForLocal ((*pos).m_local_addr);
Sean Callanan65dafa82010-08-27 01:01:44 +0000631
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000632 if (!(*pos).m_name.compare(function_name.c_str()))
Sean Callanan830a9032010-08-27 23:31:21 +0000633 {
Greg Claytond0882d02011-01-19 23:00:49 +0000634 func_end = jit_memory_manager->GetRemoteRangeForLocal ((*pos).m_local_addr).second;
Sean Callanan65dafa82010-08-27 01:01:44 +0000635 func_addr = (*pos).m_remote_addr;
Sean Callanan830a9032010-08-27 23:31:21 +0000636 }
Sean Callanan65dafa82010-08-27 01:01:44 +0000637 }
638
Sean Callanan6dff8272010-11-08 03:49:50 +0000639 if (log)
640 {
641 log->Printf("Code can be run in the target.");
642
643 StreamString disassembly_stream;
644
Greg Claytond0882d02011-01-19 23:00:49 +0000645 Error err = DisassembleFunction(disassembly_stream, exe_ctx, jit_memory_manager);
Sean Callanan6dff8272010-11-08 03:49:50 +0000646
647 if (!err.Success())
648 {
649 log->Printf("Couldn't disassemble function : %s", err.AsCString("unknown error"));
650 }
651 else
652 {
653 log->Printf("Function disassembly:\n%s", disassembly_stream.GetData());
654 }
655 }
656
Sean Callanan65dafa82010-08-27 01:01:44 +0000657 err.Clear();
658 return err;
659}
660
661Error
Greg Claytond0882d02011-01-19 23:00:49 +0000662ClangExpressionParser::DisassembleFunction (Stream &stream, ExecutionContext &exe_ctx, RecordingMemoryManager *jit_memory_manager)
Sean Callanan65dafa82010-08-27 01:01:44 +0000663{
Greg Claytone005f2c2010-11-06 01:53:30 +0000664 lldb::LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
Sean Callanan65dafa82010-08-27 01:01:44 +0000665
666 const char *name = m_expr.FunctionName();
667
668 Error ret;
669
670 ret.Clear();
671
672 lldb::addr_t func_local_addr = LLDB_INVALID_ADDRESS;
673 lldb::addr_t func_remote_addr = LLDB_INVALID_ADDRESS;
674
675 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
676
677 for (pos = m_jitted_functions.begin(); pos < end; pos++)
678 {
Sean Callanan3c9c5eb2010-09-21 00:44:12 +0000679 if (strstr(pos->m_name.c_str(), name))
Sean Callanan65dafa82010-08-27 01:01:44 +0000680 {
681 func_local_addr = pos->m_local_addr;
682 func_remote_addr = pos->m_remote_addr;
683 }
684 }
685
686 if (func_local_addr == LLDB_INVALID_ADDRESS)
687 {
688 ret.SetErrorToGenericError();
689 ret.SetErrorStringWithFormat("Couldn't find function %s for disassembly", name);
690 return ret;
691 }
692
Enrico Granata4c3fb4b2011-07-19 18:03:25 +0000693 if (log)
Sean Callanan65dafa82010-08-27 01:01:44 +0000694 log->Printf("Found function, has local address 0x%llx and remote address 0x%llx", (uint64_t)func_local_addr, (uint64_t)func_remote_addr);
695
696 std::pair <lldb::addr_t, lldb::addr_t> func_range;
697
Greg Claytond0882d02011-01-19 23:00:49 +0000698 func_range = jit_memory_manager->GetRemoteRangeForLocal(func_local_addr);
Sean Callanan65dafa82010-08-27 01:01:44 +0000699
700 if (func_range.first == 0 && func_range.second == 0)
701 {
702 ret.SetErrorToGenericError();
703 ret.SetErrorStringWithFormat("Couldn't find code range for function %s", name);
704 return ret;
705 }
706
Enrico Granata4c3fb4b2011-07-19 18:03:25 +0000707 if (log)
Sean Callanan65dafa82010-08-27 01:01:44 +0000708 log->Printf("Function's code range is [0x%llx-0x%llx]", func_range.first, func_range.second);
709
710 if (!exe_ctx.target)
711 {
712 ret.SetErrorToGenericError();
713 ret.SetErrorString("Couldn't find the target");
714 }
715
716 lldb::DataBufferSP buffer_sp(new DataBufferHeap(func_range.second - func_remote_addr, 0));
717
718 Error err;
719 exe_ctx.process->ReadMemory(func_remote_addr, buffer_sp->GetBytes(), buffer_sp->GetByteSize(), err);
720
721 if (!err.Success())
722 {
723 ret.SetErrorToGenericError();
724 ret.SetErrorStringWithFormat("Couldn't read from process: %s", err.AsCString("unknown error"));
725 return ret;
726 }
727
728 ArchSpec arch(exe_ctx.target->GetArchitecture());
729
Greg Clayton149731c2011-03-25 18:03:16 +0000730 Disassembler *disassembler = Disassembler::FindPlugin(arch, NULL);
Sean Callanan65dafa82010-08-27 01:01:44 +0000731
732 if (disassembler == NULL)
733 {
734 ret.SetErrorToGenericError();
Greg Clayton940b1032011-02-23 00:35:02 +0000735 ret.SetErrorStringWithFormat("Unable to find disassembler plug-in for %s architecture.", arch.GetArchitectureName());
Sean Callanan65dafa82010-08-27 01:01:44 +0000736 return ret;
737 }
738
739 if (!exe_ctx.process)
740 {
741 ret.SetErrorToGenericError();
742 ret.SetErrorString("Couldn't find the process");
743 return ret;
744 }
745
746 DataExtractor extractor(buffer_sp,
747 exe_ctx.process->GetByteOrder(),
748 exe_ctx.target->GetArchitecture().GetAddressByteSize());
749
Greg Claytone005f2c2010-11-06 01:53:30 +0000750 if (log)
Sean Callanan65dafa82010-08-27 01:01:44 +0000751 {
752 log->Printf("Function data has contents:");
Greg Claytone005f2c2010-11-06 01:53:30 +0000753 extractor.PutToLog (log.get(),
Sean Callanan65dafa82010-08-27 01:01:44 +0000754 0,
755 extractor.GetByteSize(),
756 func_remote_addr,
757 16,
758 DataExtractor::TypeUInt8);
759 }
760
Jim Inghamaa3e3e12011-03-22 01:48:42 +0000761 disassembler->DecodeInstructions (Address (NULL, func_remote_addr), extractor, 0, UINT32_MAX, false);
Sean Callanan65dafa82010-08-27 01:01:44 +0000762
Greg Clayton5c4c7462010-10-06 03:09:58 +0000763 InstructionList &instruction_list = disassembler->GetInstructionList();
Greg Clayton889fbd02011-03-26 19:14:58 +0000764 const uint32_t max_opcode_byte_size = instruction_list.GetMaxOpcocdeByteSize();
Sean Callanan65dafa82010-08-27 01:01:44 +0000765 for (uint32_t instruction_index = 0, num_instructions = instruction_list.GetSize();
766 instruction_index < num_instructions;
767 ++instruction_index)
768 {
Greg Clayton5c4c7462010-10-06 03:09:58 +0000769 Instruction *instruction = instruction_list.GetInstructionAtIndex(instruction_index).get();
Sean Callanan65dafa82010-08-27 01:01:44 +0000770 instruction->Dump (&stream,
Greg Clayton889fbd02011-03-26 19:14:58 +0000771 max_opcode_byte_size,
Greg Clayton5c4c7462010-10-06 03:09:58 +0000772 true,
Greg Clayton149731c2011-03-25 18:03:16 +0000773 true,
Greg Clayton5c4c7462010-10-06 03:09:58 +0000774 &exe_ctx,
Sean Callanan65dafa82010-08-27 01:01:44 +0000775 true);
776 stream.PutChar('\n');
Sean Callanan65dafa82010-08-27 01:01:44 +0000777 }
778
779 return ret;
780}