0 p p1 if p 0x1 result x x xx return

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: conMnue looping Only take branch when “while” condiMon holds x86 University of Washington “Do ­While” Loop CompilaMon Goto Version int fact_goto(int x) { int result = 1; loop: result *= x; x = x-1; if (x > 1) goto loop; return result; } Assembly fact_goto: pushl %ebp movl %esp,%ebp movl $1,%eax movl 8(%ebp),%edx .L11: imull %edx,%eax decl %edx cmpl $1,%edx jg .L11 movl %ebp,%esp popl %ebp ret x86 Registers: %edx %eax x result # # # # Setup Setup eax = 1 edx = x # # # # result *= x x-Compare x : 1 if > goto loop # Finish # Finish # Finish University of Washington General “Do ­While” TranslaMon Goto Version C Code do   Body: {   Body while (Test); } loop: Body if (Test) goto loop Statement1; Statement2; … Statementn; Test returns integer = 0 interpreted as false ≠ 0 interpreted as true x86 University of Washington “While” Loop TranslaMon C Code int fact_while(int { int result = 1; while (x > 1) { result *= x; x = x-1; }; return result; } Goto Version x) int fact_while_goto(int x) { int result = 1; goto middle; loop: result *= x; x = x-1; middle: if (x > 1) goto loop; return result; } Used by GCC for both IA32 & x86 ­64   First iteraMon jumps over body computaMon within loop straight to test   x86 University of Washington “While” Loop Example int fact_while(int x) { int result = 1; while (x > 1) { result *= x; x--; }; return result; } # x in %edx, result in %eax jmp .L34 # goto Middle .L35: # Loop: imull %edx, %eax # result *= x decl %edx # x-.L34: # Middle: cmpl $1, %edx # x:1 jg .L35 # if >, goto # Loop x86 University of Washington “For” Loop Example: Square ­and ­MulMply /* 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; }   Algorithm   Exploit bit representaIon: p = p0 + 2p1 + 22p2 + … 2n–1pn–1   Gives: xp = z0 · z1 2 · (z2 2) 2 · … · (…((zn –12) 2 )…) 2 zi = 1 when pi = 0 zi = x when pi = 1   Complexity O(log p) Example n–1 Mmes 310 = 32 * 38 = 32 * ((32)2)2 x86 University of Washington ipwr ComputaMon /* 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...
View Full Document

This document was uploaded on 04/04/2014.

Ask a homework question - tutors are online