blob: 5ec28a68b1692395ec4c8c57657f3bef4e9438c9 [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- ClangExpression.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// C Includes
11#include <stdio.h>
12#if HAVE_SYS_TYPES_H
13# include <sys/types.h>
14#endif
15
16// C++ Includes
17#include <cstdlib>
18#include <string>
19#include <map>
20
21// Other libraries and framework includes
22#include "clang/AST/ASTContext.h"
23#include "clang/AST/ExternalASTSource.h"
24#include "clang/Basic/FileManager.h"
25#include "clang/Basic/TargetInfo.h"
26#include "clang/Basic/Version.h"
Greg Claytonc4f51102010-07-02 18:39:06 +000027#include "clang/Checker/FrontendActions.h"
28#include "clang/CodeGen/CodeGenAction.h"
Chris Lattner24943d22010-06-08 16:52:24 +000029#include "clang/CodeGen/ModuleBuilder.h"
30#include "clang/Driver/CC1Options.h"
31#include "clang/Driver/OptTable.h"
Chris Lattner24943d22010-06-08 16:52:24 +000032#include "clang/Frontend/CompilerInstance.h"
33#include "clang/Frontend/CompilerInvocation.h"
34#include "clang/Frontend/FrontendActions.h"
35#include "clang/Frontend/FrontendDiagnostic.h"
36#include "clang/Frontend/FrontendPluginRegistry.h"
37#include "clang/Frontend/TextDiagnosticBuffer.h"
38#include "clang/Frontend/TextDiagnosticPrinter.h"
39#include "clang/Frontend/VerifyDiagnosticsClient.h"
40#include "clang/Lex/Preprocessor.h"
Greg Claytonc4f51102010-07-02 18:39:06 +000041#include "clang/Rewrite/FrontendActions.h"
Chris Lattner24943d22010-06-08 16:52:24 +000042#include "clang/Sema/ParseAST.h"
Sean Callanan8c6934d2010-07-01 20:08:22 +000043#include "clang/Sema/SemaConsumer.h"
Chris Lattner24943d22010-06-08 16:52:24 +000044#include "llvm/ExecutionEngine/ExecutionEngine.h"
45#include "llvm/ExecutionEngine/JIT.h"
46#include "llvm/Module.h"
47#include "llvm/ADT/StringRef.h"
48#include "llvm/LLVMContext.h"
49#include "llvm/Support/MemoryBuffer.h"
50#include "llvm/System/DynamicLibrary.h"
51#include "llvm/System/Host.h"
52#include "llvm/System/Signals.h"
Sean Callanan8bce6652010-07-13 21:41:46 +000053#include "llvm/Target/TargetRegistry.h"
Chris Lattner24943d22010-06-08 16:52:24 +000054#include "llvm/Target/TargetSelect.h"
55
56// Project includes
Sean Callanan848960c2010-06-23 23:18:04 +000057#include "lldb/Core/Log.h"
Greg Clayton1674b122010-07-21 22:12:05 +000058#include "lldb/Core/ClangForward.h"
Sean Callanan8541f2f2010-07-23 02:19:15 +000059#include "lldb/Core/DataBufferHeap.h"
60#include "lldb/Core/Disassembler.h"
Chris Lattner24943d22010-06-08 16:52:24 +000061#include "lldb/Expression/ClangExpression.h"
62#include "lldb/Expression/ClangASTSource.h"
Sean Callanan8c6934d2010-07-01 20:08:22 +000063#include "lldb/Expression/ClangResultSynthesizer.h"
Chris Lattner24943d22010-06-08 16:52:24 +000064#include "lldb/Expression/ClangStmtVisitor.h"
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000065#include "lldb/Expression/IRForTarget.h"
Sean Callanandcb658b2010-07-02 21:09:36 +000066#include "lldb/Expression/IRToDWARF.h"
Chris Lattner24943d22010-06-08 16:52:24 +000067#include "lldb/Symbol/ClangASTContext.h"
68#include "lldb/Expression/RecordingMemoryManager.h"
69#include "lldb/Target/ExecutionContext.h"
70#include "lldb/Target/Process.h"
Sean Callanan8541f2f2010-07-23 02:19:15 +000071#include "lldb/Target/Target.h"
Chris Lattner24943d22010-06-08 16:52:24 +000072
Chris Lattner24943d22010-06-08 16:52:24 +000073#include "lldb/Core/StreamString.h"
74#include "lldb/Host/Mutex.h"
Chris Lattner24943d22010-06-08 16:52:24 +000075
76
77using namespace lldb_private;
78using namespace clang;
79using namespace llvm;
80
Chris Lattner24943d22010-06-08 16:52:24 +000081
82//===----------------------------------------------------------------------===//
83// Utility Methods
84//===----------------------------------------------------------------------===//
85
86std::string GetBuiltinIncludePath(const char *Argv0) {
87 llvm::sys::Path P =
88 llvm::sys::Path::GetMainExecutable(Argv0,
89 (void*)(intptr_t) GetBuiltinIncludePath);
90
91 if (!P.isEmpty()) {
92 P.eraseComponent(); // Remove /clang from foo/bin/clang
93 P.eraseComponent(); // Remove /bin from foo/bin
94
95 // Get foo/lib/clang/<version>/include
96 P.appendComponent("lib");
97 P.appendComponent("clang");
98 P.appendComponent(CLANG_VERSION_STRING);
99 P.appendComponent("include");
100 }
101
102 return P.str();
103}
104
105
106//===----------------------------------------------------------------------===//
107// Main driver
108//===----------------------------------------------------------------------===//
109
Greg Clayton6e713402010-07-30 20:30:44 +0000110//===----------------------------------------------------------------------===//
111// Main driver
112//===----------------------------------------------------------------------===//
Chris Lattner24943d22010-06-08 16:52:24 +0000113
Greg Clayton6e713402010-07-30 20:30:44 +0000114static void LLVMErrorHandler(void *UserData, const std::string &Message) {
115 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
Chris Lattner24943d22010-06-08 16:52:24 +0000116
Greg Clayton6e713402010-07-30 20:30:44 +0000117 Diags.Report(diag::err_fe_error_backend) << Message;
118
119 // We cannot recover from llvm errors.
120 exit(1);
Chris Lattner24943d22010-06-08 16:52:24 +0000121}
122
123static FrontendAction *CreateFrontendBaseAction(CompilerInstance &CI) {
Greg Clayton6e713402010-07-30 20:30:44 +0000124 using namespace clang::frontend;
Chris Lattner24943d22010-06-08 16:52:24 +0000125
Greg Clayton6e713402010-07-30 20:30:44 +0000126 switch (CI.getFrontendOpts().ProgramAction) {
127 default:
128 llvm_unreachable("Invalid program action!");
Chris Lattner24943d22010-06-08 16:52:24 +0000129
Greg Clayton6e713402010-07-30 20:30:44 +0000130 case ASTDump: return new ASTDumpAction();
131 case ASTPrint: return new ASTPrintAction();
132 case ASTPrintXML: return new ASTPrintXMLAction();
133 case ASTView: return new ASTViewAction();
134 case BoostCon: return new BoostConAction();
135 case DumpRawTokens: return new DumpRawTokensAction();
136 case DumpTokens: return new DumpTokensAction();
137 case EmitAssembly: return new EmitAssemblyAction();
138 case EmitBC: return new EmitBCAction();
139 case EmitHTML: return new HTMLPrintAction();
140 case EmitLLVM: return new EmitLLVMAction();
141 case EmitLLVMOnly: return new EmitLLVMOnlyAction();
142 case EmitCodeGenOnly: return new EmitCodeGenOnlyAction();
143 case EmitObj: return new EmitObjAction();
144 case FixIt: return new FixItAction();
145 case GeneratePCH: return new GeneratePCHAction();
146 case GeneratePTH: return new GeneratePTHAction();
147 case InheritanceView: return new InheritanceViewAction();
148 case InitOnly: return new InitOnlyAction();
149 case ParseSyntaxOnly: return new SyntaxOnlyAction();
Chris Lattner24943d22010-06-08 16:52:24 +0000150
Greg Clayton6e713402010-07-30 20:30:44 +0000151 case PluginAction: {
Chris Lattner24943d22010-06-08 16:52:24 +0000152
Greg Clayton6e713402010-07-30 20:30:44 +0000153 for (FrontendPluginRegistry::iterator it =
154 FrontendPluginRegistry::begin(), ie = FrontendPluginRegistry::end();
155 it != ie; ++it) {
156 if (it->getName() == CI.getFrontendOpts().ActionName) {
157 PluginASTAction* plugin = it->instantiate();
158 plugin->ParseArgs(CI.getFrontendOpts().PluginArgs);
159 return plugin;
160 }
Chris Lattner24943d22010-06-08 16:52:24 +0000161 }
Greg Clayton6e713402010-07-30 20:30:44 +0000162
163 CI.getDiagnostics().Report(diag::err_fe_invalid_plugin_name)
164 << CI.getFrontendOpts().ActionName;
165 return 0;
166 }
167
168 case PrintDeclContext: return new DeclContextPrintAction();
169 case PrintPreamble: return new PrintPreambleAction();
170 case PrintPreprocessedInput: return new PrintPreprocessedAction();
171 case RewriteMacros: return new RewriteMacrosAction();
172 case RewriteObjC: return new RewriteObjCAction();
173 case RewriteTest: return new RewriteTestAction();
174 case RunAnalysis: return new AnalysisAction();
175 case RunPreprocessorOnly: return new PreprocessOnlyAction();
176 }
177}
178
179static FrontendAction *CreateFrontendAction(CompilerInstance &CI) {
180 // Create the underlying action.
181 FrontendAction *Act = CreateFrontendBaseAction(CI);
182 if (!Act)
183 return 0;
184
185 // If there are any AST files to merge, create a frontend action
186 // adaptor to perform the merge.
187 if (!CI.getFrontendOpts().ASTMergeFiles.empty())
188 Act = new ASTMergeAction(Act, &CI.getFrontendOpts().ASTMergeFiles[0],
189 CI.getFrontendOpts().ASTMergeFiles.size());
190
191 return Act;
Chris Lattner24943d22010-06-08 16:52:24 +0000192}
193
194//----------------------------------------------------------------------
195// ClangExpression constructor
196//----------------------------------------------------------------------
197ClangExpression::ClangExpression(const char *target_triple,
198 ClangExpressionDeclMap *decl_map) :
199 m_target_triple (),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000200 m_decl_map (decl_map),
201 m_clang_ap (),
Chris Lattner24943d22010-06-08 16:52:24 +0000202 m_code_generator_ptr (NULL),
Greg Clayton54e7afa2010-07-09 20:39:50 +0000203 m_jit_mm_ptr (NULL),
204 m_execution_engine (),
205 m_jitted_functions ()
Chris Lattner24943d22010-06-08 16:52:24 +0000206{
207 if (target_triple && target_triple[0])
208 m_target_triple = target_triple;
209 else
210 m_target_triple = llvm::sys::getHostTriple();
211}
212
213
214//----------------------------------------------------------------------
215// Destructor
216//----------------------------------------------------------------------
217ClangExpression::~ClangExpression()
218{
219 if (m_code_generator_ptr && !m_execution_engine.get())
220 delete m_code_generator_ptr;
221}
222
223bool
224ClangExpression::CreateCompilerInstance (bool &IsAST)
225{
226 // Initialize targets first, so that --version shows registered targets.
227 static struct InitializeLLVM {
228 InitializeLLVM() {
229 llvm::InitializeAllTargets();
230 llvm::InitializeAllAsmPrinters();
231 }
232 } InitializeLLVM;
233
234 // 1. Create a new compiler instance.
235 m_clang_ap.reset(new CompilerInstance());
236 m_clang_ap->setLLVMContext(new LLVMContext());
237
238 // 2. Set options.
239
240 // Parse expressions as Objective C++ regardless of context.
241 // Our hook into Clang's lookup mechanism only works in C++.
242 m_clang_ap->getLangOpts().CPlusPlus = true;
243 m_clang_ap->getLangOpts().ObjC1 = true;
Sean Callanan051052f2010-07-02 22:22:28 +0000244 m_clang_ap->getLangOpts().ThreadsafeStatics = false;
Sean Callanan8bce6652010-07-13 21:41:46 +0000245
246 // Set CodeGen options
247 m_clang_ap->getCodeGenOpts().EmitDeclMetadata = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000248
249 // Disable some warnings.
250 m_clang_ap->getDiagnosticOpts().Warnings.push_back("no-unused-value");
251
252 // Set the target triple.
253 m_clang_ap->getTargetOpts().Triple = m_target_triple;
254
255 // 3. Set up various important bits of infrastructure.
256
257 m_clang_ap->createDiagnostics(0, 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000258
259 // Create the target instance.
260 m_clang_ap->setTarget(TargetInfo::CreateTargetInfo(m_clang_ap->getDiagnostics(),
261 m_clang_ap->getTargetOpts()));
262 if (!m_clang_ap->hasTarget())
263 {
264 m_clang_ap.reset();
265 return false;
266 }
267
268 // Inform the target of the language options
269 //
270 // FIXME: We shouldn't need to do this, the target should be immutable once
271 // created. This complexity should be lifted elsewhere.
272 m_clang_ap->getTarget().setForcedLangOptions(m_clang_ap->getLangOpts());
273
274 return m_clang_ap.get();
275}
276
277Mutex &
278ClangExpression::GetClangMutex ()
279{
280 static Mutex g_clang_mutex(Mutex::eMutexTypeRecursive); // Control access to the clang compiler
281 return g_clang_mutex;
282}
283
284
285clang::ASTContext *
286ClangExpression::GetASTContext ()
287{
288 CompilerInstance *compiler_instance = GetCompilerInstance();
289 if (compiler_instance)
290 return &compiler_instance->getASTContext();
291 return NULL;
292}
293
294unsigned
Sean Callanan8c6934d2010-07-01 20:08:22 +0000295ClangExpression::ParseExpression (const char *expr_text,
296 Stream &stream,
297 bool add_result_var)
Chris Lattner24943d22010-06-08 16:52:24 +0000298{
299 // HACK: for now we have to make a function body around our expression
300 // since there is no way to parse a single expression line in LLVM/Clang.
Sean Callanan8bce6652010-07-13 21:41:46 +0000301 std::string func_expr("extern \"C\" void ___clang_expr(void *___clang_arg)\n{\n\t");
Chris Lattner24943d22010-06-08 16:52:24 +0000302 func_expr.append(expr_text);
303 func_expr.append(";\n}");
Sean Callanan8c6934d2010-07-01 20:08:22 +0000304 return ParseBareExpression (func_expr, stream, add_result_var);
Chris Lattner24943d22010-06-08 16:52:24 +0000305
306}
307
308unsigned
Sean Callanan8c6934d2010-07-01 20:08:22 +0000309ClangExpression::ParseBareExpression (llvm::StringRef expr_text,
310 Stream &stream,
311 bool add_result_var)
Chris Lattner24943d22010-06-08 16:52:24 +0000312{
313 Mutex::Locker locker(GetClangMutex ());
314
315 TextDiagnosticBuffer text_diagnostic_buffer;
316
317 bool IsAST = false;
318 if (!CreateCompilerInstance (IsAST))
319 {
320 stream.Printf("error: couldn't create compiler instance\n");
321 return 1;
322 }
323
324 // This code is matched below by a setClient to NULL.
325 // We cannot return out of this code without doing that.
326 m_clang_ap->getDiagnostics().setClient(&text_diagnostic_buffer);
327 text_diagnostic_buffer.FlushDiagnostics (m_clang_ap->getDiagnostics());
328
329 MemoryBuffer *memory_buffer = MemoryBuffer::getMemBufferCopy(expr_text, __FUNCTION__);
330
331 if (!m_clang_ap->hasSourceManager())
332 m_clang_ap->createSourceManager();
333
334 m_clang_ap->createFileManager();
335 m_clang_ap->createPreprocessor();
336
337 // Build the ASTContext. Most of this we inherit from the
338 // CompilerInstance, but we also want to give the context
339 // an ExternalASTSource.
340 SelectorTable selector_table;
341 std::auto_ptr<Builtin::Context> builtin_ap(new Builtin::Context(m_clang_ap->getTarget()));
342 ASTContext *Context = new ASTContext(m_clang_ap->getLangOpts(),
343 m_clang_ap->getSourceManager(),
344 m_clang_ap->getTarget(),
345 m_clang_ap->getPreprocessor().getIdentifierTable(),
346 selector_table,
Greg Clayton6e713402010-07-30 20:30:44 +0000347 *builtin_ap.get(),
348 0);
Chris Lattner24943d22010-06-08 16:52:24 +0000349
350 llvm::OwningPtr<ExternalASTSource> ASTSource(new ClangASTSource(*Context, *m_decl_map));
351
352 if (m_decl_map)
353 {
354 Context->setExternalSource(ASTSource);
355 }
356
357 m_clang_ap->setASTContext(Context);
358
359 FileID memory_buffer_file_id = m_clang_ap->getSourceManager().createMainFileIDForMemBuffer (memory_buffer);
360 std::string module_name("test_func");
361 text_diagnostic_buffer.BeginSourceFile(m_clang_ap->getLangOpts(), &m_clang_ap->getPreprocessor());
362
363 if (m_code_generator_ptr)
364 delete m_code_generator_ptr;
365
366 m_code_generator_ptr = CreateLLVMCodeGen(m_clang_ap->getDiagnostics(),
367 module_name,
368 m_clang_ap->getCodeGenOpts(),
369 m_clang_ap->getLLVMContext());
370
371
372 // - CodeGeneration ASTConsumer (include/clang/ModuleBuilder.h), which will be passed in when you call...
373 // - Call clang::ParseAST (in lib/Sema/ParseAST.cpp) to parse the buffer. The CodeGenerator will generate code for __dbg_expr.
374 // - Once ParseAST completes, you can grab the llvm::Module from the CodeGenerator, which will have an llvm::Function you can hand off to the JIT.
Sean Callanan8c6934d2010-07-01 20:08:22 +0000375
376 if (add_result_var)
377 {
378 ClangResultSynthesizer result_synthesizer(m_code_generator_ptr);
379 ParseAST(m_clang_ap->getPreprocessor(), &result_synthesizer, m_clang_ap->getASTContext());
380 }
381 else
382 {
383 ParseAST(m_clang_ap->getPreprocessor(), m_code_generator_ptr, m_clang_ap->getASTContext());
384 }
385
Sean Callanan848960c2010-06-23 23:18:04 +0000386
Chris Lattner24943d22010-06-08 16:52:24 +0000387 text_diagnostic_buffer.EndSourceFile();
388
389 //compiler_instance->getASTContext().getTranslationUnitDecl()->dump();
390
391 //if (compiler_instance->getFrontendOpts().ShowStats) {
392 // compiler_instance->getFileManager().PrintStats();
393 // fprintf(stderr, "\n");
394 //}
395
396 // This code resolves the setClient above.
397 m_clang_ap->getDiagnostics().setClient(0);
398
399 TextDiagnosticBuffer::const_iterator diag_iterator;
400
401 int num_errors = 0;
402
403#ifdef COUNT_WARNINGS_AND_ERRORS
404 int num_warnings = 0;
405
406 for (diag_iterator = text_diagnostic_buffer.warn_begin();
407 diag_iterator != text_diagnostic_buffer.warn_end();
408 ++diag_iterator)
409 num_warnings++;
410
411 for (diag_iterator = text_diagnostic_buffer.err_begin();
412 diag_iterator != text_diagnostic_buffer.err_end();
413 ++diag_iterator)
414 num_errors++;
415
416 if (num_warnings || num_errors)
417 {
418 if (num_warnings)
419 stream.Printf("%u warning%s%s", num_warnings, (num_warnings == 1 ? "" : "s"), (num_errors ? " and " : ""));
420 if (num_errors)
421 stream.Printf("%u error%s", num_errors, (num_errors == 1 ? "" : "s"));
422 stream.Printf("\n");
423 }
424#endif
425
426 for (diag_iterator = text_diagnostic_buffer.warn_begin();
427 diag_iterator != text_diagnostic_buffer.warn_end();
428 ++diag_iterator)
429 stream.Printf("warning: %s\n", (*diag_iterator).second.c_str());
430
431 num_errors = 0;
432
433 for (diag_iterator = text_diagnostic_buffer.err_begin();
434 diag_iterator != text_diagnostic_buffer.err_end();
435 ++diag_iterator)
436 {
437 num_errors++;
438 stream.Printf("error: %s\n", (*diag_iterator).second.c_str());
439 }
440
441 return num_errors;
442}
443
Chris Lattner24943d22010-06-08 16:52:24 +0000444unsigned
445ClangExpression::ConvertExpressionToDWARF (ClangExpressionVariableList& expr_local_variable_list,
446 StreamString &dwarf_opcode_strm)
447{
448 CompilerInstance *compiler_instance = GetCompilerInstance();
449
450 DeclarationName hack_func_name(&compiler_instance->getASTContext().Idents.get("___clang_expr"));
451 DeclContext::lookup_result result = compiler_instance->getASTContext().getTranslationUnitDecl()->lookup(hack_func_name);
452
453 if (result.first != result.second)
454 {
455 Decl *decl = *result.first;
456 Stmt *decl_stmt = decl->getBody();
457 if (decl_stmt)
458 {
459 ClangStmtVisitor visitor(compiler_instance->getASTContext(), expr_local_variable_list, m_decl_map, dwarf_opcode_strm);
460
461 visitor.Visit (decl_stmt);
462 }
463 }
464 return 0;
465}
466
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000467bool
Sean Callanandcb658b2010-07-02 21:09:36 +0000468ClangExpression::ConvertIRToDWARF (ClangExpressionVariableList &expr_local_variable_list,
Sean Callanan848960c2010-06-23 23:18:04 +0000469 StreamString &dwarf_opcode_strm)
470{
471 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
472
473 llvm::Module *module = m_code_generator_ptr->GetModule();
474
475 if (!module)
476 {
477 if (log)
478 log->Printf("IR doesn't contain a module");
479
480 return 1;
481 }
482
Sean Callanandcb658b2010-07-02 21:09:36 +0000483 IRToDWARF ir_to_dwarf("IR to DWARF", expr_local_variable_list, m_decl_map, dwarf_opcode_strm);
Sean Callanan8c6934d2010-07-01 20:08:22 +0000484
Sean Callanandcb658b2010-07-02 21:09:36 +0000485 return ir_to_dwarf.runOnModule(*module);
Sean Callanan848960c2010-06-23 23:18:04 +0000486}
487
Chris Lattner24943d22010-06-08 16:52:24 +0000488bool
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000489ClangExpression::PrepareIRForTarget (ClangExpressionVariableList &expr_local_variable_list)
490{
491 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
492
493 llvm::Module *module = m_code_generator_ptr->GetModule();
494
495 if (!module)
496 {
497 if (log)
498 log->Printf("IR doesn't contain a module");
499
500 return 1;
501 }
502
Sean Callanan8bce6652010-07-13 21:41:46 +0000503 llvm::Triple target_triple = m_clang_ap->getTarget().getTriple();
504
505 std::string err;
506
507 const llvm::Target *target = llvm::TargetRegistry::lookupTarget(m_target_triple, err);
508
509 if (!target)
510 {
511 if (log)
512 log->Printf("Couldn't find a target for %s", m_target_triple.c_str());
513
514 return 1;
515 }
516
517 std::auto_ptr<llvm::TargetMachine> target_machine(target->createTargetMachine(m_target_triple, ""));
518
519 IRForTarget ir_for_target("IR for target", m_decl_map, target_machine->getTargetData());
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000520
521 return ir_for_target.runOnModule(*module);
522}
523
524bool
Chris Lattner24943d22010-06-08 16:52:24 +0000525ClangExpression::JITFunction (const ExecutionContext &exc_context, const char *name)
526{
Sean Callanan321fe9e2010-07-28 01:00:59 +0000527 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
Chris Lattner24943d22010-06-08 16:52:24 +0000528
529 llvm::Module *module = m_code_generator_ptr->GetModule();
530
531 if (module)
532 {
533 std::string error;
534
535 if (m_jit_mm_ptr == NULL)
536 m_jit_mm_ptr = new RecordingMemoryManager();
537
538 //llvm::InitializeNativeTarget();
Sean Callanan321fe9e2010-07-28 01:00:59 +0000539
540 if (log)
541 {
542 const char *relocation_model_string;
543
544 switch (llvm::TargetMachine::getRelocationModel())
545 {
Sean Callanan1e7089a2010-07-29 19:03:08 +0000546 case llvm::Reloc::Default:
547 relocation_model_string = "Default";
548 break;
549 case llvm::Reloc::Static:
550 relocation_model_string = "Static";
551 break;
552 case llvm::Reloc::PIC_:
553 relocation_model_string = "PIC_";
554 break;
555 case llvm::Reloc::DynamicNoPIC:
556 relocation_model_string = "DynamicNoPIC";
557 break;
Sean Callanan321fe9e2010-07-28 01:00:59 +0000558 }
559
560 log->Printf("Target machine's relocation model: %s", relocation_model_string);
561 }
Sean Callanan1e7089a2010-07-29 19:03:08 +0000562
563 if (m_execution_engine.get() == 0)
564 m_execution_engine.reset(llvm::ExecutionEngine::createJIT (module,
565 &error,
566 m_jit_mm_ptr,
567 CodeGenOpt::Default,
568 true,
569 CodeModel::Small)); // set to small so RIP-relative relocations work in PIC
570
571 m_execution_engine->DisableLazyCompilation();
572 llvm::Function *function = module->getFunction (llvm::StringRef (name));
Sean Callanan321fe9e2010-07-28 01:00:59 +0000573
Chris Lattner24943d22010-06-08 16:52:24 +0000574 // We don't actually need the function pointer here, this just forces it to get resolved.
575 void *fun_ptr = m_execution_engine->getPointerToFunction(function);
576 // Note, you probably won't get here on error, since the LLVM JIT tends to just
577 // exit on error at present... So be careful.
578 if (fun_ptr == 0)
579 return false;
580 m_jitted_functions.push_back(ClangExpression::JittedFunction(name, (lldb::addr_t) fun_ptr));
581
582 }
583 return true;
584}
585
586bool
587ClangExpression::WriteJITCode (const ExecutionContext &exc_context)
588{
Sean Callanan321fe9e2010-07-28 01:00:59 +0000589 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
590
Chris Lattner24943d22010-06-08 16:52:24 +0000591 if (m_jit_mm_ptr == NULL)
592 return false;
593
594 if (exc_context.process == NULL)
595 return false;
596
597 // Look over the regions allocated for the function compiled. The JIT
598 // tries to allocate the functions & stubs close together, so we should try to
599 // write them that way too...
600 // For now I only write functions with no stubs, globals, exception tables,
601 // etc. So I only need to write the functions.
602
Greg Claytonbef15832010-07-14 00:18:15 +0000603 size_t alloc_size = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000604 std::map<uint8_t *, uint8_t *>::iterator fun_pos, fun_end = m_jit_mm_ptr->m_functions.end();
605 for (fun_pos = m_jit_mm_ptr->m_functions.begin(); fun_pos != fun_end; fun_pos++)
606 {
Greg Claytonbef15832010-07-14 00:18:15 +0000607 alloc_size += (*fun_pos).second - (*fun_pos).first;
Chris Lattner24943d22010-06-08 16:52:24 +0000608 }
609
610 Error error;
Greg Claytonbef15832010-07-14 00:18:15 +0000611 lldb::addr_t target_addr = exc_context.process->AllocateMemory (alloc_size, lldb::ePermissionsReadable|lldb::ePermissionsExecutable, error);
Chris Lattner24943d22010-06-08 16:52:24 +0000612
613 if (target_addr == LLDB_INVALID_ADDRESS)
614 return false;
615
616 lldb::addr_t cursor = target_addr;
617 for (fun_pos = m_jit_mm_ptr->m_functions.begin(); fun_pos != fun_end; fun_pos++)
618 {
Sean Callanan321fe9e2010-07-28 01:00:59 +0000619 if (log)
620 log->Printf("Reading [%p-%p] from m_functions", fun_pos->first, fun_pos->second);
621
Chris Lattner24943d22010-06-08 16:52:24 +0000622 lldb::addr_t lstart = (lldb::addr_t) (*fun_pos).first;
623 lldb::addr_t lend = (lldb::addr_t) (*fun_pos).second;
624 size_t size = lend - lstart;
625 exc_context.process->WriteMemory(cursor, (void *) lstart, size, error);
626 m_jit_mm_ptr->AddToLocalToRemoteMap (lstart, size, cursor);
627 cursor += size;
628 }
629
630 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
631
632 for (pos = m_jitted_functions.begin(); pos != end; pos++)
633 {
634 (*pos).m_remote_addr = m_jit_mm_ptr->GetRemoteAddressForLocal ((*pos).m_local_addr);
635 }
636 return true;
637}
638
639lldb::addr_t
640ClangExpression::GetFunctionAddress (const char *name)
641{
642 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
643
644 for (pos = m_jitted_functions.begin(); pos < end; pos++)
645 {
646 if (strcmp ((*pos).m_name.c_str(), name) == 0)
647 return (*pos).m_remote_addr;
648 }
649 return LLDB_INVALID_ADDRESS;
650}
651
Sean Callanan8541f2f2010-07-23 02:19:15 +0000652Error
653ClangExpression::DisassembleFunction (Stream &stream, ExecutionContext &exe_ctx, const char *name)
654{
655 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
656
657 Error ret;
658
659 ret.Clear();
660
661 lldb::addr_t func_local_addr = LLDB_INVALID_ADDRESS;
662 lldb::addr_t func_remote_addr = LLDB_INVALID_ADDRESS;
663
664 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
665
666 for (pos = m_jitted_functions.begin(); pos < end; pos++)
667 {
668 if (strcmp(pos->m_name.c_str(), name) == 0)
669 {
670 func_local_addr = pos->m_local_addr;
671 func_remote_addr = pos->m_remote_addr;
672 }
673 }
674
675 if (func_local_addr == LLDB_INVALID_ADDRESS)
676 {
677 ret.SetErrorToGenericError();
678 ret.SetErrorStringWithFormat("Couldn't find function %s for disassembly", name);
679 return ret;
680 }
681
682 if(log)
683 log->Printf("Found function, has local address 0x%llx and remote address 0x%llx", (uint64_t)func_local_addr, (uint64_t)func_remote_addr);
684
685 std::pair <lldb::addr_t, lldb::addr_t> func_range;
686
687 func_range = m_jit_mm_ptr->GetRemoteRangeForLocal(func_local_addr);
688
689 if (func_range.first == 0 && func_range.second == 0)
690 {
691 ret.SetErrorToGenericError();
692 ret.SetErrorStringWithFormat("Couldn't find code range for function %s", name);
693 return ret;
694 }
695
696 if(log)
697 log->Printf("Function's code range is [0x%llx-0x%llx]", func_range.first, func_range.second);
698
699 if (!exe_ctx.target)
700 {
701 ret.SetErrorToGenericError();
702 ret.SetErrorString("Couldn't find the target");
703 }
704
Sean Callanan32824aa2010-07-23 22:19:18 +0000705 lldb::DataBufferSP buffer_sp(new DataBufferHeap(func_range.second - func_remote_addr, 0));
Sean Callanan8541f2f2010-07-23 02:19:15 +0000706
707 Error err;
Sean Callanan32824aa2010-07-23 22:19:18 +0000708 exe_ctx.process->ReadMemory(func_remote_addr, buffer_sp->GetBytes(), buffer_sp->GetByteSize(), err);
Sean Callanan8541f2f2010-07-23 02:19:15 +0000709
710 if (!err.Success())
711 {
712 ret.SetErrorToGenericError();
713 ret.SetErrorStringWithFormat("Couldn't read from process: %s", err.AsCString("unknown error"));
714 return ret;
715 }
716
717 ArchSpec arch(exe_ctx.target->GetArchitecture());
718
719 Disassembler *disassembler = Disassembler::FindPlugin(arch);
720
721 if (disassembler == NULL)
722 {
723 ret.SetErrorToGenericError();
724 ret.SetErrorStringWithFormat("Unable to find disassembler plug-in for %s architecture.", arch.AsCString());
725 return ret;
726 }
727
728 if (!exe_ctx.process)
729 {
730 ret.SetErrorToGenericError();
731 ret.SetErrorString("Couldn't find the process");
732 return ret;
733 }
734
735 DataExtractor extractor(buffer_sp,
736 exe_ctx.process->GetByteOrder(),
Sean Callanan32824aa2010-07-23 22:19:18 +0000737 exe_ctx.target->GetArchitecture().GetAddressByteSize());
Sean Callanan8541f2f2010-07-23 02:19:15 +0000738
739 if(log)
740 {
741 log->Printf("Function data has contents:");
742 extractor.PutToLog (log,
743 0,
744 extractor.GetByteSize(),
Sean Callanan32824aa2010-07-23 22:19:18 +0000745 func_remote_addr,
Sean Callanan8541f2f2010-07-23 02:19:15 +0000746 16,
747 DataExtractor::TypeUInt8);
748 }
749
750 disassembler->DecodeInstructions(extractor, 0, UINT32_MAX);
751
752 Disassembler::InstructionList &instruction_list = disassembler->GetInstructionList();
753
754 uint32_t bytes_offset = 0;
755
756 for (uint32_t instruction_index = 0, num_instructions = instruction_list.GetSize();
757 instruction_index < num_instructions;
758 ++instruction_index)
759 {
760 Disassembler::Instruction *instruction = instruction_list.GetInstructionAtIndex(instruction_index);
Sean Callanan32824aa2010-07-23 22:19:18 +0000761 Address addr(NULL, func_remote_addr + bytes_offset);
Sean Callanan8541f2f2010-07-23 02:19:15 +0000762 instruction->Dump (&stream,
Sean Callanan32824aa2010-07-23 22:19:18 +0000763 &addr,
Sean Callanan8541f2f2010-07-23 02:19:15 +0000764 &extractor,
765 bytes_offset,
766 exe_ctx,
767 true);
768 stream.PutChar('\n');
769 bytes_offset += instruction->GetByteSize();
770 }
771
772 return ret;
773}
774
Chris Lattner24943d22010-06-08 16:52:24 +0000775unsigned
776ClangExpression::Compile()
777{
778 Mutex::Locker locker(GetClangMutex ());
779 bool IsAST = false;
780
781 if (CreateCompilerInstance(IsAST))
782 {
783 // Validate/process some options
784 if (m_clang_ap->getHeaderSearchOpts().Verbose)
785 llvm::errs() << "clang-cc version " CLANG_VERSION_STRING
786 << " based upon " << PACKAGE_STRING
787 << " hosted on " << llvm::sys::getHostTriple() << "\n";
788
789 // Enforce certain implications.
790 if (!m_clang_ap->getFrontendOpts().ViewClassInheritance.empty())
791 m_clang_ap->getFrontendOpts().ProgramAction = frontend::InheritanceView;
792// if (!compiler_instance->getFrontendOpts().FixItSuffix.empty())
793// compiler_instance->getFrontendOpts().ProgramAction = frontend::FixIt;
794
795 for (unsigned i = 0, e = m_clang_ap->getFrontendOpts().Inputs.size(); i != e; ++i) {
Chris Lattner24943d22010-06-08 16:52:24 +0000796
797 // If we aren't using an AST file, setup the file and source managers and
798 // the preprocessor.
799 if (!IsAST) {
800 if (!i) {
801 // Create a file manager object to provide access to and cache the
802 // filesystem.
803 m_clang_ap->createFileManager();
804
805 // Create the source manager.
806 m_clang_ap->createSourceManager();
807 } else {
808 // Reset the ID tables if we are reusing the SourceManager.
809 m_clang_ap->getSourceManager().clearIDTables();
810 }
811
812 // Create the preprocessor.
813 m_clang_ap->createPreprocessor();
814 }
815
816 llvm::OwningPtr<FrontendAction> Act(CreateFrontendAction(*m_clang_ap.get()));
817 if (!Act)
818 break;
819
Greg Claytone41c4b22010-06-13 17:34:29 +0000820 if (Act->BeginSourceFile(*m_clang_ap,
821 m_clang_ap->getFrontendOpts().Inputs[i].second,
822 m_clang_ap->getFrontendOpts().Inputs[i].first)) {
Chris Lattner24943d22010-06-08 16:52:24 +0000823 Act->Execute();
824 Act->EndSourceFile();
825 }
826 }
827
828 if (m_clang_ap->getDiagnosticOpts().ShowCarets)
829 {
830 unsigned NumWarnings = m_clang_ap->getDiagnostics().getNumWarnings();
831 unsigned NumErrors = m_clang_ap->getDiagnostics().getNumErrors() -
832 m_clang_ap->getDiagnostics().getNumErrorsSuppressed();
833
834 if (NumWarnings || NumErrors)
835 {
836 if (NumWarnings)
837 fprintf (stderr, "%u warning%s%s", NumWarnings, (NumWarnings == 1 ? "" : "s"), (NumErrors ? " and " : ""));
838 if (NumErrors)
839 fprintf (stderr, "%u error%s", NumErrors, (NumErrors == 1 ? "" : "s"));
840 fprintf (stderr, " generated.\n");
841 }
842 }
843
844 if (m_clang_ap->getFrontendOpts().ShowStats) {
845 m_clang_ap->getFileManager().PrintStats();
846 fprintf(stderr, "\n");
847 }
848
849 // Return the appropriate status when verifying diagnostics.
850 //
851 // FIXME: If we could make getNumErrors() do the right thing, we wouldn't need
852 // this.
853 if (m_clang_ap->getDiagnosticOpts().VerifyDiagnostics)
854 return static_cast<VerifyDiagnosticsClient&>(m_clang_ap->getDiagnosticClient()).HadErrors();
855
856 return m_clang_ap->getDiagnostics().getNumErrors();
857 }
858 return 1;
859}