Search code examples
compilationcompiler-construction

What compiler technology does jump label analysis and generation?


I am working on a small compiler project which involves generating a jump label in the final code.

I am not sure what particular compiler technology, the problems belongs to and so, I am not even sure how to google references.

Hope you could point me a direction.

Here is the code to be compiled:

goto A

-- some optional code
-- may be here

A: if (2 > 1)
       print Y
   else
       print N

My input is AST of the above code:

Node if, label A
   child1 condition
      child11 expr 2 > 1
   child2 body
      child21 print Y
   child3 else
      child31 print N

The problem is, I need to propagate "label A" from "Node if" to "child11", before I the code generation phase.

I was thinking this is part of Static Single Assignment, SSA, analysis and transformation, after reading a lecture note, I do not see it.

Hope you can help out.


Solution

  • Quick Short Answer

    Lookup for "intermediate code" generation phase, first. Some compilers doesn't use it, and don't documented. You will need it to implement "goto".

    Long Extended Answer

    The goto, label statements, are transformed in the code generation step, after the generation of the A.S.T.

    Remember, that there are several techniques to built a compiler, or interpreter, and may vary from one project to another.

    In this particular case, after the A.S.T., is built, an structure called "intermediate code", is built from the A.S.T.

    Usually, is a list of simple instructions, with a single operation, and a few parameters.

    (97) goto 100
    (98) do something
    (99) do something
    (100) ifgreater 2, 1
    (101) then print n
    (102) else print y
    

    Many code lines can be transform from the AST, to final code, "goto" doesn't.

    If a label is declared after the "goto", you need to generate the "goto" as "goto temp1", as an intermediate instruction, generate the following lines, included where the label is declared.

    (97) goto temp1
    (98) do something
    (99) do something
    (100) ifgreater 2, 1
    (101) then print n
    (102) else print y
    

    And later, return to replace the "temp1" with the real line number.

    (97) goto 100
    (98) do something
    (99) do something
    (100) ifgreater 2, 1
    (101) then print n
    (102) else print y
    

    And, later, transform this intermediate code into final (object) code.