0

Here is my code:

__asm__ ("movl %3, %%ecx\n"
         "movl $0, %%edx\n"
         "movl %2, %%eax\n"
         "1:\n"
         "movl %2, %%ebx\n"
         "movl %%ecx, %1\n" // Debugging
         //"movl %%edx, %3\n" // Debugging
         //"movl %%eax, %4\n" // Debugging
         "imul %%ebx, %%eax\n"
         "inc %%edx\n"
         "cmp %%edx, %%ecx\n"
         "jle 1b\n"
         "movl %%eax, %0\n"
       : "=r" (retval), "=r" (ecxval) 
       : "r" (val), "r" (pow));

(ecxval) is for debugging my code. (retval) is the return variable.

When I use 2 I always get either 4 or 0 which is weird.

(1:) is my label for my loop. (val) is the input value. (pow) is the power number. for example val: 2, pow: 5 is 2^5.

At the start of the program ecx is set to the val, edx is the counter so its set to 0, eax is set to the val. In the loop my code should move the contents of val to ebx multiply eax by ebx and the result is put into eax, then edx is increased by 1 and edx is compared to ecx and if less than or equal to it jumps and at the end the contents of eax are moved into the return value.

I've tried all ways I can think of to debug but with 2^(an even number) it always results in 4 and 2^(an uneven number) it always results in 0. But the expected result is for example 2^2 = 4, 2^3 = 8.

Timothy Baldwin
  • 3,551
  • 1
  • 14
  • 23
  • You use a bunch of hard-coded register names but don't declare clobbers on any of them. If you look at the compiler-generated asm, it should be clear that the compiler picked some of ECX, EDX, EAX, and EBX for `%0` through `%3`. Ask the compiler for inputs in registers you can modify so you don't have to start with `mov`, and so the compiler doesn't need twice as many registers as you have variables. Like `"+r"` or with `"0"(val)` "matching" constraints. You do still need early-clobber declarations on regs you write. – Peter Cordes Feb 03 '23 at 16:53
  • Possible duplicate: [Why we need Clobbered registers list in Inline Assembly?](https://stackoverflow.com/q/69453851) / [When to use earlyclobber constraint in extended GCC inline assembly?](https://stackoverflow.com/q/15819794) . See also the tag wiki https://stackoverflow.com/tags/inline-assembly/info for links to guides / docs. – Peter Cordes Feb 03 '23 at 17:14
  • Also, this should probably be tagged [gcc] and [c] – Peter Cordes Feb 03 '23 at 17:22
  • How would I use "0"(val) and "+r"? – Goennigoegoe Feb 03 '23 at 18:33
  • [segmentation fault(core dumped) error while using inline assembly](https://stackoverflow.com/a/60242248) linked from the tag wiki has some examples of read-write operands. – Peter Cordes Feb 03 '23 at 18:35

0 Answers0