0

I am looking for Backpatching in FOR-LOOP.

I know this approach at IF-THEN-ELSE is in this way:

IF '(' expr M ')' stmt N ELSE L stmt L
{
   backpatch($4, $9 - $4);
   backpatch($7, $11 - $7);
}

You can use these markers in your answer:

FOR '(' expr ';' L expr M N ';' L expr N ')' L stmt N L

Please explan your answer.

Mohsen
  • 11
  • 3
  • What is the software you're using for this task? Which version of yacc? Do you have the source code for the IF-THEN-ELSE version? What are the parameters of backpatch(x, y)? I assume that $N are references to your grammar symbols. Aside: why do you have "L stmt L" and not just "stmt L"? – battlmonstr May 06 '18 at 16:38
  • 2
    @battlmonstr: `L` is apparently a rule that inserts a label for branching purposes, so we need one before the else statement for the false part of the test to branch to, and one after the else for `N` to branch to. However, this entire question appears to me to be homework. – torek May 06 '18 at 17:39
  • This looks very much like a homework question. Please read "[How do I ask and answer homework questions?](https://meta.stackoverflow.com/q/334822)" and revise your question accordingly. – Johan May 07 '18 at 13:55
  • Backpatching is an assembler concept; there is no reason for it in the intermediate representation of the higher level language. Backpatching allows an instruction such as a jump to refer to a label which occurs later. The label's address is not known at the time when we assemble the jump, so we just put zeros (or whatever) for the address/offset and keep a record. Later when we see the label, and its address is assigned, we put that address back into that jump instruction: that is backpatching. – Kaz May 09 '18 at 23:49

1 Answers1

1

At FOR '(' expr1 ';' L1 expr2 ';' L2 expr3 N1 ')' L3 stmt N2 we will have this scenario:

backpatch( $14 , $8 - $14 );
backpatch( $10 , $5 - $10 ); 
backpatchlist( $6.truelist , $12 );
backpatchlist( $6.falselist , pc );
  1. First line: When we are at end of LOOP (N2), we must jump to first of Increment Section of the loop (L2) to compute expr3
  2. Second line: After computing expr3, must jump to first of Test Expression section expr2
  3. Third line: if evaluation of expr2 is true, jump to first of LOOP's Body (L3) to compute stmt.
  4. Fourth line: if evaluation of expr2 is false, processing the loop has been finished and we must jump the first instruction after LOOP which is accessible by pc.

In this condition the markers must be defined as this:

L1,L2,L3 :  { 
              $$ = pc;
            }

N1       :  {
             emit(pop);
             $$ = pc;
             emit3(goto_, 0);
            }

N2       : { 
             $$ = pc;
             emit3(goto_, 0);
           }
Mohsen
  • 11
  • 3
  • It seems that the semantic values of your grammar productions are instruction addresses? Bizarre. – Kaz May 09 '18 at 23:52