Machine Level Programming: Control Computer Systems Organization (Spring 2016) CSCI-UA 201, Section 2
Instructor: Joanna Klukowska
Slides adapted from Randal E. Bryant and David R. O’Hallaron (CMU) Mohamed Zahran (NYU)
Condition Codes
2
Processor State (x86-64, first look) Information about currently executing program ● Temporary da data ( %rax, … ) ● Lo Loca cati tio on of of run runti time me st stac ack k ( %rsp ) ● Lo Loca cati tio on of of cur curre rent nt co cod de control point ( %rip, … ) ● Status of of re recent tests ( CF, ZF, SF, OF ) current top of the stack
3
Condition Codes (Implicit Setting) ●
Single bit registers ○ ○
●
CF ZF
Carry Flag (for unsigned) SF Sign Flag (for signed) Zero Flag OF Overflow Flag (for signed)
Implic Imp licitly itly set (thi (think nk of itit as side side effe effect) ct) by by arithm arithmeti etic c operat operation ions s Example: addq Src,Dest ↔ t = a+b CF set if carry out from most significant bit (unsigned overflow) ZF set if t == 0 SF set if t < 0 (as signed) OF set if two’s-complement (signed) overflow (a>0 && b>0 && t<0) || (a<0 && b<0 && t>=0)
●
Not set by leaq instruction 4
Condition Codes (Explicit Setting - cmpq ) ●
Expl Ex plici icitt Set Setti ting ng by Co Comp mpar are e Ins Instr truc ucti tion on
cmpq Src2, Src1 ○
cmpq b,a
○
CF set if car carry ry out fro from m mos mostt sig signif nifica icant nt bit (us (used ed for uns unsign igned ed comparisons) ZF set if a == b SF se sett if (a (a-b -b)) < 0 (a (as s si sign gned ed)) OF se sett if tw two’ o’ss-co comp mple leme ment nt (s (sig igne ned) d) ov over erfl flow ow (a>0 (a >0 && && b<0 b<0 && (a(a-b) b)<0 <0)) || (a< (a<0 0 && b>0 b>0 && && (a-b (a-b)> )>0) 0)
○ ○ ○ ○
like computing a-b without setting destination
5
Condition Codes (Explicit Setting - testq ) ●
Expl Ex plic icit it Set Setti ting ng by by Test Test ins instr truc ucti tion on
testq Src2, Src1 ○ ○ ○
testq b,a like computing a&b without setting s etting destination Sets Se ts cond condit itio ion n code codes s base based d on val value ue of of Src1 Src1 & Src Src2 2 Usef Us eful ul to ha have ve on one e of of the the ope opera rand nds s be be a ma mask sk
○ ○
ZF set when a&b == 0 SF set when a&b < 0
6
Reading Condition Codes ●
SetX family of instructions ○ ○
Set low-o low-order rder byte of destina destination tion to 0 or 1 based on combin combination ations s of condi condition tion codes Does Do es no nott alt alter er re rema main inin ing g 7 by byte tes s
7
x86-64 Integer Registers
We can reference low-order byte. 8
Reading Condition Codes ●
SetX In Inst strructi tio ons: ○ ○ ○ ○ ○
Set sin single gle byt byte e base based d on on combi combinat nation ion of cond conditi ition on code codes s One On e of of addr addres essa sabl ble e byt byte e reg regis iste ters rs Does Do es no nott alt alter er re rema main inin ing g byt bytes es Typically use movzbl to finish job (32(3 2-bi bitt instr instruc ucti tion ons s also also set set upp upper er 32 32 bits bits to to 0)
int gt (long x, long y) { return x > y; }
cmpq %rsi, %rdi setg %al movzbl %al, %eax ret
# Compare x:y # Set when > # Zero rest of %rax 9
Conditional Branches
10
Jumping (in the code) jX family of instructions ●
Jump Jum p to dif differ ferent ent par partt of code code dep depend ending ing on cond conditio ition n codes codes
11
Re-Writing Code with goto Statements ● ●
C allows goto statement Jump Ju mp to to posi positi tion on des desig igna nate ted d by by labe labell
long absdiff (long x, long y) { long result; if (x > y)
result = x-y;
result = x-y;
else
result = y-x; return result; }
long absdiff_j (long x, long y) { long result; int ntest = x <= y; if (ntest) goto Else; goto Done; Else:
result = y-x; Done: return result; }
Why do that? ● Becaus Because e the "goto" "goto" code code is close closerr to the the assemb assembly ly inst instruc ructio tions. ns. 12
General Conditional Expression Translation C code:
val = Test ? Then Expr : Else Expr; for example: val = x>y ? x-y : y-x;
ntest = !Test; if (ntest) goto Else; val = Then_Expr; goto Done; Else: val = Else_Expr; Done: . . .
●
Crea Create te sep separ arat ate e cod code e reg regio ions ns for for then & else expressions
●
Exe Execute cute appr approp opri riat ate e one one
13
Using Conditional Moves ●
Cond Co ndit itio iona nall Mo Move ve In Inst stru ruct ctio ions ns ○
Instr tru uction sup supports:
if (Test) Dest
⇐
Src
○
Supp Su ppor orte ted d in in pos post-1 t-199 995 5 x86 x86 pr proc oces esso sors rs
○
GCC GC C tri tries es to use use th them em,, but but only only wh when en kn know own n to be safe
●
Why? ○
Branch Bra nches es are ver very y disr disrupt uptive ive to ins instru tructi ction on flo flow w through pipelines
○
Cond Co ndit itio iona nall mov moves es do do not not req requi uire re con contro troll transfer
C Code: val = Test ? Then_Expr : Else_Expr;
goto version: result = Then_Expr; eval = Else_Expr; nt = !Test; if (nt) result = eval; return result;
14
Conditional Move Example long absdiff (long x, long y) { long result; if (x > y)
result = x-y;
else
result = y-x; return result; }
absdiff: movq
%rdi, %rax
# x
subq
%rsi, %rax
# result = x-y
movq
%rsi, %rdx
subq
%rdi, %rdx
# eval = y-x
cmpq cmovle ret
%rsi, %rdi %rdx, %rax
# x:y # if <=, result = eval
15
Bad Cases of Conditional Move
●
expe ex pens nsiv ive e co comp mpu uta tati tion ons: s: ○ ○
●
risky co computations ○ ○
●
bot oth h val value ues s get get ca callcu cullat ated ed only onl y make makes s sens sense e when when com comput putati ations ons are ver very y sim simple ple
bot oth h val value ues s get get ca callcu cullat ated ed may have undes undesirabl irable e side side effects effects (abov (above e it is derefere dereferencing ncing a pointer pointer that that may may be 0)
comp co mput utat atio ions ns wi with th si side de ef effe fect cts s ○ ○
bot oth h val value ues s get get ca callcu cullat ated ed must mu st be be side side-eff -effect ect fre free e (unli (unlike ke the exa exampl mple e abov above) e)
16
Loops
17
do...while… loop example long pcount_do (unsigned long x) { long result = 0; do { result += x & 0x1; x >>= 1; } while (x); return result; }
● ●
long pcount_goto (unsigned long x) { long result = 0; loop: result += x & 0x1; x >>= 1; if(x) goto loop; return result; }
Countt num Coun numbe berr of of 1’s 1’s in ar argu gume ment nt x Use cond conditi itiona onall branc branch h to eith either er conti continue nue loo loopin ping g or to to exit exit loop loop
18
do...while… loop compilation long pcount_goto (unsigned long x) { long result = 0; loop: result += x & 0x1; x >>= 1; if(x) goto loop; return result; }
movl $0, %eax .L2: movq %rdi, %rdx andl $1, %edx addq %rdx, %rax shrq %rdi jne .L2 rep; ret
# result = 0 # loop: # # # #
t = x & 0x1 result resul t += t x >>= 1 if (x) goto loop
19
General do...while… Translation loop: do Body
while (Test);
Body
if (Test) goto loop
20
General while Loop Translation (ver. 1)
while (Test) Body
goto test; loop: Body
test: if (Test) goto loop; done:
● ●
“Jump“Jum p-to to-m -mid iddl dle” e” tr tran ansl slat atio ion n Use Us ed wit with h -O -Og op opti tio on to to gcc gcc
21
General while Loop Translation (ver. 1) long pcount_while (unsigned long x) { long result = 0; while (x) { result += x & 0x1; x >>= 1; } return result; }
● ●
long pcount_goto_jtm(unsigned pcount_goto_jtm(unsigned long x) { long result = 0; goto test; loop: result += x & 0x1; x >>= 1; test: if(x) goto loop; return result; }
Compar Comp are e to to dodo-wh whilile e ver versi sion on of fu func ncti tion on Init In itia iall got goto o sta start rts s loo loop p at at tes testt
22
General while Loop Translation (ver. 2)
while (Test)
● ●
“Do Do--while” con conve verrsion Used with -O - O1
Body
convert to do.. while.. first
if (!Test) goto done; do Body
while(Test); done:
if (!Test) goto done; loop: Body if (Test)
goto loop; done: 23
General while Loop Translation (ver. 1) long pcount_while (unsigned long x) { long result = 0; while (x) { result += x & 0x1; x >>= 1; } return result; }
● ●
long pcount_goto_dw (unsigned long x) { long result = 0; if (!x) goto done; loop: result += x & 0x1; x >>= 1; if(x) goto loop; done: return result; }
Compar Comp are e to to dodo-wh whilile e ver versi sion on of fu func ncti tion on Init In itia iall cond condit itio iona nall guar guards ds ent entra ranc nce e to lo loop op
24
for Loop Form General form: for (Init; Test; Update ) Body
#define WSIZE 8*sizeof(int) long pcount_for (unsigned long x) { size_t i; long result = 0; for (i = 0; i < WSIZE; i++) { unsigned bit = (x >> i) & 0x1; result += bit; } return result; } 25
for Loop ⇒ while loop
for (Init; Test; Update ) Body convert to while loop
Init;
while (Test ) { Body Update
}
26
for Loop ⇒ while loop long pcount_for_while (unsigned long x) { size_t i; long result = 0; i = 0; while ( i < WSIZE) {
unsigned bit = (x >> i) & 0x1; result += bit; i++; } return result; }
27
for Loop ⇒ while loop
long pcount_for (unsigned long x) { size_t i; long result = 0; for (i = 0; i < WSIZE; WSIZE; i++) { unsigned bit = (x >> i) & 0x1; result += bit; } return result; }
long pcount_for_goto_dw( unsigned long x) { size_t i; long result = 0; Init i = 0; if (!(i < WSIZE)) !Test goto done; loop: { unsigned bit = (x >> i) & 0x1; Body result += bit; } Update i++; if (i < WSIZE) Test goto loop; done: return result; }
Initial test can be optimized away 28