blob: a3a58b69a14baa995028c0dd4832c33414d1faff [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"
53#include "llvm/Target/TargetSelect.h"
54
55// Project includes
Sean Callanan848960c2010-06-23 23:18:04 +000056#include "lldb/Core/Log.h"
Chris Lattner24943d22010-06-08 16:52:24 +000057#include "lldb/Expression/ClangExpression.h"
58#include "lldb/Expression/ClangASTSource.h"
Sean Callanan8c6934d2010-07-01 20:08:22 +000059#include "lldb/Expression/ClangResultSynthesizer.h"
Chris Lattner24943d22010-06-08 16:52:24 +000060#include "lldb/Expression/ClangStmtVisitor.h"
Sean Callanan5cf4a1c2010-07-03 01:35:46 +000061#include "lldb/Expression/IRForTarget.h"
Sean Callanandcb658b2010-07-02 21:09:36 +000062#include "lldb/Expression/IRToDWARF.h"
Chris Lattner24943d22010-06-08 16:52:24 +000063#include "lldb/Symbol/ClangASTContext.h"
64#include "lldb/Expression/RecordingMemoryManager.h"
65#include "lldb/Target/ExecutionContext.h"
66#include "lldb/Target/Process.h"
67
Chris Lattner24943d22010-06-08 16:52:24 +000068#include "lldb/Core/StreamString.h"
69#include "lldb/Host/Mutex.h"
70#include "lldb/Core/dwarf.h"
71
72
73using namespace lldb_private;
74using namespace clang;
75using namespace llvm;
76
77namespace clang {
78
79class AnalyzerOptions;
80class CodeGenOptions;
81class DependencyOutputOptions;
82class DiagnosticOptions;
83class FrontendOptions;
84class HeaderSearchOptions;
85class LangOptions;
86class PreprocessorOptions;
87class PreprocessorOutputOptions;
88class TargetInfo;
89class TargetOptions;
90
91} // end namespace clang
92
93
94
95//===----------------------------------------------------------------------===//
96// Utility Methods
97//===----------------------------------------------------------------------===//
98
99std::string GetBuiltinIncludePath(const char *Argv0) {
100 llvm::sys::Path P =
101 llvm::sys::Path::GetMainExecutable(Argv0,
102 (void*)(intptr_t) GetBuiltinIncludePath);
103
104 if (!P.isEmpty()) {
105 P.eraseComponent(); // Remove /clang from foo/bin/clang
106 P.eraseComponent(); // Remove /bin from foo/bin
107
108 // Get foo/lib/clang/<version>/include
109 P.appendComponent("lib");
110 P.appendComponent("clang");
111 P.appendComponent(CLANG_VERSION_STRING);
112 P.appendComponent("include");
113 }
114
115 return P.str();
116}
117
118
119//===----------------------------------------------------------------------===//
120// Main driver
121//===----------------------------------------------------------------------===//
122
123void LLVMErrorHandler(void *UserData, const std::string &Message) {
124 Diagnostic &Diags = *static_cast<Diagnostic*>(UserData);
125
126 Diags.Report(diag::err_fe_error_backend) << Message;
127
128 // We cannot recover from llvm errors.
129 exit(1);
130}
131
132static FrontendAction *CreateFrontendBaseAction(CompilerInstance &CI) {
133 using namespace clang::frontend;
134
135 switch (CI.getFrontendOpts().ProgramAction) {
136 default:
137 llvm_unreachable("Invalid program action!");
138
139 case ASTDump: return new ASTDumpAction();
140 case ASTPrint: return new ASTPrintAction();
141 case ASTPrintXML: return new ASTPrintXMLAction();
142 case ASTView: return new ASTViewAction();
143 case DumpRawTokens: return new DumpRawTokensAction();
144 case DumpTokens: return new DumpTokensAction();
145 case EmitAssembly: return new EmitAssemblyAction();
146 case EmitBC: return new EmitBCAction();
147 case EmitHTML: return new HTMLPrintAction();
148 case EmitLLVM: return new EmitLLVMAction();
149 case EmitLLVMOnly: return new EmitLLVMOnlyAction();
150 case EmitObj: return new EmitObjAction();
151 case FixIt: return new FixItAction();
152 case GeneratePCH: return new GeneratePCHAction();
153 case GeneratePTH: return new GeneratePTHAction();
154 case InheritanceView: return new InheritanceViewAction();
155 case InitOnly: return new InitOnlyAction();
156 case ParseNoop: return new ParseOnlyAction();
157 case ParsePrintCallbacks: return new PrintParseAction();
158 case ParseSyntaxOnly: return new SyntaxOnlyAction();
159
160 case PluginAction: {
161 if (CI.getFrontendOpts().ActionName == "help") {
162 llvm::errs() << "clang -cc1 plugins:\n";
163 for (FrontendPluginRegistry::iterator it =
164 FrontendPluginRegistry::begin(),
165 ie = FrontendPluginRegistry::end();
166 it != ie; ++it)
167 llvm::errs() << " " << it->getName() << " - " << it->getDesc() << "\n";
168 return 0;
169 }
170
171 for (FrontendPluginRegistry::iterator it =
172 FrontendPluginRegistry::begin(), ie = FrontendPluginRegistry::end();
173 it != ie; ++it) {
174 if (it->getName() == CI.getFrontendOpts().ActionName)
175 return it->instantiate();
176 }
177
178 CI.getDiagnostics().Report(diag::err_fe_invalid_plugin_name)
179 << CI.getFrontendOpts().ActionName;
180 return 0;
181 }
182
183 case PrintDeclContext: return new DeclContextPrintAction();
184 case PrintPreprocessedInput: return new PrintPreprocessedAction();
185 case RewriteMacros: return new RewriteMacrosAction();
186 case RewriteObjC: return new RewriteObjCAction();
187 case RewriteTest: return new RewriteTestAction();
188 case RunAnalysis: return new AnalysisAction();
189 case RunPreprocessorOnly: return new PreprocessOnlyAction();
190 }
191}
192
193//----------------------------------------------------------------------
194// ClangExpression constructor
195//----------------------------------------------------------------------
196ClangExpression::ClangExpression(const char *target_triple,
197 ClangExpressionDeclMap *decl_map) :
198 m_target_triple (),
199 m_jit_mm_ptr (NULL),
200 m_code_generator_ptr (NULL),
201 m_decl_map (decl_map)
202{
203 if (target_triple && target_triple[0])
204 m_target_triple = target_triple;
205 else
206 m_target_triple = llvm::sys::getHostTriple();
207}
208
209
210//----------------------------------------------------------------------
211// Destructor
212//----------------------------------------------------------------------
213ClangExpression::~ClangExpression()
214{
215 if (m_code_generator_ptr && !m_execution_engine.get())
216 delete m_code_generator_ptr;
217}
218
219bool
220ClangExpression::CreateCompilerInstance (bool &IsAST)
221{
222 // Initialize targets first, so that --version shows registered targets.
223 static struct InitializeLLVM {
224 InitializeLLVM() {
225 llvm::InitializeAllTargets();
226 llvm::InitializeAllAsmPrinters();
227 }
228 } InitializeLLVM;
229
230 // 1. Create a new compiler instance.
231 m_clang_ap.reset(new CompilerInstance());
232 m_clang_ap->setLLVMContext(new LLVMContext());
233
234 // 2. Set options.
235
236 // Parse expressions as Objective C++ regardless of context.
237 // Our hook into Clang's lookup mechanism only works in C++.
238 m_clang_ap->getLangOpts().CPlusPlus = true;
239 m_clang_ap->getLangOpts().ObjC1 = true;
Sean Callanan051052f2010-07-02 22:22:28 +0000240 m_clang_ap->getLangOpts().ThreadsafeStatics = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000241
242 // Disable some warnings.
243 m_clang_ap->getDiagnosticOpts().Warnings.push_back("no-unused-value");
244
245 // Set the target triple.
246 m_clang_ap->getTargetOpts().Triple = m_target_triple;
247
248 // 3. Set up various important bits of infrastructure.
249
250 m_clang_ap->createDiagnostics(0, 0);
251 m_clang_ap->getLangOpts().CPlusPlus = true;
252
253 // Create the target instance.
254 m_clang_ap->setTarget(TargetInfo::CreateTargetInfo(m_clang_ap->getDiagnostics(),
255 m_clang_ap->getTargetOpts()));
256 if (!m_clang_ap->hasTarget())
257 {
258 m_clang_ap.reset();
259 return false;
260 }
261
262 // Inform the target of the language options
263 //
264 // FIXME: We shouldn't need to do this, the target should be immutable once
265 // created. This complexity should be lifted elsewhere.
266 m_clang_ap->getTarget().setForcedLangOptions(m_clang_ap->getLangOpts());
267
268 return m_clang_ap.get();
269}
270
271Mutex &
272ClangExpression::GetClangMutex ()
273{
274 static Mutex g_clang_mutex(Mutex::eMutexTypeRecursive); // Control access to the clang compiler
275 return g_clang_mutex;
276}
277
278
279clang::ASTContext *
280ClangExpression::GetASTContext ()
281{
282 CompilerInstance *compiler_instance = GetCompilerInstance();
283 if (compiler_instance)
284 return &compiler_instance->getASTContext();
285 return NULL;
286}
287
288unsigned
Sean Callanan8c6934d2010-07-01 20:08:22 +0000289ClangExpression::ParseExpression (const char *expr_text,
290 Stream &stream,
291 bool add_result_var)
Chris Lattner24943d22010-06-08 16:52:24 +0000292{
293 // HACK: for now we have to make a function body around our expression
294 // since there is no way to parse a single expression line in LLVM/Clang.
Sean Callanan8c6934d2010-07-01 20:08:22 +0000295 std::string func_expr("extern \"C\" void ___clang_expr()\n{\n\t");
Chris Lattner24943d22010-06-08 16:52:24 +0000296 func_expr.append(expr_text);
297 func_expr.append(";\n}");
Sean Callanan8c6934d2010-07-01 20:08:22 +0000298 return ParseBareExpression (func_expr, stream, add_result_var);
Chris Lattner24943d22010-06-08 16:52:24 +0000299
300}
301
302unsigned
Sean Callanan8c6934d2010-07-01 20:08:22 +0000303ClangExpression::ParseBareExpression (llvm::StringRef expr_text,
304 Stream &stream,
305 bool add_result_var)
Chris Lattner24943d22010-06-08 16:52:24 +0000306{
307 Mutex::Locker locker(GetClangMutex ());
308
309 TextDiagnosticBuffer text_diagnostic_buffer;
310
311 bool IsAST = false;
312 if (!CreateCompilerInstance (IsAST))
313 {
314 stream.Printf("error: couldn't create compiler instance\n");
315 return 1;
316 }
317
318 // This code is matched below by a setClient to NULL.
319 // We cannot return out of this code without doing that.
320 m_clang_ap->getDiagnostics().setClient(&text_diagnostic_buffer);
321 text_diagnostic_buffer.FlushDiagnostics (m_clang_ap->getDiagnostics());
322
323 MemoryBuffer *memory_buffer = MemoryBuffer::getMemBufferCopy(expr_text, __FUNCTION__);
324
325 if (!m_clang_ap->hasSourceManager())
326 m_clang_ap->createSourceManager();
327
328 m_clang_ap->createFileManager();
329 m_clang_ap->createPreprocessor();
330
331 // Build the ASTContext. Most of this we inherit from the
332 // CompilerInstance, but we also want to give the context
333 // an ExternalASTSource.
334 SelectorTable selector_table;
335 std::auto_ptr<Builtin::Context> builtin_ap(new Builtin::Context(m_clang_ap->getTarget()));
336 ASTContext *Context = new ASTContext(m_clang_ap->getLangOpts(),
337 m_clang_ap->getSourceManager(),
338 m_clang_ap->getTarget(),
339 m_clang_ap->getPreprocessor().getIdentifierTable(),
340 selector_table,
341 *builtin_ap.get());
342
343 llvm::OwningPtr<ExternalASTSource> ASTSource(new ClangASTSource(*Context, *m_decl_map));
344
345 if (m_decl_map)
346 {
347 Context->setExternalSource(ASTSource);
348 }
349
350 m_clang_ap->setASTContext(Context);
351
352 FileID memory_buffer_file_id = m_clang_ap->getSourceManager().createMainFileIDForMemBuffer (memory_buffer);
353 std::string module_name("test_func");
354 text_diagnostic_buffer.BeginSourceFile(m_clang_ap->getLangOpts(), &m_clang_ap->getPreprocessor());
355
356 if (m_code_generator_ptr)
357 delete m_code_generator_ptr;
358
359 m_code_generator_ptr = CreateLLVMCodeGen(m_clang_ap->getDiagnostics(),
360 module_name,
361 m_clang_ap->getCodeGenOpts(),
362 m_clang_ap->getLLVMContext());
363
364
365 // - CodeGeneration ASTConsumer (include/clang/ModuleBuilder.h), which will be passed in when you call...
366 // - Call clang::ParseAST (in lib/Sema/ParseAST.cpp) to parse the buffer. The CodeGenerator will generate code for __dbg_expr.
367 // - 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 +0000368
369 if (add_result_var)
370 {
371 ClangResultSynthesizer result_synthesizer(m_code_generator_ptr);
372 ParseAST(m_clang_ap->getPreprocessor(), &result_synthesizer, m_clang_ap->getASTContext());
373 }
374 else
375 {
376 ParseAST(m_clang_ap->getPreprocessor(), m_code_generator_ptr, m_clang_ap->getASTContext());
377 }
378
Sean Callanan848960c2010-06-23 23:18:04 +0000379
Chris Lattner24943d22010-06-08 16:52:24 +0000380 text_diagnostic_buffer.EndSourceFile();
381
382 //compiler_instance->getASTContext().getTranslationUnitDecl()->dump();
383
384 //if (compiler_instance->getFrontendOpts().ShowStats) {
385 // compiler_instance->getFileManager().PrintStats();
386 // fprintf(stderr, "\n");
387 //}
388
389 // This code resolves the setClient above.
390 m_clang_ap->getDiagnostics().setClient(0);
391
392 TextDiagnosticBuffer::const_iterator diag_iterator;
393
394 int num_errors = 0;
395
396#ifdef COUNT_WARNINGS_AND_ERRORS
397 int num_warnings = 0;
398
399 for (diag_iterator = text_diagnostic_buffer.warn_begin();
400 diag_iterator != text_diagnostic_buffer.warn_end();
401 ++diag_iterator)
402 num_warnings++;
403
404 for (diag_iterator = text_diagnostic_buffer.err_begin();
405 diag_iterator != text_diagnostic_buffer.err_end();
406 ++diag_iterator)
407 num_errors++;
408
409 if (num_warnings || num_errors)
410 {
411 if (num_warnings)
412 stream.Printf("%u warning%s%s", num_warnings, (num_warnings == 1 ? "" : "s"), (num_errors ? " and " : ""));
413 if (num_errors)
414 stream.Printf("%u error%s", num_errors, (num_errors == 1 ? "" : "s"));
415 stream.Printf("\n");
416 }
417#endif
418
419 for (diag_iterator = text_diagnostic_buffer.warn_begin();
420 diag_iterator != text_diagnostic_buffer.warn_end();
421 ++diag_iterator)
422 stream.Printf("warning: %s\n", (*diag_iterator).second.c_str());
423
424 num_errors = 0;
425
426 for (diag_iterator = text_diagnostic_buffer.err_begin();
427 diag_iterator != text_diagnostic_buffer.err_end();
428 ++diag_iterator)
429 {
430 num_errors++;
431 stream.Printf("error: %s\n", (*diag_iterator).second.c_str());
432 }
433
434 return num_errors;
435}
436
Chris Lattner24943d22010-06-08 16:52:24 +0000437static FrontendAction *
438CreateFrontendAction(CompilerInstance &CI)
439{
440 // Create the underlying action.
441 FrontendAction *Act = CreateFrontendBaseAction(CI);
442 if (!Act)
443 return 0;
444
445 // If there are any AST files to merge, create a frontend action
446 // adaptor to perform the merge.
447 if (!CI.getFrontendOpts().ASTMergeFiles.empty())
448 Act = new ASTMergeAction(Act, &CI.getFrontendOpts().ASTMergeFiles[0],
449 CI.getFrontendOpts().ASTMergeFiles.size());
450
451 return Act;
452}
453
454
455unsigned
456ClangExpression::ConvertExpressionToDWARF (ClangExpressionVariableList& expr_local_variable_list,
457 StreamString &dwarf_opcode_strm)
458{
459 CompilerInstance *compiler_instance = GetCompilerInstance();
460
461 DeclarationName hack_func_name(&compiler_instance->getASTContext().Idents.get("___clang_expr"));
462 DeclContext::lookup_result result = compiler_instance->getASTContext().getTranslationUnitDecl()->lookup(hack_func_name);
463
464 if (result.first != result.second)
465 {
466 Decl *decl = *result.first;
467 Stmt *decl_stmt = decl->getBody();
468 if (decl_stmt)
469 {
470 ClangStmtVisitor visitor(compiler_instance->getASTContext(), expr_local_variable_list, m_decl_map, dwarf_opcode_strm);
471
472 visitor.Visit (decl_stmt);
473 }
474 }
475 return 0;
476}
477
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000478bool
Sean Callanandcb658b2010-07-02 21:09:36 +0000479ClangExpression::ConvertIRToDWARF (ClangExpressionVariableList &expr_local_variable_list,
Sean Callanan848960c2010-06-23 23:18:04 +0000480 StreamString &dwarf_opcode_strm)
481{
482 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
483
484 llvm::Module *module = m_code_generator_ptr->GetModule();
485
486 if (!module)
487 {
488 if (log)
489 log->Printf("IR doesn't contain a module");
490
491 return 1;
492 }
493
Sean Callanandcb658b2010-07-02 21:09:36 +0000494 IRToDWARF ir_to_dwarf("IR to DWARF", expr_local_variable_list, m_decl_map, dwarf_opcode_strm);
Sean Callanan8c6934d2010-07-01 20:08:22 +0000495
Sean Callanandcb658b2010-07-02 21:09:36 +0000496 return ir_to_dwarf.runOnModule(*module);
Sean Callanan848960c2010-06-23 23:18:04 +0000497}
498
Chris Lattner24943d22010-06-08 16:52:24 +0000499bool
Sean Callanan5cf4a1c2010-07-03 01:35:46 +0000500ClangExpression::PrepareIRForTarget (ClangExpressionVariableList &expr_local_variable_list)
501{
502 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS);
503
504 llvm::Module *module = m_code_generator_ptr->GetModule();
505
506 if (!module)
507 {
508 if (log)
509 log->Printf("IR doesn't contain a module");
510
511 return 1;
512 }
513
514 IRForTarget ir_for_target("IR for target", m_decl_map);
515
516 return ir_for_target.runOnModule(*module);
517}
518
519bool
Chris Lattner24943d22010-06-08 16:52:24 +0000520ClangExpression::JITFunction (const ExecutionContext &exc_context, const char *name)
521{
522
523 llvm::Module *module = m_code_generator_ptr->GetModule();
524
525 if (module)
526 {
527 std::string error;
528
529 if (m_jit_mm_ptr == NULL)
530 m_jit_mm_ptr = new RecordingMemoryManager();
531
532 //llvm::InitializeNativeTarget();
533 if (m_execution_engine.get() == 0)
534 m_execution_engine.reset(llvm::ExecutionEngine::createJIT (module, &error, m_jit_mm_ptr));
535 m_execution_engine->DisableLazyCompilation();
536 llvm::Function *function = module->getFunction (llvm::StringRef (name));
537
538 // We don't actually need the function pointer here, this just forces it to get resolved.
539 void *fun_ptr = m_execution_engine->getPointerToFunction(function);
540 // Note, you probably won't get here on error, since the LLVM JIT tends to just
541 // exit on error at present... So be careful.
542 if (fun_ptr == 0)
543 return false;
544 m_jitted_functions.push_back(ClangExpression::JittedFunction(name, (lldb::addr_t) fun_ptr));
545
546 }
547 return true;
548}
549
550bool
551ClangExpression::WriteJITCode (const ExecutionContext &exc_context)
552{
553 if (m_jit_mm_ptr == NULL)
554 return false;
555
556 if (exc_context.process == NULL)
557 return false;
558
559 // Look over the regions allocated for the function compiled. The JIT
560 // tries to allocate the functions & stubs close together, so we should try to
561 // write them that way too...
562 // For now I only write functions with no stubs, globals, exception tables,
563 // etc. So I only need to write the functions.
564
565 size_t size = 0;
566 std::map<uint8_t *, uint8_t *>::iterator fun_pos, fun_end = m_jit_mm_ptr->m_functions.end();
567 for (fun_pos = m_jit_mm_ptr->m_functions.begin(); fun_pos != fun_end; fun_pos++)
568 {
569 size += (*fun_pos).second - (*fun_pos).first;
570 }
571
572 Error error;
573 lldb::addr_t target_addr = exc_context.process->AllocateMemory (size, lldb::ePermissionsReadable|lldb::ePermissionsExecutable, error);
574
575 if (target_addr == LLDB_INVALID_ADDRESS)
576 return false;
577
578 lldb::addr_t cursor = target_addr;
579 for (fun_pos = m_jit_mm_ptr->m_functions.begin(); fun_pos != fun_end; fun_pos++)
580 {
581 lldb::addr_t lstart = (lldb::addr_t) (*fun_pos).first;
582 lldb::addr_t lend = (lldb::addr_t) (*fun_pos).second;
583 size_t size = lend - lstart;
584 exc_context.process->WriteMemory(cursor, (void *) lstart, size, error);
585 m_jit_mm_ptr->AddToLocalToRemoteMap (lstart, size, cursor);
586 cursor += size;
587 }
588
589 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
590
591 for (pos = m_jitted_functions.begin(); pos != end; pos++)
592 {
593 (*pos).m_remote_addr = m_jit_mm_ptr->GetRemoteAddressForLocal ((*pos).m_local_addr);
594 }
595 return true;
596}
597
598lldb::addr_t
599ClangExpression::GetFunctionAddress (const char *name)
600{
601 std::vector<JittedFunction>::iterator pos, end = m_jitted_functions.end();
602
603 for (pos = m_jitted_functions.begin(); pos < end; pos++)
604 {
605 if (strcmp ((*pos).m_name.c_str(), name) == 0)
606 return (*pos).m_remote_addr;
607 }
608 return LLDB_INVALID_ADDRESS;
609}
610
611unsigned
612ClangExpression::Compile()
613{
614 Mutex::Locker locker(GetClangMutex ());
615 bool IsAST = false;
616
617 if (CreateCompilerInstance(IsAST))
618 {
619 // Validate/process some options
620 if (m_clang_ap->getHeaderSearchOpts().Verbose)
621 llvm::errs() << "clang-cc version " CLANG_VERSION_STRING
622 << " based upon " << PACKAGE_STRING
623 << " hosted on " << llvm::sys::getHostTriple() << "\n";
624
625 // Enforce certain implications.
626 if (!m_clang_ap->getFrontendOpts().ViewClassInheritance.empty())
627 m_clang_ap->getFrontendOpts().ProgramAction = frontend::InheritanceView;
628// if (!compiler_instance->getFrontendOpts().FixItSuffix.empty())
629// compiler_instance->getFrontendOpts().ProgramAction = frontend::FixIt;
630
631 for (unsigned i = 0, e = m_clang_ap->getFrontendOpts().Inputs.size(); i != e; ++i) {
Chris Lattner24943d22010-06-08 16:52:24 +0000632
633 // If we aren't using an AST file, setup the file and source managers and
634 // the preprocessor.
635 if (!IsAST) {
636 if (!i) {
637 // Create a file manager object to provide access to and cache the
638 // filesystem.
639 m_clang_ap->createFileManager();
640
641 // Create the source manager.
642 m_clang_ap->createSourceManager();
643 } else {
644 // Reset the ID tables if we are reusing the SourceManager.
645 m_clang_ap->getSourceManager().clearIDTables();
646 }
647
648 // Create the preprocessor.
649 m_clang_ap->createPreprocessor();
650 }
651
652 llvm::OwningPtr<FrontendAction> Act(CreateFrontendAction(*m_clang_ap.get()));
653 if (!Act)
654 break;
655
Greg Claytone41c4b22010-06-13 17:34:29 +0000656 if (Act->BeginSourceFile(*m_clang_ap,
657 m_clang_ap->getFrontendOpts().Inputs[i].second,
658 m_clang_ap->getFrontendOpts().Inputs[i].first)) {
Chris Lattner24943d22010-06-08 16:52:24 +0000659 Act->Execute();
660 Act->EndSourceFile();
661 }
662 }
663
664 if (m_clang_ap->getDiagnosticOpts().ShowCarets)
665 {
666 unsigned NumWarnings = m_clang_ap->getDiagnostics().getNumWarnings();
667 unsigned NumErrors = m_clang_ap->getDiagnostics().getNumErrors() -
668 m_clang_ap->getDiagnostics().getNumErrorsSuppressed();
669
670 if (NumWarnings || NumErrors)
671 {
672 if (NumWarnings)
673 fprintf (stderr, "%u warning%s%s", NumWarnings, (NumWarnings == 1 ? "" : "s"), (NumErrors ? " and " : ""));
674 if (NumErrors)
675 fprintf (stderr, "%u error%s", NumErrors, (NumErrors == 1 ? "" : "s"));
676 fprintf (stderr, " generated.\n");
677 }
678 }
679
680 if (m_clang_ap->getFrontendOpts().ShowStats) {
681 m_clang_ap->getFileManager().PrintStats();
682 fprintf(stderr, "\n");
683 }
684
685 // Return the appropriate status when verifying diagnostics.
686 //
687 // FIXME: If we could make getNumErrors() do the right thing, we wouldn't need
688 // this.
689 if (m_clang_ap->getDiagnosticOpts().VerifyDiagnostics)
690 return static_cast<VerifyDiagnosticsClient&>(m_clang_ap->getDiagnosticClient()).HadErrors();
691
692 return m_clang_ap->getDiagnostics().getNumErrors();
693 }
694 return 1;
695}