Skip to content

[cxx-interop] ClangDeclFinder to handle problematic codegen cases #39551

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
132 changes: 132 additions & 0 deletions lib/IRGen/GenClangDecl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "clang-decl-finder"

#include "IRGenModule.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/IRGenOptions.h"
Expand Down Expand Up @@ -82,6 +84,116 @@ clang::Decl *getDeclWithExecutableCode(clang::Decl *decl) {
return nullptr;
}

auto walkCallGraphFromCtor(
const clang::CXXConstructorDecl *toplevelCtor,
llvm::SmallPtrSet<const clang::Decl *, 8> visited,
llvm::SmallPtrSet<const clang::Decl *, 8> &functionDecls) {

llvm::SmallVector<clang::Stmt *, 8> stack;
auto recurseStmt = [&stack](clang::Stmt *s) {
if (s) {
stack.push_back(s);
return true;
}
return false;
};

// Keep track of decls we have already walked over so that we don't re-walk
// over them redundantly. Returns true if the insertion took place.
auto visitDecl = [&visited](const clang::Decl *decl) {
return decl ? visited.insert(decl).second : false;
};

auto handleCtor = [&recurseStmt,
&functionDecls](const clang::CXXConstructorDecl *ctor) {
functionDecls.insert(ctor);
if (ctor->getParent()->getDestructor())
functionDecls.insert(ctor->getParent()->getDestructor());
recurseStmt(ctor->getBody());
for (auto *init : ctor->inits()) {
recurseStmt(init->getInit());
if (clang::FieldDecl *field = init->getMember())
recurseStmt(field->getInClassInitializer());
}
};

auto handleFunctionDecl = [&recurseStmt, &functionDecls](
clang::FunctionDecl *functionDecl) {
LLVM_DEBUG({
llvm::dbgs() << "HANDLE FUNCTION DECL:\n";
llvm::dbgs() << "IS INLINE "
<< (functionDecl->isInlineSpecified() ? "YES" : "NO")
<< "\n";
llvm::dbgs() << "IS TEMPLATE INST "
<< (functionDecl->isTemplateInstantiation() ? "YES" : "NO")
<< "\n";
});

if (functionDecl->isInlineSpecified() || // is 'inline' specified
functionDecl->isInlined() || // is inlined or constexpr
functionDecl->isTemplateInstantiation()) // is template instance
functionDecls.insert(functionDecl);

// Even if this function is not inlined or a template instance we want to
// recurse on it in case it calls something or calls something that calls
// something that is.
recurseStmt(functionDecl->getBody());
};

handleCtor(toplevelCtor);

while (!stack.empty()) {
auto *back = stack.pop_back_val();

LLVM_DEBUG({
llvm::dbgs() << "\nClang Decl Walker Candidate:\n";
back->dump(llvm::dbgs(), toplevelCtor->getASTContext());
});

// Handle if the expression is a callsite or a ExprWithCleanups.
if (auto *fn = dyn_cast<clang::MemberExpr>(back)) {
if (visitDecl(fn->getMemberDecl()))
recurseStmt(fn->getMemberDecl()->getBody());
} else if (auto *fn = dyn_cast<clang::CallExpr>(back)) {
auto *memberCall = dyn_cast<clang::CXXMemberCallExpr>(back);
if (memberCall && visitDecl(memberCall->getMethodDecl())) {
functionDecls.insert(memberCall->getMethodDecl());
recurseStmt(memberCall->getMethodDecl()->getBody());
}

if (visitDecl(fn->getCalleeDecl())) {
functionDecls.insert(fn->getCalleeDecl());
recurseStmt(fn->getCalleeDecl()->getBody());
}
} else if (auto *fn = dyn_cast<clang::CXXConstructExpr>(back)) {

// Use the constructor expression to traverse corresponding destructors.
// This is done because default destructor decls are empty and have very
// little to traverse.
if (auto *dtor = fn->getConstructor() && fn->getConstructor()->getParent()
? fn->getConstructor()->getParent()->getDestructor()
: nullptr) {
handleFunctionDecl(dtor);
if (dtor->getBody())
recurseStmt(dtor->getBody());
}

for (auto *child : fn->children())
recurseStmt(child);

if (visitDecl(fn->getConstructor()))
handleCtor(fn->getConstructor());
} else if (auto *declRef = dyn_cast<clang::DeclRefExpr>(back)) {
if (auto *fn = dyn_cast_or_null<clang::FunctionDecl>(declRef->getDecl()))
handleFunctionDecl(fn);
}

// Walk the expression's children.
for (clang::Stmt *child : back->children())
recurseStmt(child);
}
}

} // end anonymous namespace

