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