Yet another approach is to use the compiler and disassemble the result:
C
File
rpn.c:
Code:
int f() {
int a = 2;
int b = 3;
int c = 4;
int d = 5;
return (a+b)*(c+d);
}
Compile and disassemble:
gcc -g -c -o rpn.o rpn.c
objdump -S rpn.o
Code:
0000000000000000 <f>:
int f() {
0: 55 push %rbp
1: 48 89 e5 mov %rsp,%rbp
int a = 2;
4: c7 45 f0 02 00 00 00 movl $0x2,-0x10(%rbp)
int b = 3;
b: c7 45 f4 03 00 00 00 movl $0x3,-0xc(%rbp)
int c = 4;
12: c7 45 f8 04 00 00 00 movl $0x4,-0x8(%rbp)
int d = 5;
19: c7 45 fc 05 00 00 00 movl $0x5,-0x4(%rbp)
return (a+b)*(c+d);
20: 8b 45 f4 mov -0xc(%rbp),%eax
23: 8b 55 f0 mov -0x10(%rbp),%edx
26: 8d 0c 02 lea (%rdx,%rax,1),%ecx
29: 8b 45 fc mov -0x4(%rbp),%eax
2c: 8b 55 f8 mov -0x8(%rbp),%edx
2f: 8d 04 02 lea (%rdx,%rax,1),%eax
32: 0f af c1 imul %ecx,%eax
}
35: c9 leaveq
36: c3 retq
Java
File
rpn.java:
Code:
class rpn {
int f() {
int a = 2;
int b = 3;
int c = 4;
int d = 5;
return (a+b)*(c+d);
}
}
Compile and disassemble:
javac rpn.java
javap -c rpn
Code:
int f();
Code:
0: iconst_2
1: istore_1
2: iconst_3
3: istore_2
4: iconst_4
5: istore_3
6: iconst_5
7: istore 4
9: iload_1
10: iload_2
11: iadd
12: iload_3
13: iload 4
15: iadd
16: imul
17: ireturn
Python
File
rpn.py:
Code:
def f():
a, b, c, d = 2, 3, 4, 5
return (a+b)*(c+d)
Load and disassemble:
Code:
Python 2.6.6 (r266:84292, Nov 21 2013, 10:50:32)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from rpn import f
>>> from dis import dis
>>> dis(f)
2 0 LOAD_CONST 5 ((2, 3, 4, 5))
3 UNPACK_SEQUENCE 4
6 STORE_FAST 0 (a)
9 STORE_FAST 1 (b)
12 STORE_FAST 2 (c)
15 STORE_FAST 3 (d)
3 18 LOAD_FAST 0 (a)
21 LOAD_FAST 1 (b)
24 BINARY_ADD
25 LOAD_FAST 2 (c)
28 LOAD_FAST 3 (d)
31 BINARY_ADD
32 BINARY_MULTIPLY
33 RETURN_VALUE
Cheers
Thomas