3

It appears that C functions which return structs sometimes use a magic hidden return argument carrying a pointer to some memory to be overwritten with the return value of the function.

For example, a C function declared like:

MyBuffer string_from_double(double d);

will appear in LLVM like:

declare void @string_from_double(%struct.MyBuffer* sret align 8, double)

Despite appearances, the function actually has two arguments instead of one. The magic argument is apparently identified by its sret tag.

(Bewilderingly, LLVM doesn't automatically perform the transformation from return-by-value, even for cdecl convention functions. There must be a reason for it, but it seems counterintuitive to me).

So my question is: From the compiler backend, how do I tell when an FFI function needs to be transformed into an "sret" form?

trbabb
  • 1,894
  • 18
  • 35
  • 1
    This will depend on the ABI for the target platform, and varies wildly from platform to platform. For X86 platforms, see the survey in Table 7 of https://www.agner.org/optimize/calling_conventions.pdf – rici Mar 31 '21 at 20:48
  • 1
    @rici It seems like this makes LLVM a leaky abstraction— I thought LLVM IR is generally supposed to be architecture-agnostic. Is there a way to get LLVM to tell me what I should do? E.g., is [`Type.isSingleValueType()`](https://llvm.org/doxygen/classllvm_1_1Type.html#a5f6edc5246188225b3f49bd5c974c759) a reliable way to check? How do other systems which implement FFI generally solve it? – trbabb Mar 31 '21 at 21:54
  • What compiler backend are you talking about in your question? – arrowd Apr 01 '21 at 15:37
  • @arrowd, the one I'm writing, which I'd like to make able to invoke FFI functions. – trbabb Apr 01 '21 at 16:40
  • How do you inform your frontend about FFI calls? Are you parsing C headers for this? – arrowd Apr 01 '21 at 17:55
  • @arrowd That's not *exactly* what I'm doing, but function and type declarations are basically the information that I have access to, so it's probably safe to imagine that I am. – trbabb Apr 01 '21 at 18:14
  • Well, then you have to replay what Clang does in case of C function returning a struct. Or in other words, what C standard say on this matter. – arrowd Apr 01 '21 at 18:33

0 Answers0