Join GitHub today
GitHub is home to over 40 million developers working together to host and review code, manage projects, and build software together.Sign up
A non-inlinable function that returns new memory always allocates it on the heap. For example, in the base64 package the
It is common for this return value to have limited life, easily scoped to the stack:
For cases like this, the
No heap allocation is necessary for calling this version. This transformation has been manually applied in many places in the standard library, from the
The compiler could do this automatically.
For concrete methods, the original function signature can be satisfied by a wrapper function, that allocates the value on the heap and calls a variant where return values containing pointers are passed as "out" arguments. When compiling code that can keep the output on the stack, the caller can be modified to use the generated functions.
For example, the implementation of
Currently, escape analysis determines that
Then the compiler can transform callers of
The general analysis of can the Ψ allocation function be inlined, and how does it pass data dependencies to the Φ function could get complicated.
I haven't done any research on how it would affect compiler time, or how often it would trigger. I suspect the easiest way to answer both would be to build a prototype. (I don't intend to anytime soon, just wanted to write the idea down.)
As described, I believe it would work through multiple calls. The Ψ-function would be inlined into the intermediate function, and a new Ψ-function for that intermediate function would be extracted from the inlined body. A lot would depend on inlining at the right time.