4

I'm attempting to write inline assembly in GCC which writes a value in a #define to a register.

#define SOME_VALUE 0xDEADBEEF void foo(void) { __asm__("lis r5, SOME_VALUE@ha"); __asm__("ori r5, r5, SOME_VALUE@l"); } 

However, I get an error when I compile:

undefined reference to `SOME_VALUE'

Is there a way for the assembler to see the #define in the inline assembly?

I've solved it by doing the following:

#define SOME_VALUE 0xDEADBEEF __asm__(".equ SOME_VALUE, 0xDEADBEEF"); void foo(void) { __asm__("lis r5, SOME_VALUE@ha"); __asm__("ori r5, r5, SOME_VALUE@l"); } 

However, I really don't want to duplicate the value.

4
  • 2
    As you can see, __asm__ is taking a string as an argument. So think about macro stringifying the value/ concatenating strings. Commented Sep 26, 2018 at 20:33
  • Just FYI, your examples are completely unsafe. If you're going to clobber a register, you need to use Extended asm with an output constraint. And you should definitely put multiple instructions in the same asm statement; you shouldn't assume that the compiler will put your asm statements back to back. Commented Sep 26, 2018 at 20:43
  • 1
    So if you're using extended asm anyway, you can use constraints to ask for SOME_VALUE as an immediate on whatever architecture that is. Or just ask the compiler to put it in r5 for you, with register int foo asm("r5") = SOME_VALUE; and then use it as an input. Or if you don't care what register, then let the compiler pick. Commented Sep 26, 2018 at 20:45
  • @PeterCordes Right, it was just a dumb example. I realize how unsafe it is. But thank you for pointing it out. Some one reading in the future may not realize it. Commented Sep 27, 2018 at 15:53

1 Answer 1

6

Use some preprocessor magic for stringification of the value and the string continuation in C:

#define SOME_VALUE 0xDEADBEEF #define STR(x) #x #define XSTR(s) STR(s) void foo(void) { __asm__("lis r5, " XSTR(SOME_VALUE) "@ha"); __asm__("ori r5, r5, " XSTR(SOME_VALUE) "@l"); } 

XSTR will expand into the string "0xDEADBEEF", which will get concatenated with the strings around it.

Here is the demo: https://godbolt.org/z/2tBfoD

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, but this seems like an XY problem, because that inline asm steps on the compiler's registers. See my comments on the question; using a numeric constant as an input constraint should work too as either an immediate / literal or as a register value.