For very low level optimization purposes it would be useful to me if I could store a compiled function inside a variable directly, not a pointer to a function. That is, if I have a function foo, I want to make a char buffer large enough to hold the machine instructions generated for foo, and then be able to in effect call foo by somehow telling C to jump execution to the contents of that buffer (assume that I have a compiler intrinsic to make sure the char buffer is aligned properly for my architecture). Ideally, I'd like to do this keeping assembly usage to a minimum (I realize some might be required).
My best solution so far would be to compile a program that has just the function I want to assembly with GCC, then compile to machine code, then use the addresses from the outputted assembly to extract the desired machine code from the executable, then manually fill the buffer with that in my program, then use inline assembly to jump to the starting address of the buffer. That's more hackish and manual work than I would like though.
I don't need to compile new functions at runtime, just have the buffer contain instructions corresponding to different already compiled functions during runtime. E.g. I might have 3 compiled functions, and 1 buffer. The 3 functions are known at compile time, but at runtime the buffer may correspond to any one of the 3 at different times.
Edit: To clarify what there would be to gain: I have a struct of which this buffer will be a member, and various pointers to instances of that struct. Each struct's buffer may contain a different compiled function. If I were to use a function pointer instead of the buffer, I would have to load the struct's function pointer, then deref the function pointer. With the buffer, I can just jump the program counter to an offset (the buffer's relative location) of the base of the struct. It's one less level of indirection. For very tiny functions, this can be a savings.
Edit 2: Further clarifying:
With a function pointer:
- Load pointer from &struct+offsetof(pointer)
- Jump to location contained in pointer
With a buffer that contains machine code:
- Jump to &struct+offsetof(buffer)
The second one is less steps.