Boolean Expression in Compiler Design

Boolean Expression

The translation of conditional statements such as if-else statements and while-do statements is associated with Boolean expression's translation. The main use of the Boolean expression is the following:

  • Boolean expressions are used as conditional expressions in statements that alter the flow of control.
  • A Boolean expression can compute logical values, true or false.

Boolean expression is composed of Boolean operators like &&, ||, !, etc. applied to the elements that are Boolean or relational expressions. E1 rel E2 is the form of relational expressions.

Let us consider the following grammars:

B => B1 | | B2

B => B1 && B2 |

B => !B1

B => (B)

B => E1 rel E2

B => true

B => false

If we compute that B1 is true in the first expression, then the entire expression will be true. We don’t need to compute B2. In the second expression, if B1 is false, then the entire expression is false.

The comparison operators <, <=, =, !=, >, or => is represented by rel.op.

We also assume that || and && are left-associative. || has the lowest precedence and then &&, and !.

PRODUCTIONSEMANTIC R RULES
B => B1 | | B2B1.true = B.true B1.false = newlabel () B2.true = B.true B2.false = B.false B.code = B1.code || label(B1.false) ||    B2.code
B => B1 && B2B1.true = newlabel () B1.false = B.false B2.true = B.true B2.false = B.false        B.code = B1.code | | label( B1.true) | |    B2.code  
B => !B1B1.true = B.false B1.false = B.true B.code = B1.code
B =>  E1 rel E2B.code = E1.code | | E2.code | | gen(‘if’ E1.addr rel.op E2.addr         ‘goto’ B.true) | | gen(‘goto’ B.false)
B => trueB.code = gen(‘goto’ B.true )
B => falseB.code = gen(‘goto’ B.false )

The below example can generate the three address code using the above translation scheme:

if ( x < 100 || x > 200 && x ! = y ) x = 0;

           if x < 100 goto L2

           goto L3                

L3:     if x > 200 goto L4

          goto L1                 

L4:     if x != y goto L 2 

           goto L1               

L2:     x = 0                     

L1: