[Design 5] Compilers 101 for Hardware Engineers: All the Way to Verilog

The 7 phases of a compiler: preprocessing, lexical analysis, syntactic analysis, semantic analysis, IR, optimization, code generation

Written by

in

If you do RTL design or verification, you see compiler error messages several times a day. Yet when asked exactly how a "parse error" differs from a "semantic error", or what the elaboration a simulator talks about actually is, it turns out to be surprisingly hard to explain.

This post aims to help hardware engineers get comfortable with compiler terminology. It focuses on the big picture rather than deep technical detail, so some expressions may not be strictly precise.


What is a compiler?

A compiler is a program that translates code written in one language into another language. It usually means turning a high-level language into a lower-level one, and the direction sometimes gets its own name.

  • Low level → high level: decompiler
  • High level → high level: transpiler (for example Verilator, which turns SystemVerilog into C++)

The word is also used more broadly. When people say "gcc", they usually mean not just the C compiler in the narrow sense but the whole tool set, including the assembler and the linker.

Compiler in the broad sense Compiler in the narrow sense
The whole tool chain from source code to executable The program that turns source code into object code

This post uses the narrow sense. A compiler in the narrow sense usually goes through these phases.

The 7 phases of a compiler: preprocessing, lexical analysis, syntactic analysis, semantic analysis, IR, optimization, code generation
Figure 1. The phases of a compiler and the data passed between them. Everything before the IR is the front end and everything after is the back end; the symbol table is consulted throughout.
  1. Pre-processing
  2. Lexical analysis
  3. Syntactic analysis (parsing)
  4. Semantic analysis
  5. IR (Intermediate Representation) generation
  6. Code optimization
  7. Code generation

Everything before the IR is called the front end, and everything after it the back end.


Terms that are easy to mix up

Phase vs pass vs stage

Phase Pass Stage
A unit of work in the compiler (each of 1–7 above) A group of phases bounded by an IR A unit of work in optimization

Early compilers were written by one or two people with scarce computing resources, so single-pass compilers were the norm. Today, with the work split into specialized parts, multi-pass is common. The Rust compiler, for example, goes through four IRs: HIR, THIR, MIR and LLVM IR.

Stage is mostly used for optimization; think of one stage as applying one optimization technique. Each of those techniques is also called a transformation.

Object code vs IR

  • IR: a conceptual structure that holds information midway through translation. It is not tied to a particular architecture.
  • Object code: machine code, or code close enough to machine code that it assumes a specific instruction set and memory/register structure.

Even "Hello, world" in LLVM IR is still in a form people can read, as shown below.

@.str = internal constant [14 x i8] c"Hello, world\0A\00"
declare i32 @printf(ptr, ...)

define i32 @main(i32 %argc, ptr %argv) nounwind {
entry:
  %tmp1 = getelementptr [14 x i8], ptr @.str, i32 0, i32 0
  %tmp2 = call i32 (ptr, ...) @printf(ptr %tmp1) nounwind
  ret i32 0
}

An object file (for example ELF), on the other hand, contains the target machine (such as Intel 80386), sections such as .text, .data and .rodata, a symbol table, and relocation information for filling in addresses later. External functions such as printf do not have an address yet. To see this yourself, run readelf -a hello.o.

Comparing C and Java makes the positions of IR and object code clearer.

The compile flows of C and Java compared
Figure 2. C goes through IR → assembly → object code, and the linker builds the executable. Java produces only platform-independent bytecode, and each OS's JVM turns it into machine code at run time.

Compiler vs linker

Compiler Linker
Source code → object code Joins object code → executable

The linker fixes the addresses between the object code produced by the compiler (including precompiled libraries) and builds an executable in the format the operating system requires. This joining is called linking. It is also the step where the empty address of printf above gets filled in.


The compiler phases

1. Pre-processing

