I want to write this for loop in asm ,

for (i=0;i<1000000;i++){


}


Any ideas ?

I also want to incorporate this into a devc++ project so if anybody knows how to do this or of source then thanks.
Posted on 2004-05-15 07:11:36 by jonnyr
xor ebx,ebx

L1:
;#########
; code here
;
;#########
inc ebx
cmp ebx, 1000000
jl L1
Posted on 2004-05-15 07:22:09 by donkey
Careful, jl is signed (like jg, jge, jle).
If i is unsigned, you should use jb instead (or its cousins ja etc).

Also, compilers will often rewrite for loops to do-while loops which count down to 0, if possible, since this is the most efficient way to loop.

So it would rewrite eg to:



i = 1000000;

do {.. } while (--i);


Which would translate to:



mov ecx, 1000000

myLoop:
...
sub ecx, 1
jnz myLoop


You can see why this is the most efficient. The sub (not dec, since inc/dec are slower on P4s and Athlons) will already set the zero-flag, so there's no extra cmp required.
Alternatively you can count upwards to 0 (start at -1000000). This will allow you to index memory with it more easily (it still counts up, it is just offset from 0, which you can easily fix by offsetting the base-pointer aswell).
Posted on 2004-05-15 08:06:35 by Scali
Thanks well i added this to my C++ project,

asm(


"mov ecx, 1000000"
"myLoop:"
"sub ecx, 1"
"jnz myLoop"

);



I am getting the error, 'too many memory references for `mov''

any ideas ?


btw: i know virtually nothing about asm.
Posted on 2004-05-15 08:29:15 by jonnyr
I am not familiar with devc++, but the syntax you put there, is mixed gcc and VC++ syntax.

In VC++ it would be:


__asm{
mov ecx, 1000000
myLoop:
sub ecx, 1
jnz myLoop
}


In gcc you use AT&T syntax, and you write it as one big C string, pretty much. The compiler then spits out those C strings to a temporary asm file, inside the rest of the generated asm code, and then assembles the lot. Very nasty actually, 70s technology.
I never use it, so this may not be 100% correct, but it would sort of be like this:


asm(
"movl #1000000, %ecx \n"
"myLoop: \n"
"subl #1, %ecx \n"
"jnz myLoop \n"
);


Some things to note: '\n' at the end of each line, so the string actually works. And there is a size-suffix on every instruction ('l' in this case, to indicate a 'long' operation, or 32 bits), and each operand has a prefix that indicates whether it's a variable, register or immediate.
Posted on 2004-05-15 08:57:28 by Scali
Excellent thanks.

So i really need to go read up on the AT&T syntax.

:alright:
Posted on 2004-05-15 09:02:55 by jonnyr


xchg eax, eax

:grin:
Posted on 2004-05-15 09:38:50 by roticv
roticv, have to love those optimizing compilers! :)
Posted on 2004-05-15 10:00:47 by bitRAKE
An optimizing compiler would generate exactly nothing from an empty loop, beating your silly nop.
Posted on 2004-05-15 10:03:10 by Scali