Skip to content
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

Create MethodOp for representing C++ methods #343

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
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
48 changes: 26 additions & 22 deletions include/vast/Dialect/HighLevel/HighLevelOps.td
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,19 @@ def ScopeOp : HighLevel_Op< "scope", [NoTerminator] >
let assemblyFormat = [{ $body attr-dict }];
}

def FuncOp : HighLevel_Op< "func", [
AutomaticAllocationScope, CallableOpInterface, FunctionOpInterface,
IsolatedFromAbove, Symbol, NoTerminator
] > {
let summary = "VAST high-level function definintion or declaration";

class FuncLikeOp< string mnemonic, dag add_args = (ins), dag add_builders = (ins), string add_init = "" >
: HighLevel_Op< mnemonic, [
AutomaticAllocationScope, CallableOpInterface, FunctionOpInterface,
IsolatedFromAbove, Symbol, NoTerminator ] >
, Arguments< !con((ins
SymbolNameAttr:$sym_name,
TypeAttrOf<FunctionType>:$function_type,
DefaultValuedAttr<GlobalLinkageKind, "GlobalLinkageKind::ExternalLinkage">:$linkage),
add_args,
(ins OptionalAttr<StrAttr>:$sym_visibility,
OptionalAttr<DictArrayAttr>:$arg_attrs,
OptionalAttr<DictArrayAttr>:$res_attrs)) >
{
let description = [{
Inspired by `cir::FuncOp` and `mlir::func::FuncOp`:
> Operations within the function cannot implicitly capture values defined
Expand All @@ -62,26 +69,18 @@ def FuncOp : HighLevel_Op< "func", [
`GlobalLinkageKind` attribute.
}];

let arguments =(ins
SymbolNameAttr:$sym_name,
TypeAttrOf<FunctionType>:$function_type,
DefaultValuedAttr<GlobalLinkageKind, "GlobalLinkageKind::ExternalLinkage">:$linkage,
OptionalAttr<StrAttr>:$sym_visibility,
OptionalAttr<DictArrayAttr>:$arg_attrs,
OptionalAttr<DictArrayAttr>:$res_attrs
);

let regions = (region AnyRegion:$body);
let skipDefaultBuilders = 1;

let builders = [OpBuilder< (ins
let builders = [OpBuilder< !con((ins
"llvm::StringRef":$name,
"mlir::FunctionType":$type,
CArg< "GlobalLinkageKind", "GlobalLinkageKind::ExternalLinkage" >:$linkage,
CArg< "llvm::ArrayRef<mlir::NamedAttribute>", "{}" >:$attrs,
CArg< "GlobalLinkageKind", "GlobalLinkageKind::ExternalLinkage" >:$linkage),
add_builders,
(ins CArg< "llvm::ArrayRef<mlir::NamedAttribute>", "{}" >:$attrs,
CArg< "llvm::ArrayRef<mlir::DictionaryAttr>", "{}" >:$arg_attrs,
CArg< "llvm::ArrayRef<mlir::DictionaryAttr>", "{}" >:$res_attrs,
CArg< "BuilderCallback", "std::nullopt" >:$body), [{
CArg< "BuilderCallback", "std::nullopt" >:$body)), !strconcat([{
InsertionGuard guard($_builder);
build_region($_builder, $_state, body);

Expand All @@ -92,6 +91,7 @@ def FuncOp : HighLevel_Op< "func", [
$_state.addAttribute(
"linkage", GlobalLinkageKindAttr::get($_builder.getContext(), linkage)
);
}], add_init, [{
$_state.attributes.append(attrs.begin(), attrs.end());

if (arg_attrs.empty())
Expand All @@ -101,7 +101,7 @@ def FuncOp : HighLevel_Op< "func", [
$_builder, $_state, arg_attrs, res_attrs,
getArgAttrsAttrName($_state.name), getResAttrsAttrName($_state.name)
);
}] >
}]) >
];

let extraClassDeclaration = [{
Expand Down Expand Up @@ -139,11 +139,15 @@ def FuncOp : HighLevel_Op< "func", [
bool isDeclaration() { return isExternal(); }
}];

let hasVerifier = 1;
}

def FuncOp : FuncLikeOp< "func" > {
let summary = "VAST high-level function definintion or declaration";

let assemblyFormat = [{
$linkage $sym_name custom< FunctionSignatureAndBody >($function_type, attr-dict, $body)
}];

let hasVerifier = 1;
}

def TypeDeclOp
Expand Down
53 changes: 53 additions & 0 deletions include/vast/Dialect/HighLevel/HighLevelOpsCxx.td
Original file line number Diff line number Diff line change
Expand Up @@ -85,4 +85,57 @@ def ThisOp
}];
}

def NoRef :
I32EnumAttrCase<"ref_none", 0, "ref_none">;
def LValueRef :
I32EnumAttrCase<"ref_lvalue", 1, "ref_lvalue">;
def RValueRef :
I32EnumAttrCase<"ref_rvalue", 2, "ref_rvalue">;

def RefQualifier : I32EnumAttr<
"RefQualifier", "ref qualifier",
[
NoRef, LValueRef, RValueRef
]>
{
let cppNamespace = "::vast::hl";
}

def MethodOp
: FuncLikeOp< "method", (ins
UnitAttr:$is_virtual,
UnitAttr:$is_const,
UnitAttr:$is_volatile,
RefQualifier:$ref), (ins
CArg< "bool", "false" >:$is_virtual,
CArg< "bool", "false" >:$is_const,
CArg< "bool", "false" >:$is_volatile,
CArg< "RefQualifier", "RefQualifier::ref_none" >:$ref), [{
if (is_virtual) {
$_state.addAttribute(
"is_virtual", mlir::UnitAttr::get($_builder.getContext())
);
}
if (is_const) {
$_state.addAttribute(
"is_const", mlir::UnitAttr::get($_builder.getContext())
);
}
if (is_volatile) {
$_state.addAttribute(
"is_volatile", mlir::UnitAttr::get($_builder.getContext())
);
}
$_state.addAttribute(
"ref", RefQualifierAttr::get($_builder.getContext(), ref)
);
}] >
{
let summary = "VAST high-level method definintion or declaration";

let assemblyFormat = [{
$linkage (`virtual` $is_virtual^)? $ref (`const` $is_const^)? (`volatile` $is_volatile^)? $sym_name custom< FunctionSignatureAndBody >($function_type, attr-dict, $body)
}];
}

#endif // VAST_DIALECT_HIGHLEVEL_IR_HIGHLEVELOPS_CXX
3 changes: 3 additions & 0 deletions include/vast/Translation/CodeGen.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ namespace vast::cg
using EnumConstantsScope = ScopedSymbolTable< const clang::EnumConstantDecl *, hl::EnumConstantOp >;
using LabelTable = ScopedSymbolTable< const clang::LabelDecl*, hl::LabelDeclOp >;
using FunctionsScope = ScopedSymbolTable< mangled_name_ref, hl::FuncOp >;
using MethodsScope = ScopedSymbolTable< mangled_name_ref, hl::MethodOp >;
using VariablesScope = ScopedSymbolTable< const clang::VarDecl *, Value >;

struct CodegenScope {
Expand All @@ -98,6 +99,7 @@ namespace vast::cg
EnumConstantsScope enumconsts;
LabelTable labels;
FunctionsScope funcdecls;
MethodsScope methdecls;
VariablesScope globs;
};

Expand Down Expand Up @@ -597,6 +599,7 @@ namespace vast::cg
.enumconsts = _cgctx.enumconsts,
.labels = _cgctx.labels,
.funcdecls = _cgctx.funcdecls,
.methdecls = _cgctx.methdecls,
.globs = _cgctx.vars
});

