The PoC commit is already opened at [libc][RFC] add support for function level attributes by SchrodingerZhu · Pull Request #79891 · llvm/llvm-project (github.com).
Why is this needed?
According to discussions at [libc] abs is a const function by AtariDreams · Pull Request #79650 · llvm/llvm-project (github.com), it may be helpful to annotate some functions with attributes. For example, math kernels (such as abs) generally have no side effects and are constant on the same input. Annotate them with const will effectively assist compilers to emit better code.
How is it implemented?
I hope to introduce the following in the TableGen:
class FunctionAttr {}
class GnuFunctionAttr<string attr> : FunctionAttr {
string Attr = attr;
string Style = "gnu";
}
class Cxx11FunctionAttr<string attr, string namespace> : FunctionAttr {
string Attr = attr;
string Namespace = namespace;
string Style = "cxx11";
}
class DeclspecFunctionAttr<string attr> : FunctionAttr {
string Attr = attr;
string Style = "declspec";
}
class FunctionAttrSpec<string macro, list<FunctionAttr> instances> {
list<FunctionAttr> Instances = instances;
string Macro = macro;
}
Such that one can declare an attribute as:
FunctionAttrSpec ConstAttr = FunctionAttrSpec<"__LIBC_CONST_ATTR", [
Cxx11FunctionAttr<"const", "gnu">,
GnuFunctionAttr<"const">,
]>;
Then, for those applicable functions, the attribute can be added via:
FunctionSpec<"fabs", RetValSpec<DoubleType>, [ArgSpec<DoubleType>], [ConstAttr]>,
The generated header will be like:
__LIBC_CONST_ATTR double fabs(double) _NOTHROW;
Currently, the dispatch considerations are the following (in order):
- If
__cplusplusis defined andcxx11style is provided, define the macro usingcxx11version; - Otherwise, if
__GNUC__is defined andgnustyle is provided, define the macro usinggnuversion; - (unlikely, just for future-proof) Otherwise, if
_MSC_VERis defined and__declspecis provided, define the macro using__declspecversion; - Fallback to empty macro.
Limitations
- Not all attributes are supported, especially those who are sensitive to positions.
- Some special attributes need extra effort to define such as “quoting” the string parameter.
- Parameter attributes are not considered.
- Attributes are collected per header file, so repeated definitions are expected (Of course, all these macros are gated by macro guards and
#undefat the end of the file. I just mean code duplication).
Other considerations
- There is an existing
_Noreturnattribute which is handled in a rather “ad hoc” way (they are annotated as special return types). Perhaps we can change it to this new style if the proposal is accepted. - Is
#pragma push_macro("...")a better way to guard these macros?
Thanks @Lancern for mentioning the following to me:
- As mentioned in the commit, we may want to check the namespace of
cxx11style. Especially when we really want theMSVCversion to work. c23style is not yet considered.