Which of the following is the CORRECT sequence of the phases of a compiler?
2023
Which of the following is the CORRECT sequence of the phases of a compiler?
Answer: D. Lexical analysis, syntax analysis, intermediate code generation, code optimization, code generation — Concept: A compiler transforms source code into target code through a fixed pipeline in which each phase consumes the previous phase's output: lexical…
- A.
Lexical analysis, syntax analysis, intermediate code generation, code generation, code optimization
- B.
Lexical analysis, intermediate code generation, syntax analysis, code generation, code optimization
- C.
Lexical analysis, intermediate code generation, syntax analysis, code optimization, code generation
- D.
Lexical analysis, syntax analysis, intermediate code generation, code optimization, code generation
Attempted by 368 students.
Show answer & explanation
Correct answer: D
Concept: A compiler transforms source code into target code through a fixed pipeline in which each phase consumes the previous phase's output: lexical analysis (characters -> tokens), syntax analysis (tokens -> parse tree), semantic analysis (type/scope checking), intermediate code generation (parse tree -> intermediate representation), code optimization (improves that intermediate representation), and code generation (intermediate representation -> target code).
Application: Trace the five phases named in this item through that dependency chain:
Lexical analysis must run first, since it is the only one of these phases that reads raw source characters.
Syntax analysis runs next, because it needs the token stream that lexical analysis produces.
Intermediate code generation runs after syntax analysis, since it needs a validated parse tree as its input.
Code optimization runs after intermediate code generation, because it improves the intermediate representation that phase produces.
Code generation runs last, emitting target code from the optimized intermediate form.
So the order among these five phases is: lexical analysis, syntax analysis, intermediate code generation, code optimization, code generation.
Cross-check: Reading the dependencies backward confirms it: code generation needs the optimized intermediate code, which needs the unoptimized intermediate code from intermediate code generation, which needs the parse tree from syntax analysis, which needs the tokens from lexical analysis -- a clean chain with no phase used before its input exists. (Semantic analysis, which normally sits between syntax analysis and intermediate code generation, is not among the phases listed in these options.)