Expand Down
16 changes: 14 additions & 2 deletions include/vast/Translation/CodeGenContext.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,9 @@ namespace vast::cg
using FuncDeclTable = scoped_table< mangled_name_ref, hl::FuncOp >;
FuncDeclTable funcdecls;

using MethodDeclTable = scoped_table< mangled_name_ref, hl::MethodOp >;
MethodDeclTable methdecls;

using EnumDecls = scoped_table< const clang::EnumDecl *, hl::EnumDeclOp >;
EnumDecls enumdecls;

Expand Down Expand Up @@ -207,8 +210,17 @@ namespace vast::cg
return symbol(funcdecls, mangled, "undeclared function '" + mangled.name + "'", with_error);
}

hl::FuncOp declare(mangled_name_ref mangled, auto vast_decl_builder) {
return declare< hl::FuncOp >(funcdecls, mangled, vast_decl_builder, mangled.name);
hl::MethodOp lookup_method(mangled_name_ref mangled, bool with_error = true) {
return symbol(methdecls, mangled, "undeclared method '" + mangled.name + "'", with_error);
}

template< typename Op >
Op declare(mangled_name_ref mangled, auto vast_decl_builder) {
if constexpr (std::is_same_v< Op, hl::FuncOp >) {
return declare< Op >(funcdecls, mangled, vast_decl_builder, mangled.name);
} else {
return declare< Op >(methdecls, mangled, vast_decl_builder, mangled.name);
}
}

mlir_value declare(const clang::VarDecl *decl, mlir_value vast_value) {
Expand Down
66 changes: 56 additions & 10 deletions include/vast/Translation/CodeGenDeclVisitor.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ namespace vast::cg {

// make function header, that will be later filled with function body
// or returned as declaration in the case of external function
auto fn = context().declare(mangled_name, [&] () {
auto fn = context().template declare< hl::FuncOp >(mangled_name, [&] () {
return make< hl::FuncOp >(loc, mangled_name.name, fty, linkage);
});

Expand Down Expand Up @@ -293,13 +293,21 @@ namespace vast::cg {
}

// FIXME: remove as this duplicates logic from codegen driver
template< typename Decl >
operation VisitFunctionLikeDecl(const Decl *decl) {
template< typename Op, typename Decl, typename Builder >
operation VisitFunctionLikeDecl(const Decl *decl, Builder builder_callback) {
auto gdecl = get_gdecl(decl);
auto mangled = context().get_mangled_name(gdecl);

if (auto fn = context().lookup_function(mangled, false /* emit no error */)) {
return fn;
if constexpr (std::is_same_v< Op, hl::FuncOp >) {
if (auto fn = context().lookup_function(mangled, false /* emit no error */)) {
return fn;
}
}

if constexpr (std::is_same_v< Op, hl::MethodOp >) {
if (auto fn = context().lookup_method(mangled, false /* emit no error */)) {
return fn;
}
}

InsertionGuard guard(builder());
Expand Down Expand Up @@ -402,12 +410,12 @@ namespace vast::cg {

auto linkage = hl::get_function_linkage(gdecl);

auto fn = context().declare(mangled, [&] () {
auto fn = context().template declare< Op >(mangled, [&] () {
auto loc = meta_location(decl);
auto type = visit(decl->getFunctionType()).template cast< mlir::FunctionType >();
// make function header, that will be later filled with function body
// or returned as declaration in the case of external function
return make< hl::FuncOp >(loc, mangled.name, type, linkage);
return builder_callback(loc, mangled.name, type, linkage);
});

if (!is_definition) {
Expand All @@ -426,15 +434,39 @@ namespace vast::cg {
}

operation VisitFunctionDecl(const clang::FunctionDecl *decl) {
return VisitFunctionLikeDecl(decl);
return VisitFunctionLikeDecl< hl::FuncOp >(decl, [&](auto loc, auto name, auto type, auto linkage) {
return make< hl::FuncOp >(loc, name, type, linkage);
});
}

operation VisitCXXMethodDecl(const clang::CXXMethodDecl *decl) {
return VisitFunctionLikeDecl< hl::MethodOp >(decl, [&](auto loc, auto name, auto type, auto linkage) {
return make< hl::MethodOp >(loc, name, type, linkage,
decl->isVirtual(),
decl->isConst(),
decl->isVolatile(),
convert_ref_qual(decl->getRefQualifier()));
});
}

operation VisitCXXConstructorDecl(const clang::CXXConstructorDecl *decl) {
return VisitFunctionLikeDecl(decl);
return VisitFunctionLikeDecl< hl::MethodOp >(decl, [&](auto loc, auto name, auto type, auto linkage) {
return make< hl::MethodOp >(loc, name, type, linkage,
decl->isVirtual(),
decl->isConst(),
decl->isVolatile(),
convert_ref_qual(decl->getRefQualifier()));
});
}

operation VisitCXXDestructorDecl(const clang::CXXDestructorDecl *decl) {
return VisitFunctionLikeDecl(decl);
return VisitFunctionLikeDecl< hl::MethodOp >(decl, [&](auto loc, auto name, auto type, auto linkage) {
return make< hl::MethodOp >(loc, name, type, linkage,
decl->isVirtual(),
decl->isConst(),
decl->isVolatile(),
convert_ref_qual(decl->getRefQualifier()));
});
}

//
Expand Down Expand Up @@ -649,6 +681,18 @@ namespace vast::cg {
VAST_UNREACHABLE("unknown access specifier");
}

hl::RefQualifier convert_ref_qual(clang::RefQualifierKind kind) {
switch(kind) {
case clang::RefQualifierKind::RQ_None:
return hl::RefQualifier::ref_none;
case clang::RefQualifierKind::RQ_LValue:
return hl::RefQualifier::ref_lvalue;
case clang::RefQualifierKind::RQ_RValue:
return hl::RefQualifier::ref_rvalue;
}
VAST_UNREACHABLE("unknown ref qualifier");
}

//
// Record Declaration
//
Expand Down Expand Up @@ -685,6 +729,8 @@ namespace vast::cg {
visit(ctor);
} else if (auto dtor = clang::dyn_cast< clang::CXXDestructorDecl >(child)) {
visit(dtor);
} else if (auto method = clang::dyn_cast< clang::CXXMethodDecl >(child)) {
visit(method);
} else if (auto func = clang::dyn_cast< clang::FunctionDecl >(child)) {
auto name = func->getDeclName();
if (name.getNameKind() != clang::DeclarationName::NameKind::Identifier) {
Expand Down
31 changes: 24 additions & 7 deletions lib/vast/Dialect/HighLevel/HighLevelOps.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -36,22 +36,23 @@ namespace vast::hl
// Verifies linkage types, similar to LLVM:
// - functions don't have 'common' linkage
// - external functions have 'external' or 'extern_weak' linkage
logical_result FuncOp::verify() {
auto linkage = getLinkage();
template<typename Op>
logical_result verify_funclike(Op* self) {
auto linkage = self->getLinkage();
constexpr auto common = GlobalLinkageKind::CommonLinkage;
if (linkage == common) {
return emitOpError() << "functions cannot have '"
return self->emitOpError() << "functions cannot have '"
<< stringifyGlobalLinkageKind(common)
<< "' linkage";
}

// isExternal(FunctionOpInterface) only checks for empty bodyonly checks for empty body...
// We need to be able to handle functions with internal linkage without body.
if (linkage != GlobalLinkageKind::InternalLinkage && isExternal()) {
if (linkage != GlobalLinkageKind::InternalLinkage && self->isExternal()) {
constexpr auto external = GlobalLinkageKind::ExternalLinkage;
constexpr auto weak_external = GlobalLinkageKind::ExternalWeakLinkage;
if (linkage != external && linkage != weak_external) {
return emitOpError() << "external functions must have '"
return self->emitOpError() << "external functions must have '"
<< stringifyGlobalLinkageKind(external)
<< "' or '"
<< stringifyGlobalLinkageKind(weak_external)
Expand All @@ -62,6 +63,14 @@ namespace vast::hl
return mlir::success();
}

logical_result FuncOp::verify() {
return verify_funclike(this);
}

logical_result MethodOp::verify() {
return verify_funclike(this);
}

ParseResult parseFunctionSignatureAndBody(
Parser &parser, Attribute &funcion_type, mlir::NamedAttrList &attr_dict, Region &body
) {
Expand Down Expand Up @@ -116,16 +125,24 @@ namespace vast::hl
return mlir::success();
}

template< typename Op >
void printFunctionSignatureAndBody(
Printer &printer, FuncOp op, Attribute /* funcion_type */, mlir::DictionaryAttr, Region &body
Printer &printer, Op op, Attribute /* funcion_type */, mlir::DictionaryAttr, Region &body
) {
auto fty = op.getFunctionType();
mlir::function_interface_impl::printFunctionSignature(
printer, op, fty.getInputs(), /* variadic */false, fty.getResults()
);

mlir::function_interface_impl::printFunctionAttributes(
printer, op, {"linkage", op.getFunctionTypeAttrName() }
printer, op, {
"linkage",
op.getFunctionTypeAttrName(),
"is_virtual",
"is_const",
"is_volatile",
"ref"
}
);

if (!body.empty()) {
Expand Down
Loading