Are reference type parameters to functions passed by copy or straight?

Hello in Javascript parameters that are reference types are first copied and then passed into functions. So effectively you have one more ref, the parameter, to some data.

I'm wondering how Swift handles reference type parameters for functions.

By default Swift uses an argument passing convention where the caller’s reference is “borrowed” temporarily by the callee, and if the callee wants to keep the reference around after returning, it has to make a new reference itself (for Swift reference types this is recorded by incrementing the object’s internal reference count).

However, in some cases (initializers, arguments marked as owned, or functions that the optimizer decides would benefit from it), Swift also supports a convention where the callee is given ownership of the reference, and the caller has to create the extra reference (increment the count) if it wants to continue using it.

3 Likes

Hey @David_Smith,
This is interesting to know! Just curious about what would be the criteria the optimizer uses to decide when this convention is used? Or in general in what kind of context this would be a benefit?

I’m fuzzy on the details myself, but if you feel up to reading compiler internals I believe this is the file you want: swift/FunctionSignatureOpts.cpp at main · apple/swift · GitHub

I think the “Total owned args -> guaranteed args" stat on line 56 is the one you’d want to look into.

(edit: actually that's going the other direction, I'm not sure if we have a transformation that converts to owned arguments)

2 Likes