The preprocessor handles some of the compiler directives.

  • File inclusion (include)
  • Predefined macro substitution (e.g. __FILE__, __LINE__)
  • User-defined macro substitution (e.g. #define NULL 0)

Unlike the later phases it is plain text substitution, so it is intuitive, but when something goes wrong the cause is hard to find, and names cannot have a scope. That is why macros are best kept to a limited, global or project-wide role. The same goes for Verilog's `define; real cases where macro handling differs between tools are covered in 3 SystemVerilog portability traps: VCS vs Xcelium.

2. Lexical analysis

This phase splits a character stream into tokens, and is also called a tokenizer or scanner. A token is a pair of a piece found with regular expressions and its attribute.

logic idx = 0; split into keyword, identifier, operator, constant and symbol tokens
Figure 3. The line logic idx = 0; splits into five tokens: keyword, identifier, operator, constant and symbol. Each is a pair of a piece and its kind, as in (idx, identifier).

3. Syntactic analysis (parsing)

This phase takes the token stream and builds a parse tree (syntax tree). It establishes and checks the relationships between tokens.

Code that breaks the grammar, such as an unclosed ( or logic 0 = idx;, cannot be detected from the tokens alone; it is caught only at this phase.

The syntax tree of the SystemVerilog code nxt = idx + 1; and the formal syntax from IEEE 1800 Annex A
Figure 4. Left: the source code. Middle: the syntax tree. Right: the formal syntax (BNF) from IEEE 1800-2017 Annex A, trimmed to fit this tree. The parser follows the rules on the right to build the tree in the middle.

A language's grammar is defined like this in a format called BNF (Backus-Naur Form). The full grammar of SystemVerilog is in Annex A of IEEE 1800.

4. Semantic analysis

This is where each language's character really shows. Simply put, it is the process of checking that the syntax tree follows the language rules and extracting information about meaning.

  • Type check: argument types that do not match
  • Scope resolution: undeclared variables, variables declared twice
  • Control flow check

Code that is grammatically correct but wrong in meaning is caught here.

// arguments do not match (type check)
function magic();
...
magic(num);
// the same name declared twice (scope resolution)
logic [7:0] sth_unique;
...
wire  [7:0] sth_unique;

Finishing semantic analysis means the compiler has understood the full meaning of the code. That is why everything up to here is sometimes called the analysis phase, and everything after the synthesis phase.

Information from this phase that is passed on to later phases such as optimization, or the act of passing it, is called an annotation. Examples in C include __alignof__(double) and #pragma weak symbol. (__attribute__ is a GCC extension, while #pragma is part of the C/C++ standards.)

Syntactic analysis Semantic analysis
Deals with the code's grammar Deals with the code's context
Checks that the token stream follows the formal grammar Checks that the syntax tree follows the language rules

AST (abstract syntax tree)

A real syntax tree carries a lot of information needed for error messages and later work, such as file names, line numbers and symbol table indexes. By the dictionary definition, the AST is the tree with only the parts needed to understand meaning.

In practice, though, the term is often used interchangeably with syntax tree and attributed syntax tree. So it is more practical to think of the AST as "the result after semantic analysis, with the code's structure fully interpreted".

You can view ASTs of general programming languages in AST Explorer. For SystemVerilog, you can see one yourself with the open-source compiler slang.

# save the AST after compilation and elaboration as JSON
slang top.sv --ast-json ast.json

# to look at one hierarchy only
slang top.sv --ast-json ast.json --ast-json-scope top.u_core

Open it once to see how your RTL looks to a compiler, and the terms above become much more concrete.

Symbol table

This structure is used throughout compilation, from the moment lexical analysis starts classifying identifiers until code generation ends. It usually holds the following, with more added depending on the phase or implementation.

  • Name
  • Type
  • Scope
  • Declaration location

Think of it as an index for finding AST nodes quickly.

Analysis phases consult and update the symbol table, and each new scope creates a child table in a hierarchy
Figure 5. Top: lexical, syntactic and semantic analysis all consult and update the symbol table. Bottom: it can be implemented as a hierarchy, with a child table created whenever a new scope (module, function, begin-end block and so on) opens.

Thanks to the hierarchy, the same name in different scopes can be told apart. That is why a cnt inside a module and a cnt inside a function do not collide.

5. After semantic analysis

In textbook terms the order is IR generation → optimization → code generation. In reality, though, optimization keeps stepping in across many phases, so they are hard to separate cleanly. Machine-independent optimizations happen before machine code is generated and machine-dependent optimizations after, applied as small transformations over many stages.


Compilation and elaboration in Verilog

Now back to hardware. Section 3.12, "Compilation and elaboration" of IEEE Std 1800-2017 (SystemVerilog) separates the two like this.

  • Compilation: reading the source code (decrypting encrypted code) and checking for syntax and semantic errors
  • Elaboration: binding together the components that make up the design

What elaboration actually does is roughly:

  • Binding module definitions to module instances
  • Building the module hierarchy
  • Computing parameter values
  • Resolving hierarchical path names
  • Finalizing net connections

This split is very similar to the division of work between a C compiler and linker.

C compilation and linking compared with SystemVerilog compilation and elaboration
Figure 6. On the left, C produces object code per compilation unit and the linker combines it into an executable. On the right, SystemVerilog stores compilation results in intermediate files (Mentor style) or a library database (Synopsys/Cadence style), and elaboration ties them into a design with a module hierarchy.
Step C Verilog / SystemVerilog
1 Compiler: object code per source file Compilation: analyze each source file and build an AST per module
2 Linker: join the objects into an executable Elaboration: instantiate modules and tie them into a hierarchy to form the design

Compilation units

The parts grouped by dotted lines in Figure 6 are compilation units: sets of source files compiled together at once, covered in LRM section 3.12.1.

This matters because of things declared outside modules and packages (typedefs, functions, `define macros and so on). These declarations belong to the $unit scope of their compilation unit, and the standard lets the tool choose whether to treat each file as a separate compilation unit or all the files on one command line as one. So the same code can be visible with one tool or option and fail with "not declared" in another.

// a.sv — declaration outside a module (belongs to $unit)
typedef logic [7:0] byte_t;

// b.sv
module top;
  byte_t data;   // visible only when in the same compilation unit as a.sv
endmodule

The fix is simple. Put shared declarations in a package and import it, and it works regardless of how compilation units are handled.

How it looks in a simulator

Commercial simulators expose this split as separate commands. Running them in three steps makes it clear what each step does.

Step Synopsys VCS (3-step) Cadence Xcelium (3-step)
Compilation vlogan xmvlog
Elaboration vcs (with the top module) xmelab
Simulation ./simv xmsim

Day to day you often run VCS's 2-step (vcs → ./simv) or Xcelium's single xrun, but internally the same steps happen. When an error occurs, just seeing which step it came from (xmvlog or xmelab) narrows down the cause.

  • Compilation errors: syntax errors, type errors, undeclared identifiers
  • Elaboration errors: module not found, port connection mismatches, parameter computation errors, hierarchical path not found

So what changes?

The original purpose of an HDL is to describe a design. So passing compilation is not the end; the design is complete only when it passes elaboration too.

Parameterized modules in particular need to make good use of elaboration. You should vary how they connect to other modules and the combinations of parameters, and check that elaboration passes, because bit-width mismatches or broken generate blocks that depend on parameter values do not show up at compilation.


Summary

  • A compiler works in the order pre-processing → lexical → syntactic → semantic analysis → IR → optimization → code generation, split into front end and back end at the IR.
  • Syntax errors are caught in parsing, semantic errors in semantic analysis.
  • The AST is the fully interpreted code structure, and the symbol table is an index for finding names in it quickly by scope.
  • In Verilog, compilation corresponds to C's compiler and elaboration to its linker. A design is complete only when it passes elaboration.
  • Declarations outside modules may be invisible depending on how compilation units are handled, so put shared declarations in a package.

Further reading

Design (5 posts)

  1. The SoC Development Flow at a Glance: From Concept to Chip
  2. Getting Started with Verilog Digital Logic: Combinational Circuits, Sequential Circuits and FSMs
  3. Learning RTL Coding by Rewriting Verilog in SystemVerilog
  4. 22 SystemVerilog Coding Guidelines for Synthesis, and Why
  5. Compilers 101 for Hardware Engineers: All the Way to Verilog Reading now

See the full Tech Notes index

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *