how to load (mov) a class variable into cpu register
I would like to load an int value defined as class member to eax cpu register. smt like this:
class x
{
int a;
x() { a=5; }
do_stuff()
{
__asm
{
mov eax, a; //开发者_如何学Go mov a varbiale content into register
};
}
};
how can I do that with any variable in any class? thanks...
If you are using gcc or icc, this does exactly what you want:
class x
{
int a;
x() { a=5; }
do_stuff()
{
asm("mov %0, %%eax; // mov a varbiale content into register \n"
:
: "r" (a)
: "%eax"
);
}
};
An explanation of rgister constrains and clobber lists is at http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html if you are still interested. On MS VC I would not recommend using inline assembly, because the MS compiler is not good at mixing inline and generated assmbely and produces a lot of overhead.
The best way to load a class variable into a register is by letting the compiler do it for you.
Since the compiler always have to assume the worst, when it comes to reading things from memory, it might be forced to read the value from a class member multiple times, despite the fact that you know that the value has not changed.
For example, in the code below in the function do_stuff
, the compiler can not assume that the value of mX
is unchanged over the call to foo()
. Hence, it is not allowed to place it in a processor register.
int glob;
int glob2;
void foo();
class Test
{
public:
Test(int x) : mX(x) { }
void do_stuff();
private:
int mX;
};
void Test::do_stuff()
{
glob = mX;
foo();
glob2 = mX;
}
On the other hand, in the following case, the source code is written so that tmp
can't change over the function call, so the compiler is safe to place it in a register.
void Test::do_stuff()
{
int tmp = mX;
glob = tmp;
foo();
glob2 = tmp;
}
When it comes to inline assembler, I would strongly discourage you from using it. When introducing C++ the situation is even worse, as the underlying representation of a class object is not as straight-forward as that of a C struct (which must be laid out in memory exactly as declared). This mean that a slight change in the class or a migration to a newer compiler could break your code.
You need to get the address of of the instance of class "x" you're working with (mov eax,this), and the offset of "a" relative to the start of "x" (offsetof macro).
It's a lot easier if you just add "a" or "&a" as a parameter of the do_stuff() function.
精彩评论