Page 1 of 1

inline assembly problems

Posted: Sat Mar 20, 2010 3:01 pm
by FlashBurn
As I use segments in my OS and gcc (as most/all c compilers) doesn´t know anything of segments I need to use some sort of inline assembly to access these segments.

So I have a inline function like this:

Code: Select all

static inline uint32t getGSval(const uint32t offset) {
	uint32t res;
	
	asm volatile("movl %%gs:(%[off]),%[output]"
		:[output] "=r"(res)
		:[off] "q"(offset));
	
	return res;
}
Ok, it works, but I like to optimize it even more, because the offset will always be known at compile time, it would be better (because it frees a register) to use a constant for the offset, but how can I do this? I mean this doesn´t work:

Code: Select all

static inline uint32t getGSval(const uint32t offset) {
	uint32t res;
	
	asm volatile("movl %%gs:(%[off]),%[output]"
		:[output] "=r"(res)
		:[off] "i"(offset));
	
	return res;
}
Then I have another problem with this inline assembly:

Code: Select all

static inline void setGSval64(const uint32t offset, uint64t val) {
	asm volatile("movl %%eax,%%gs:(%[off])\n\t"
				"movl %%edx,%%gs:4(%[off])"
				:
				:"A"(val), [off] "q"(offset));
}
The problem here is that if gcc uses "eax" as register for "offset", it will be overwritten by the 1st assembly instruction and so the 2nd instruction is wrong (and results in this case in an general protection exception). So here I would need the constant way even more, because the register way isn´t working.

Re: inline assembly problems

Posted: Mon Mar 22, 2010 2:43 am
by qw
You are reading from a memory location, why not use the "m" constraint? GCC doesn't have to know that you're overriding the segment. GCC will optimize if "offset" is known at compile time.

Code: Select all

static inline uint32_t get_gs_val(uint32_t offset)
{
    uint32_t output;

    asm volatile
    (
        "movl	%%gs:%1, %0"
      : "=ar" (output)
      : "m" (*(const uint32_t *)offset)
    );
    return output;
}
Roel

Re: inline assembly problems

Posted: Mon Mar 22, 2010 3:03 am
by FlashBurn
Thanks, this saved my day and I can go on programming :D

Re: inline assembly problems

Posted: Mon Mar 22, 2010 3:38 am
by qw
You're welcome!