Skip to content

floriandotorg/mini-llvm

Repository files navigation

mini-llvm

A proof-of-concept minimal LLVM-like compiler that generates an Intermediate Representation (IR) and supports the addition of multiple frontends and backends.

Architecture

┌─────────────┐     ┌─────────────┐     ┌─────────────┐
│  Frontend   │────▶│     IR      │────▶│   Backend   │
│   (C, ...)  │     │ (optimized) │     │ (aarch64,...│
└─────────────┘     └─────────────┘     └─────────────┘

The compiler follows the classic three-phase design:

  1. Frontend: Parses source code and generates IR
  2. IR: A typed intermediate representation with optimization passes
  3. Backend: Converts IR to target-specific assembly

Currently Supported

Frontends Backends
C aarch64

IR Example

The IR uses an LLVM-inspired syntax:

define i32 @main() {
  %0 = alloca i32
  %1 = add i32 1, 3
  store i32 %1, ptr %0
  %2 = load i32, ptr %0
  %3 = add i32 3, 4
  %4 = mul i32 %3, %2
  %5 = add i32 %4, 1
  ret i32 %5
}

Installation

npm install

Usage

npm start <source-file> <target-file> -s <source-language> -t <target-arch>

Options

Option Description Values
-s, --source Source language c
-t, --target Target architecture aarch64

Example

Compile a C file to aarch64 assembly:

npm start test1.c output.asm -s c -t aarch64

Running the Output (macOS aarch64)

clang -arch arm64 -o output output.asm
./output
echo $?  # prints the return value

Development

npm test          # run tests
npm check         # type check
npm lint          # lint

Adding a New Frontend

Create a new directory under frontend/ and implement:

  1. Tokenizer
  2. Parser (AST generation)
  3. Processor (AST processing)
  4. Codegen (AST → IR)

Then add the language option in index.ts.

Adding a New Backend

Create a new directory under backend/ and implement a codegen function that converts IntermediateFunction[] to assembly string.

Then add the architecture option in index.ts.

About

A proof-of-concept minimal LLVM-like compiler that generates an Intermediate Representation (IR) and supports the addition of multiple frontends and backends.

Topics

Resources

Stars

Watchers

Forks

Contributors