void IRGenModule::emitClangDecl(const clang::Decl *decl) {
Expand Down Expand Up @@ -120,6 +232,26 @@ void IRGenModule::emitClangDecl(const clang::Decl *decl) {
stack.push_back(D);
});

std::vector<const clang::Decl *> ctors;
llvm::copy_if(stack, std::back_inserter(ctors), [](const clang::Decl *decl) {
return isa<clang::CXXConstructorDecl>(decl);
});

llvm::SmallPtrSet<const clang::Decl *, 8> visited;
llvm::SmallPtrSet<const clang::Decl *, 8> functionDecls;
for (auto *ctor : ctors)
walkCallGraphFromCtor(cast<clang::CXXConstructorDecl>(ctor), visited,
functionDecls);
llvm::copy(functionDecls, std::back_inserter(stack));

LLVM_DEBUG({
llvm::dbgs()
<< "\nAdditional Function/Method decls found on constructor path:\n";
for (auto *functionDecl : functionDecls)
functionDecl->dump(llvm::dbgs());
llvm::dbgs() << "\n";
});

while (!stack.empty()) {
auto *next = const_cast<clang::Decl *>(stack.pop_back_val());
if (clang::Decl *executableDecl = getDeclWithExecutableCode(next)) {
Expand Down
14 changes: 14 additions & 0 deletions test/Interop/Cxx/class/Inputs/initializer-from-inline.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
inline int get42() { return 42; }
struct Hold42 { int m = get42(); };

template <typename T> T passThroughArgT(T t) { return t; }
struct Hold23 { int m = passThroughArgT<int>(23); };

struct HoldMemberThatHolds42 { Hold42 m; };
struct HoldMemberThatHoldsMemberThatHolds42 { HoldMemberThatHolds42 m; };

inline int get42Level4() { return get42(); }
inline int get42Level3() { return get42Level4(); }
inline int get42Level2() { return get42Level3(); }
inline int get42Level1() { return get42Level2(); }
struct Hold42WithLongInitCallGraph { int m = get42Level1(); };
5 changes: 5 additions & 0 deletions test/Interop/Cxx/class/Inputs/module.modulemap
Original file line number Diff line number Diff line change
Expand Up @@ -87,3 +87,8 @@ module InvalidNestedStruct {
header "invalid-nested-struct.h"
requires cplusplus
}

module InitializerFromInline {
header "initializer-from-inline.h"
requires cplusplus
}
20 changes: 20 additions & 0 deletions test/Interop/Cxx/class/initializer-from-inline.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// RUN: %swift -I %S/Inputs -enable-cxx-interop -emit-ir %s | %FileCheck %s

import InitializerFromInline

// CHECK: define linkonce_odr i32 @{{_Z5get42v|\?get42@@YAHXZ}}
// CHECK: define linkonce_odr i32 @{{_Z15passThroughArgTIiET_S0_|\?\?$passThroughArgT@H@@YAHH@Z}}
// CHECK: define linkonce_odr i32 @{{_Z11get42Level1v|\?get42Level1@@YAHXZ}}
// CHECK: define linkonce_odr i32 @{{_Z11get42Level2v|\?get42Level2@@YAHXZ}}
// CHECK: define linkonce_odr i32 @{{_Z11get42Level3v|\?get42Level3@@YAHXZ}}
// CHECK: define linkonce_odr i32 @{{_Z11get42Level4v|\?get42Level4@@YAHXZ}}

var a = Hold42()
var b = Hold23()
var c = HoldMemberThatHolds42()
var d = HoldMemberThatHoldsMemberThatHolds42()
var e = Hold42WithLongInitCallGraph()

let sum = a.m + b.m + c.m.m + d.m.m.m + e.m

print("Sum: \(sum)")