Lecture Slides 04 046-X86-Loops
Lecture Slides 04 046-X86-Loops
of Washington
Compiling
Loops
C/Java
code:
Machine
code:
while ( sum != 0 ) { loopTop: cmpl $0, %eax
<loop body> je loopDone
} <loop body code>
jmp loopTop
loopDone:
x86
University
of
Washington
x86
University
of
Washington
loop: .L11:
result *= x; imull %edx,%eax # result *= x
x = x-1; decl %edx # x--
if (x > 1) cmpl $1,%edx # Compare x : 1
goto loop; jg .L11 # if > goto loop
x86
University
of
Washington
¢ Body:
{
Statement1;
Statement2;
…
Statementn;
}
¢ Test
returns
integer
=
0
interpreted
as
false
≠
0
interpreted
as
true
x86
University
of
Washington
x86
University
of
Washington
x86
University
of
Washington
¢ Algorithm
§ Exploit
bit
representa6on:
p = p0 + 2p1 + 22p2 + … 2n–1pn–1
§ Gives:
xp = z0 · z1 2 · (z2 2) 2 · … · (…((zn –12) 2 )…) 2
Example
zi = 1
when
pi = 0
n–1
Umes
310
=
32
*
38
zi = x when
pi = 1
§ Complexity
O(log p)
=
32
*
((32)2)2
x86
University
of
Washington
ipwr
ComputaUon
/* Compute x raised to nonnegative power p */
int ipwr_for(int x, unsigned int p)
{
int result;
for (result = 1; p != 0; p = p>>1) {
if (p & 0x1)
result *= x;
x = x*x;
}
return result;
}
General
Form
for (Init; Test; Update)
Body
“For”→
“While”
For
Version
for (Init; Test; Update
)
Body
Goto
Version
Init;
goto middle;
loop:
While
Version
Body
Init; Update
;
while (Test
) { middle:
Body
if (Test)
Update
;
goto loop;
} done:
x86
University
of
Washington
For-‐Loop:
CompilaUon
for (result = 1; p != 0; p = p>>1)
For
Version
{
for (Init; Test; Update
) if (p & 0x1)
result *= x;
Body
x = x*x;
}
Goto
Version
Init; result = 1;
goto middle;
goto middle; loop:
loop: if (p & 0x1)
Body result *= x;
Update
; x = x*x;
middle: p = p >> 1;
if (Test) middle:
if (p != 0)
goto loop;
goto loop;
done: done:
x86