1 //===-- ASTResultSynthesizer.cpp --------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 #include "clang/AST/ASTContext.h"
12 #include "clang/AST/Decl.h"
13 #include "clang/AST/DeclCXX.h"
14 #include "clang/AST/DeclGroup.h"
15 #include "clang/AST/DeclObjC.h"
16 #include "clang/AST/Expr.h"
17 #include "clang/AST/Stmt.h"
18 #include "clang/Parse/Parser.h"
19 #include "clang/Sema/SemaDiagnostic.h"
20 #include "llvm/Support/Casting.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include "lldb/Core/Log.h"
23 #include "lldb/Expression/ClangPersistentVariables.h"
24 #include "lldb/Expression/ASTResultSynthesizer.h"
25 #include "lldb/Symbol/ClangASTContext.h"
26 #include "lldb/Symbol/ClangASTImporter.h"
27 #include "lldb/Target/Target.h"
30 using namespace clang;
31 using namespace lldb_private;
33 ASTResultSynthesizer::ASTResultSynthesizer(ASTConsumer *passthrough,
36 m_passthrough (passthrough),
37 m_passthrough_sema (NULL),
44 m_passthrough_sema = dyn_cast<SemaConsumer>(passthrough);
47 ASTResultSynthesizer::~ASTResultSynthesizer()
52 ASTResultSynthesizer::Initialize(ASTContext &Context)
54 m_ast_context = &Context;
57 m_passthrough->Initialize(Context);
61 ASTResultSynthesizer::TransformTopLevelDecl(Decl* D)
63 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
65 if (NamedDecl *named_decl = dyn_cast<NamedDecl>(D))
67 if (log && log->GetVerbose())
69 if (named_decl->getIdentifier())
70 log->Printf("TransformTopLevelDecl(%s)", named_decl->getIdentifier()->getNameStart());
71 else if (ObjCMethodDecl *method_decl = dyn_cast<ObjCMethodDecl>(D))
72 log->Printf("TransformTopLevelDecl(%s)", method_decl->getSelector().getAsString().c_str());
74 log->Printf("TransformTopLevelDecl(<complex>)");
79 if (LinkageSpecDecl *linkage_spec_decl = dyn_cast<LinkageSpecDecl>(D))
81 RecordDecl::decl_iterator decl_iterator;
83 for (decl_iterator = linkage_spec_decl->decls_begin();
84 decl_iterator != linkage_spec_decl->decls_end();
87 TransformTopLevelDecl(*decl_iterator);
90 else if (ObjCMethodDecl *method_decl = dyn_cast<ObjCMethodDecl>(D))
93 !method_decl->getSelector().getAsString().compare("$__lldb_expr:"))
95 RecordPersistentTypes(method_decl);
96 SynthesizeObjCMethodResult(method_decl);
99 else if (FunctionDecl *function_decl = dyn_cast<FunctionDecl>(D))
102 !function_decl->getNameInfo().getAsString().compare("$__lldb_expr"))
104 RecordPersistentTypes(function_decl);
105 SynthesizeFunctionResult(function_decl);
111 ASTResultSynthesizer::HandleTopLevelDecl(DeclGroupRef D)
113 DeclGroupRef::iterator decl_iterator;
115 for (decl_iterator = D.begin();
116 decl_iterator != D.end();
119 Decl *decl = *decl_iterator;
121 TransformTopLevelDecl(decl);
125 return m_passthrough->HandleTopLevelDecl(D);
130 ASTResultSynthesizer::SynthesizeFunctionResult (FunctionDecl *FunDecl)
132 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
137 FunctionDecl *function_decl = FunDecl;
142 if (log && log->GetVerbose())
145 raw_string_ostream os(s);
147 function_decl->print(os);
151 log->Printf ("Untransformed function AST:\n%s", s.c_str());
154 Stmt *function_body = function_decl->getBody();
155 CompoundStmt *compound_stmt = dyn_cast<CompoundStmt>(function_body);
157 bool ret = SynthesizeBodyResult (compound_stmt,
160 if (log && log->GetVerbose())
163 raw_string_ostream os(s);
165 function_decl->print(os);
169 log->Printf ("Transformed function AST:\n%s", s.c_str());
176 ASTResultSynthesizer::SynthesizeObjCMethodResult (ObjCMethodDecl *MethodDecl)
178 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
186 if (log && log->GetVerbose())
189 raw_string_ostream os(s);
191 MethodDecl->print(os);
195 log->Printf ("Untransformed method AST:\n%s", s.c_str());
198 Stmt *method_body = MethodDecl->getBody();
203 CompoundStmt *compound_stmt = dyn_cast<CompoundStmt>(method_body);
205 bool ret = SynthesizeBodyResult (compound_stmt,
208 if (log && log->GetVerbose())
211 raw_string_ostream os(s);
213 MethodDecl->print(os);
217 log->Printf("Transformed method AST:\n%s", s.c_str());
224 ASTResultSynthesizer::SynthesizeBodyResult (CompoundStmt *Body,
227 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
229 ASTContext &Ctx(*m_ast_context);
234 if (Body->body_empty())
237 Stmt **last_stmt_ptr = Body->body_end() - 1;
238 Stmt *last_stmt = *last_stmt_ptr;
240 while (dyn_cast<NullStmt>(last_stmt))
242 if (last_stmt_ptr != Body->body_begin())
245 last_stmt = *last_stmt_ptr;
253 Expr *last_expr = dyn_cast<Expr>(last_stmt);
256 // No auxiliary variable necessary; expression returns void
259 // In C++11, last_expr can be a LValueToRvalue implicit cast. Strip that off if that's the
263 ImplicitCastExpr *implicit_cast = dyn_cast<ImplicitCastExpr>(last_expr);
268 if (implicit_cast->getCastKind() != CK_LValueToRValue)
271 last_expr = implicit_cast->getSubExpr();
274 // is_lvalue is used to record whether the expression returns an assignable Lvalue or an
275 // Rvalue. This is relevant because they are handled differently.
279 // - In AST result synthesis (here!) the expression E is transformed into an initialization
280 // T *$__lldb_expr_result_ptr = &E.
282 // - In structure allocation, a pointer-sized slot is allocated in the struct that is to be
283 // passed into the expression.
285 // - In IR transformations, reads and writes to $__lldb_expr_result_ptr are redirected at
286 // an entry in the struct ($__lldb_arg) passed into the expression. (Other persistent
287 // variables are treated similarly, having been materialized as references, but in those
288 // cases the value of the reference itself is never modified.)
290 // - During materialization, $0 (the result persistent variable) is ignored.
292 // - During dematerialization, $0 is marked up as a load address with value equal to the
293 // contents of the structure entry.
297 // - In AST result synthesis the expression E is transformed into an initialization
298 // static T $__lldb_expr_result = E.
300 // - In structure allocation, a pointer-sized slot is allocated in the struct that is to be
301 // passed into the expression.
303 // - In IR transformations, an instruction is inserted at the beginning of the function to
304 // dereference the pointer resident in the slot. Reads and writes to $__lldb_expr_result
305 // are redirected at that dereferenced version. Guard variables for the static variable
308 // - During materialization, $0 (the result persistent variable) is populated with the location
309 // of a newly-allocated area of memory.
311 // - During dematerialization, $0 is ignored.
314 (last_expr->getValueKind() == VK_LValue || last_expr->getValueKind() == VK_XValue) &&
315 (last_expr->getObjectKind() == OK_Ordinary);
317 QualType expr_qual_type = last_expr->getType();
318 const clang::Type *expr_type = expr_qual_type.getTypePtr();
323 if (expr_type->isVoidType())
328 std::string s = expr_qual_type.getAsString();
330 log->Printf("Last statement is an %s with type: %s", (is_lvalue ? "lvalue" : "rvalue"), s.c_str());
333 clang::VarDecl *result_decl = NULL;
337 IdentifierInfo *result_ptr_id;
339 if (expr_type->isFunctionType())
340 result_ptr_id = &Ctx.Idents.get("$__lldb_expr_result"); // functions actually should be treated like function pointers
342 result_ptr_id = &Ctx.Idents.get("$__lldb_expr_result_ptr");
344 m_sema->RequireCompleteType(SourceLocation(), expr_qual_type, clang::diag::err_incomplete_type);
346 QualType ptr_qual_type;
348 if (expr_qual_type->getAs<ObjCObjectType>() != NULL)
349 ptr_qual_type = Ctx.getObjCObjectPointerType(expr_qual_type);
351 ptr_qual_type = Ctx.getPointerType(expr_qual_type);
353 result_decl = VarDecl::Create(Ctx,
365 ExprResult address_of_expr = m_sema->CreateBuiltinUnaryOp(SourceLocation(), UO_AddrOf, last_expr);
367 m_sema->AddInitializerToDecl(result_decl, address_of_expr.get(), true, false);
371 IdentifierInfo &result_id = Ctx.Idents.get("$__lldb_expr_result");
373 result_decl = VarDecl::Create(Ctx,
385 m_sema->AddInitializerToDecl(result_decl, last_expr, true, false);
388 DC->addDecl(result_decl);
390 ///////////////////////////////
391 // call AddInitializerToDecl
394 //m_sema->AddInitializerToDecl(result_decl, last_expr);
396 /////////////////////////////////
397 // call ConvertDeclToDeclGroup
400 Sema::DeclGroupPtrTy result_decl_group_ptr;
402 result_decl_group_ptr = m_sema->ConvertDeclToDeclGroup(result_decl);
404 ////////////////////////
405 // call ActOnDeclStmt
408 StmtResult result_initialization_stmt_result(m_sema->ActOnDeclStmt(result_decl_group_ptr,
412 ////////////////////////////////////////////////
413 // replace the old statement with the new one
416 *last_stmt_ptr = reinterpret_cast<Stmt*>(result_initialization_stmt_result.get());
422 ASTResultSynthesizer::HandleTranslationUnit(ASTContext &Ctx)
425 m_passthrough->HandleTranslationUnit(Ctx);
429 ASTResultSynthesizer::RecordPersistentTypes(DeclContext *FunDeclCtx)
431 typedef DeclContext::specific_decl_iterator<TypeDecl> TypeDeclIterator;
433 for (TypeDeclIterator i = TypeDeclIterator(FunDeclCtx->decls_begin()),
434 e = TypeDeclIterator(FunDeclCtx->decls_end());
438 MaybeRecordPersistentType(*i);
443 ASTResultSynthesizer::MaybeRecordPersistentType(TypeDecl *D)
445 if (!D->getIdentifier())
448 StringRef name = D->getName();
450 if (name.size() == 0 || name[0] != '$')
453 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_EXPRESSIONS));
455 ConstString name_cs(name.str().c_str());
458 log->Printf ("Recording persistent type %s\n", name_cs.GetCString());
460 Decl *D_scratch = m_target.GetClangASTImporter()->DeportDecl(m_target.GetScratchClangASTContext()->getASTContext(),
464 if (TypeDecl *TypeDecl_scratch = dyn_cast<TypeDecl>(D_scratch))
465 m_target.GetPersistentVariables().RegisterPersistentType(name_cs, TypeDecl_scratch);
469 ASTResultSynthesizer::HandleTagDeclDefinition(TagDecl *D)
472 m_passthrough->HandleTagDeclDefinition(D);
476 ASTResultSynthesizer::CompleteTentativeDefinition(VarDecl *D)
479 m_passthrough->CompleteTentativeDefinition(D);
483 ASTResultSynthesizer::HandleVTable(CXXRecordDecl *RD, bool DefinitionRequired)
486 m_passthrough->HandleVTable(RD, DefinitionRequired);
490 ASTResultSynthesizer::PrintStats()
493 m_passthrough->PrintStats();
497 ASTResultSynthesizer::InitializeSema(Sema &S)
501 if (m_passthrough_sema)
502 m_passthrough_sema->InitializeSema(S);
506 ASTResultSynthesizer::ForgetSema()
510 if (m_passthrough_sema)
511 m_passthrough_sema->ForgetSema();