Date post: | 21-Dec-2015 |
Category: |
Documents |
View: | 228 times |
Download: | 0 times |
Lecture 14 Boolean Expressions
Lecture 14 Boolean Expressions
Topics Topics Numeric Implementation of Booleans Positional Encoding of Booleans Short Circuit Evaluation If Then else (incorrect version)
Readings: 8.4Readings: 8.4
March 1, 2006
CSCE 531 Compiler Construction
– 2 – CSCE 531 Spring 2006
OverviewOverviewLast TimeLast Time
LALR(1) Parse Table construction Handling Ambiguous Programming Language Constructs
An Expression Interpreter Generating Postfix code
Today’s Lecture Today’s Lecture Evaluations of Expressions Numeric Implementation of Booleans Positional Encoding of Booleans Short Circuit Evaluation If-then-else semantic actions almost
References: Sections 8.4References: Sections 8.4
Homework:Homework:
– 3 – CSCE 531 Spring 2006
Intermediate CodeIntermediate Code
Forms of Intermediate RepresentationsForms of Intermediate Representations
Code-like: quadruples (like postfix.y)Code-like: quadruples (like postfix.y)
Parse-tree likeParse-tree like
Lexicalanalyzer Parser Code
GeneratorSource
programObjectModule
Streamof tokens
Intermediateform
SymbolTable
Management
– 4 – CSCE 531 Spring 2006
Arithmetic ExpressionsArithmetic Expressions
E : E '+' EE : E '+' E
| E '*' E| E '*' E
| E ‘-' E| E ‘-' E
| E ‘/' E| E ‘/' E
| ‘(’ E ‘)’| ‘(’ E ‘)’
| - E| - E
| id| id
;;
Other expressionsOther expressions
E : E ‘^' EE : E ‘^' E//exponentiation//exponentiation
| id '(' Plist ')'| id '(' Plist ')' // ??// ??
| id '[' Elist ']'| id '[' Elist ']' // ??// ??
| * id| * id ////
| & id| & id ////
| id . id| id . id ////
| id | id id id ////
;;
Others ? - Bitwise and or xor, shifts, Others ? - Bitwise and or xor, shifts,
– 5 – CSCE 531 Spring 2006
Arithmetic Expressions: AttributesArithmetic Expressions: AttributesPossibilitiesPossibilities
E.place – pointer to the symbol tableE.place – pointer to the symbol table Type information Offset information for structures Scope information global/local/nested
contexts
E.code – pointer to code that will E.code – pointer to code that will evaluate the expressionevaluate the expression
E.typeE.type
We will generate “postfix” code and We will generate “postfix” code and assume E.place and install every assume E.place and install every temporary (as in Examples/PostfixCode)temporary (as in Examples/PostfixCode)
– 6 – CSCE 531 Spring 2006
Boolean Expression GrammarBoolean Expression Grammar
BoolExprBoolExpr not OrTerm | OrTerm not OrTerm | OrTerm
OrTerm OrTerm OrTerm OR AndTerm | AndTerm OrTerm OR AndTerm | AndTerm
AndTerm AndTerm AndTerm AND Bool | Bool AndTerm AND Bool | Bool
Bool Bool RelExpr | true | false RelExpr | true | false
RelExpr RelExpr E RelOp E E RelOp E
E E E + E | E * E | ( E ) | ID | NUM | … E + E | E * E | ( E ) | ID | NUM | …
– 7 – CSCE 531 Spring 2006
Numeric EncodingNumeric Encoding
True = non-zeroTrue = non-zero
False = zeroFalse = zero
ExampleExampleB OR C AND NOT DB OR C AND NOT D
QuadruplesQuadruples
NOTNOT rDrD __ T1T1
AND rCAND rC T1T1 T2T2
OROR rBrB T2T2 T3T3
– 8 – CSCE 531 Spring 2006
Numeric Encod. Extended to ComparisonsNumeric Encod. Extended to Comparisons
Comparison operations in HardwareComparison operations in Hardware IA32 -
CC register set as result of arithmetic operations
» Add, Subtract, … CMP = subtract without saving resultJumps then test certain bits in the CC register
» JLT, JLE, JEQ, JGE, JGT, JNEQSo encoding includes a lot of Jumps (x < y) AND (y < z) OR (y=x)
» Label Opcode LeftOp RightOp Target
» L0 cmp x y _
» _ JLT L2
» L1 LoadI 0 T1
» _ JMP L3
» L2 LoadI 1 _ T1
» L3 NOP
– 9 – CSCE 531 Spring 2006
Example: (x < y) AND (y < z) Example: (x < y) AND (y < z)
LabelLabel OpOp A1A1 A2A2 TargetTarget
CMPCMP XX YY __
JLTJLT L2L2
LOADILOADI 00 T1T1
JMPJMP L3L3
L2L2 LOADILOADI 11 T1T1
L3L3 CMPCMP YY ZZ __
JLTJLT L4L4
LOADILOADI 00 T2T2
JMPJMP L3L3
L4L4 LOADILOADI 11 T2T2
L5L5 ANDAND T1T1 T2T2 T3T3
– 10 – CSCE 531 Spring 2006
Positional EncodingPositional EncodingIn Positional Encoding we represent the value of an expression In Positional Encoding we represent the value of an expression
by where (the position) you end up in the codeby where (the position) you end up in the code
ExampleExample
while(k < 20) {while(k < 20) {
sum = sum + k*k;sum = sum + k*k;
k = k + 1;k = k + 1;
}}
Note in the code on the right the value Note in the code on the right the value of the boolean expr k<20 is never of the boolean expr k<20 is never explicitly represented other than in explicitly represented other than in the Condition Code Register (CC)the Condition Code Register (CC)
The value is represented by whether The value is represented by whether you end up at quad 7 or quad 3you end up at quad 7 or quad 3
QuadQuad OpOp S1S1 S2S2 TT
11 CMPICMPI kk 2020 __
22 JGEJGE ?7?7
33 MULTMULT kk kk T1T1
44 ADDADD sumsum T1T1 sumsum
55 ADDIADDI kk 11 kk
66 JMPJMP 11
77 ……
– 11 – CSCE 531 Spring 2006
Attributes for BooleansAttributes for Booleans
Consider the example on the next slideConsider the example on the next slide
As we generate the code we don’t know what the target As we generate the code we don’t know what the target branches should be.branches should be.
We need to build lists of quads whose target fields We need to build lists of quads whose target fields need to be filled in laterneed to be filled in later
B.True – list of quadruples that need to be filled in B.True – list of quadruples that need to be filled in later(backpatched) to the location that we should later(backpatched) to the location that we should branch to if this Boolean is true.branch to if this Boolean is true.
B.False - …B.False - …
– 12 – CSCE 531 Spring 2006
Example: (x < y) AND (y < z) Example: (x < y) AND (y < z)
QuadNumQuadNum OpOp A1A1 A2A2 TargetTarget
00 IF < XX YY 22
11 GOTO __ __ ??
22 IF < YY ZZ ??
33 GOTO __ __ ??
B.true
B.false 1 3
2
λ
λ
– 13 – CSCE 531 Spring 2006
Now a Boolean in an IF-ELSENow a Boolean in an IF-ELSE
programprogram
beginbegin
if x <if x < y and y < z y and y < z
then then
mid = bmid = b
else else
mid = cmid = c
endend
0 if < 0 if < x yx y 22
1 GOTO 1 GOTO _ _ __ 66
2 if < 2 if < y z y z 44
3 GOTO 3 GOTO _ _ _ _ 66
4 ASSIGN 4 ASSIGN b b _ _ midmid
5 GOTO 5 GOTO __ _ VOID_ VOID
6 ASSIGN 6 ASSIGN c c _ _ midmid
– 14 – CSCE 531 Spring 2006
Functions for Boolean AttributesFunctions for Boolean Attributes
int nextquad variable – a variable which maintain the int nextquad variable – a variable which maintain the quad number of the next quad that will be generatedquad number of the next quad that will be generated
Makelist (quad) – build a list with a single quad # on itMakelist (quad) – build a list with a single quad # on it
Merge(list1, list2) – merge two lists of quadsMerge(list1, list2) – merge two lists of quads
Backpatch(list, target) – for every quad on “list” fill in Backpatch(list, target) – for every quad on “list” fill in the branch target to “target”the branch target to “target”
– 15 – CSCE 531 Spring 2006
Quadlists Quadlists
A quadlist is just a list of intsA quadlist is just a list of ints
typedef struct node{typedef struct node{
int quadnum;int quadnum;
struct node *link;struct node *link;
} *QuadList, QuadListNode;} *QuadList, QuadListNode;
– 16 – CSCE 531 Spring 2006
Quadlists Quadlists
QuadListNode * QuadListNode *
makelist(int q)makelist(int q)
{{
QuadListNode *tmp;QuadListNode *tmp;
tmp = (QuadListNode *) malloc(sizeof (QuadListNode));tmp = (QuadListNode *) malloc(sizeof (QuadListNode));
tmp -> quadnum = q;tmp -> quadnum = q;
return(tmp);return(tmp);
}}
– 17 – CSCE 531 Spring 2006
BackpatchBackpatch
voidvoid
backpatch(QuadList p, int q)backpatch(QuadList p, int q)
{{
while (p != NULL){while (p != NULL){
target[p->quadnum] = (QuadListNode *) q;target[p->quadnum] = (QuadListNode *) q;
p = p -> link;p = p -> link;
}}
}}
– 18 – CSCE 531 Spring 2006
Dumplist – A Debugging Support Routine Dumplist – A Debugging Support Routine
voidvoid
dumplist(char *label, LIST p)dumplist(char *label, LIST p)
{{
printf("\nDUMPLIST %s", label);printf("\nDUMPLIST %s", label);
while (p != NULL){while (p != NULL){
printf(" %d ",p->quadnum);printf(" %d ",p->quadnum);
p = p -> link;p = p -> link;
}}
}}
– 19 – CSCE 531 Spring 2006
Stack types – Multiple Type Attributes Stack types – Multiple Type Attributes
%union{%union{
struct nlist *place;struct nlist *place;
struct {struct {
QuadListNode *true;QuadListNode *true;
QuadListNode *false;QuadListNode *false;
} quadlist;} quadlist;
int quad;int quad;
int type;int type;
LIST next;LIST next;
}}
– 20 – CSCE 531 Spring 2006
Stack types – Multiple Type Attributes II Stack types – Multiple Type Attributes II
%type <place> expr%type <place> expr
%type <list> B%type <list> B
%type <quad> M%type <quad> M
%type <next> N%type <next> N
%type <next> L%type <next> L
%type <next> S%type <next> S
%token <place> ID%token <place> ID
%token <type> RELOP%token <type> RELOP
– 21 – CSCE 531 Spring 2006
Intermediate Code Generation Intermediate Code Generation
QuadruplesQuadruples OPCODE LeftOperand RightOperand Result ADD “x” “y” “z” GOTO quadnumber What are the type of these?
Quadruples – implemented as 5 parallel arraysQuadruples – implemented as 5 parallel arrays int opcode[CODESIZE]; struct nlist *left[CODESIZE]; struct nlist *right[CODESIZE]; struct nlist *result[CODESIZE]; int branchTarget[CODESIZE];
We could use a union and merge result and We could use a union and merge result and branchTarget, but this just over complicates issues.branchTarget, but this just over complicates issues.
– 22 – CSCE 531 Spring 2006
Intermediate Code Generation Intermediate Code Generation
voidvoid
gen(int op, struct nlist *p1, struct nlist *p2, struct nlist *r, int t)gen(int op, struct nlist *p1, struct nlist *p2, struct nlist *r, int t)
{{
opcode[nextquad] = op;opcode[nextquad] = op;
op1[nextquad] = p1;op1[nextquad] = p1;
op2[nextquad] = p2;op2[nextquad] = p2;
result[nextquad] = r;result[nextquad] = r;
branchTarget[nextquad] = t;branchTarget[nextquad] = t;
nextquad = nextquad + 1;nextquad = nextquad + 1;
}}
– 23 – CSCE 531 Spring 2006
Semantic Actions for B ID RELOP IDSemantic Actions for B ID RELOP ID
B: ID RELOP ID {B: ID RELOP ID {
gen($2, $1, $3, NULL, VOID);gen($2, $1, $3, NULL, VOID);
gen(GOTO, NULL,NULL,NULL,VOID);gen(GOTO, NULL,NULL,NULL,VOID);
$$.true = makelist(nextquad -2);$$.true = makelist(nextquad -2);
$$.false = makelist(nextquad - 1);$$.false = makelist(nextquad - 1);
}}
;;
– 24 – CSCE 531 Spring 2006
MarkersMarkers
Markers are typically nonterminals that derive Markers are typically nonterminals that derive εε that are that are inserted to insure an action is performed at a given inserted to insure an action is performed at a given time.time.
A common thing need is to remember the quad number A common thing need is to remember the quad number where something starts, so the attribute of a marker where something starts, so the attribute of a marker is just the next quad number.is just the next quad number.
M M εε { M.quad = nextquad; }{ M.quad = nextquad; }
So instead ofSo instead of
S S if B then S else S if B then S else S
We useWe use
S S if B then M if B then M11 S else M S else M22 S S ***Almost***Almost
– 25 – CSCE 531 Spring 2006
Semantic Actions for B B AND M B Semantic Actions for B B AND M B
B B B AND M B { B AND M B {
backpatch($1.true,$3);backpatch($1.true,$3);
$$.true = $4.true;$$.true = $4.true;
$$.false = merge($1.false,$4.false);$$.false = merge($1.false,$4.false);
}}
– 26 – CSCE 531 Spring 2006
Semantic Actions for B B OR M BSemantic Actions for B B OR M B
B B B OR M B { B OR M B {
backpatch($1.false,$3);backpatch($1.false,$3);
$$.false = $4.false;$$.false = $4.false;
$$.true = merge($1.true, $4.true);$$.true = merge($1.true, $4.true);
}}
– 27 – CSCE 531 Spring 2006
Semantic Actions for S if B then M S else M S ***Almost Semantic Actions for S if B then M S else M S ***Almost
S: IF B THEN M S N ELSE M S {S: IF B THEN M S N ELSE M S {
backpatch($2.true, $4);backpatch($2.true, $4);
backpatch($2.false, $8);backpatch($2.false, $8);
tmplist = merge($5, $6);tmplist = merge($5, $6);
$$ = merge(tmplist, $9);$$ = merge(tmplist, $9);
}}
;;
Why almost?Why almost?
– 28 – CSCE 531 Spring 2006
Semantic Actions for Assignments Semantic Actions for Assignments
S: ID ASSIGNOP expr {S: ID ASSIGNOP expr {
gen(ASSIGNOP, $<place>3, NULL, $1, VOID);gen(ASSIGNOP, $<place>3, NULL, $1, VOID);
$$ = NULL;$$ = NULL;
}}
||
– 29 – CSCE 531 Spring 2006
Semantic Actions for Markers Semantic Actions for Markers
M: {$$ = nextquad;}M: {$$ = nextquad;}
;;
– 30 – CSCE 531 Spring 2006
Project 3 – Generating Postfix Code for Expressions Project 3 – Generating Postfix Code for Expressions
ExpressionsExpressions
BooleansBooleans
If B then assign else assignIf B then assign else assign
Undeclared variables print error message including line Undeclared variables print error message including line numbernumber
Mixed mode expressions (Graduate students only) Mixed mode expressions (Graduate students only) Extra credit for ugradsExtra credit for ugrads int k; float f; k + f (float)k + f Code toFloat k _ t1 addf t1 f t2
Write up in the email soonWrite up in the email soon
– 31 – CSCE 531 Spring 2006
Debugging Parsers written with YaccDebugging Parsers written with Yacc
1.1. Debug the grammarDebug the grammar1. Rewrite grammar to eliminate reduce/reduce and as many
shift/reduce as you can.
2. Tracing parses using –t option to bison or yacc -DYYDEBUG compile option int yydebug=1; in bison specification (C definitions section %{ ..%} extern int yydebug; in lex specification
2.2. Debug the semantic actionsDebug the semantic actions Compile with –g option; set CFLAGS=-g in Makefile and use
gcc $(CFLAGS) … as the compile (or rely on the builtin rules)
Use gdb (Gnu debugger) to debug the program
– 32 – CSCE 531 Spring 2006
Common MistakesCommon Mistakes
Segmentation fault - This means you have Segmentation fault - This means you have referenced a memory location that is outside of the referenced a memory location that is outside of the memory segment of your program.memory segment of your program. You have a pointer that has a bad value! First make sure everytime you copy a string value you use
strdup. Several people have had errors with strcat(s,t) where they did not allocate space for the string “s”.
Use gdb and bt (backtrace) to trace down the pointer with the bad value
– 33 – CSCE 531 Spring 2006
GDB - Essential CommandsGDB - Essential Commands
gdb program [core] - debug program gdb program [core] - debug program [using coredump core][using coredump core]
b [file:] function b [file:] function set breakpoint at function [in file]set breakpoint at function [in file]
run [arglist] run [arglist] start your program [with arglist]start your program [with arglist]
bt backtrace: bt backtrace: display program stackdisplay program stack
p expr p expr display the value of an expressiondisplay the value of an expression
c c continue running your programcontinue running your program
n n next line, stepping over function callsnext line, stepping over function calls
s s next line, stepping into function callsnext line, stepping into function calls
– 34 – CSCE 531 Spring 2006
Example using gdbExample using gdb
deneb> makedeneb> make
bison -d decaf.ybison -d decaf.y
decaf.y contains 51 shift/reduce conflicts.decaf.y contains 51 shift/reduce conflicts.
gcc -c -g decaf.tab.cgcc -c -g decaf.tab.c
flex decaf.lflex decaf.l
gcc -DYYDEBUG -g -c lex.yy.cgcc -DYYDEBUG -g -c lex.yy.c
gcc -c -g tree.cgcc -c -g tree.c
gcc -DYYDEBUG -g decaf.tab.o lex.yy.o tree.o -ly -o decafgcc -DYYDEBUG -g decaf.tab.o lex.yy.o tree.o -ly -o decaf
deneb> ./decaf < t1deneb> ./decaf < t1
Keyword intKeyword int
Segmentation Fault (core dumped) Segmentation Fault (core dumped) !!! !!!
– 35 – CSCE 531 Spring 2006
Example using gdbExample using gdb
deneb> makedeneb> make
bison -d decaf.ybison -d decaf.y
decaf.y contains 51 shift/reduce conflicts.decaf.y contains 51 shift/reduce conflicts.
gcc -c -g decaf.tab.cgcc -c -g decaf.tab.c
flex decaf.lflex decaf.l
gcc -DYYDEBUG -g -c lex.yy.cgcc -DYYDEBUG -g -c lex.yy.c
gcc -c -g tree.cgcc -c -g tree.c
gcc -DYYDEBUG -g decaf.tab.o lex.yy.o tree.o -ly -o decafgcc -DYYDEBUG -g decaf.tab.o lex.yy.o tree.o -ly -o decaf
deneb> ./decaf < t1deneb> ./decaf < t1
Keyword intKeyword int
Segmentation Fault (core dumped)Segmentation Fault (core dumped)
Note the use of the –g option (CFLAGS=-g in Makefile