Difference between revisions of "Code Generation/Exercise 6"

From Wiki**3

< Code Generation
(Postfix Code)
Line 3: Line 3:
 
Consider the following C function:
 
Consider the following C function:
  
<c>
+
<source lang="c">
 
int powmod(int base, int exp, int modulus) {
 
int powmod(int base, int exp, int modulus) {
 
   int accum = 1, i = 0, basepow2 = base;
 
   int accum = 1, i = 0, basepow2 = base;
Line 14: Line 14:
 
   return accum;
 
   return accum;
 
}
 
}
</c>
+
</source>
  
 
== Postfix Code ==
 
== Postfix Code ==
Line 20: Line 20:
 
The Postfix code for the above function is as follows:  
 
The Postfix code for the above function is as follows:  
 
{{CollapsedCode|Postfix code|
 
{{CollapsedCode|Postfix code|
<asm>
+
<source lang="asm">
 
TEXT
 
TEXT
 
ALIGN
 
ALIGN
Line 105: Line 105:
 
LEAVE
 
LEAVE
 
RET
 
RET
</asm>
+
</source>
 
}}
 
}}
  

Revision as of 13:42, 12 February 2019

The Original Code

Consider the following C function:

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;
}

Postfix Code

The Postfix code for the above function is as follows:

Postfix code
TEXT
ALIGN
GLOBL powmod, FUNC
LABEL powmod
ENTER 12
INT 1
LOCAL -4
STINT
INT 0
LOCAL -8
STINT
LOCAL +8
LDINT
LOCAL -12
STINT

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

LOCAL +12
LDINT
LOCAL -8
LDINT
SHTRU
INT 1
AND
INT 1
EQ
JZ if_end

LOCAL -4
LDINT
LOCAL -12
LDINT
MUL
LOCAL +16
LDINT
MOD
DUP32
LOCAL -4
STINT
TRASH 4

ALIGN
LABEL if_end

LOCAL -12
LDINT
LOCAL -12
LDINT
MUL
LOCAL +16
LDINT
MOD
DUP32
LOCAL -12
STINT
TRASH 4

LOCAL -8
LDINT
DUP32
INT 1
ADD
LOCAL -8
STINT
TRASH 4

JMP while
LABEL while_end

LOCAL -4
LDINT
STFVAL32
LEAVE
RET

Compiling and Running

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

pf2asm powmod.pf
yasm -felf powmod.asm