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