Difference between revisions of "Code Generation/Exercise 6"

From Wiki**3

< Code Generation
(Created page with "== The Original Code == Consider the following C function: <c> int powmod(int base, int exp, int modulus) { int accum = 1, i = 0, basepow2 = base; while ((exp >> i) > 0) { ...")
 
Line 92: Line 92:
 
To compile the Postfix code directly, [[pf2asm]] can be used:
 
To compile the Postfix code directly, [[pf2asm]] can be used:
  
* pf2asm gcd.pf
+
* pf2asm powmod.pf
* yasm -felf gcd.asm
+
* yasm -felf powmod.asm
  
 
[[category:Compilers]]
 
[[category:Compilers]]
 
[[category:Teaching]]
 
[[category:Teaching]]

Revision as of 16:37, 21 May 2011

The Original Code

Consider the following C function:

<c> int powmod(int base, int exp, int modulus) {

 int accum = 1, i = 0, basepow2 = base;
 while ((exp >> i) > 0) {
   if (((exp >> i) & 1) == 1) 
     accum = (accum * basepow2) % modulus;
   basepow2 = (basepow2 * basepow2) % modulus;
   i++;
 }
 return accum;

} </c>

Postfix Code

The Postfix code for the above function is as follows:

<asm> TEXT ALIGN GLOBL powmod, FUNC LABEL powmod ENTER 12 INT 1 LOCA -4 INT 0 LOCA -8 LOCV +8 LOCA -12

ALIGN LABEL while LOCV +12 LOCV -8 SHTRU INT 0 GT JZ while_end

LOCV +12 LOCV -8 SHTRU INT 1 AND INT 1 EQ JZ if_end

LOCV -4 LOCV -12 MUL LOCV +16 MOD DUP LOCA -4 TRASH 4

ALIGN LABEL if_end

LOCV -12 LOCV -12 MUL LOCV +16 MOD DUP LOCA -12 TRASH 4

LOCV -8 DUP INT 1 ADD LOCA -8 TRASH 4

JMP while LABEL while_end

LOCV -4 POP LEAVE RET </asm>

Compiling and Running

To compile the Postfix code directly, pf2asm can be used:

  • pf2asm powmod.pf
  • yasm -felf powmod.asm