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