Skip to content

Instantly share code, notes, and snippets.

@wilzbach
Last active Jul 24, 2018
Embed
What would you like to do?
C++ Munich Meetup - D without a runtime
int foo(int a, int b)
{
return (a % 3235272) % b;
}
int bar(int a)
{
return foo(a, 88);
}
extern(C) void main(int argc, char** argv) {
auto ret = foo(argc, 88);
version(print)
{
print_num(ret);
print(argv[0]);
print("\n");
print(argv[1]);
}
}
void print_num(int val)
{
enum base = 10;
char[11] buf = '0';
buf[$-1] = '\n';
auto gptr = buf.ptr + buf.length - 1;
do {
*(--gptr) = (val % base) + '0';
val /= base;
} while(val);
print(buf.ptr, buf.length);
}
void print(const char* c)
{
print(c, c.strlen);
}
void print(const char* c, size_t len)
{
asm
{
mov RDX, len;
mov RSI, c;
mov RAX, 1; // write
mov RDI, RAX;
syscall;
}
}
size_t strlen(const char* c)
{
auto cptr = cast(char*) c;
size_t i;
while (*cptr != 0)
{
cptr++;
i++;
}
return i;
}
> dmd -c -lib main.d runtime.d -of=main.o && ld.bfd main.o -o main
> perf stat -d ./main
Performance counter stats for './main':
0,127654 task-clock:u (msec) # 0,191 CPUs utilized
0 context-switches:u # 0,000 K/sec
0 cpu-migrations:u # 0,000 K/sec
1 page-faults:u # 0,008 M/sec
1.489 cycles:u # 0,012 GHz
39 instructions:u # 0,03 insn per cycle
7 branches:u # 0,055 M/sec
0 branch-misses:u # 0,00% of all branches
10 L1-dcache-loads:u # 0,078 M/sec
11 L1-dcache-load-misses:u # 110,00% of all L1-dcache hits
<not counted> LLC-loads:u (0,00%)
<not counted> LLC-load-misses:u (0,00%)
0,000667675 seconds time elapsed
> ldc -O3 -c -lib main.d runtime.d -of=main.a && ld.bfd main.a -o main
> perf stat -d ./main
Performance counter stats for './main':
0,130168 task-clock:u (msec) # 0,154 CPUs utilized
0 context-switches:u # 0,000 K/sec
0 cpu-migrations:u # 0,000 K/sec
1 page-faults:u # 0,008 M/sec
1.467 cycles:u # 0,011 GHz
18 instructions:u # 0,01 insn per cycle
5 branches:u # 0,038 M/sec
0 branch-misses:u # 0,00% of all branches
6 L1-dcache-loads:u # 0,046 M/sec
10 L1-dcache-load-misses:u # 166,67% of all L1-dcache hits
<not counted> LLC-loads:u (0,00%)
<not counted> LLC-load-misses:u (0,00%)
0,000846418 seconds time elapsed
> ldc -d-version=print -betterC -O3 -c -lib main.d runtime.d -of=main.a && ld.bfd main.a -o main && ./main 123 456
0000000003
./main
123
extern(C) void __d_sys_exit(long arg1)
{
asm
{
mov RAX, 60;
mov RDI, arg1;
syscall;
}
}
extern extern(C) void main(int, char**);
private extern(C) void _start()
{
int argc;
char** argv;
asm
{
mov RCX, 24[RSP];
mov argc, ECX;
lea RCX, 32[RSP];
mov argv, RCX;
}
main(argc, argv);
__d_sys_exit(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment