ice799 (owner)

Revisions

gist: 219407 Download_button fork
public
Public Clone URL: git://gist.github.com/219407.git
Embed All Files: show embed
branch_predictor.c #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#if 0
In these examples, let's assume that passing more than 2 args to the program is
*not* the case we are optimizing this for.
 
With that in mind, lets build a sample program with
and without __builtin_expect and compare assembly output.
#endif
 
/*
no predictor:
 
sub $0x8,%rsp
cmp $0x3,%edi
jle 0x4004e8 <main+24> ; <===== fail
int3 ; <===== fail
xor %eax,%eax
add $0x8,%rsp
retq
nopl 0x0(%rax)
mov $0x4005ec,%edi
callq 0x4003c0 <puts@plt>
xor %eax,%eax
add $0x8,%rsp
retq
 
*/
 
#include <stdio.h>
 
int main(int argc, char *argv[]) {
 
  if (argc > 3)
    asm("int $0x3\n");
  else
    printf("yo dog\n");
 
  return 0;
}
 
 
===
 
/*
with predictor:
 
sub $0x8,%rsp
cmp $0x3,%edi
jg 0x4004ea <main+26> ; <==== win
mov $0x4005dc,%edi ; <==== win
callq 0x4003c0 <puts@plt>
xor %eax,%eax
add $0x8,%rsp
retq
int3
jmp 0x4004e3 <main+19>
 
*/
 
#include <stdio.h>
 
#define unlikely(x) __builtin_expect((x),0)
 
int main(int argc, char *argv[]) {
 
  if (unlikely(argc > 3))
    asm("int $0x3\n");
  else
    printf("yo dog\n");
 
  return 0;
}