项目 / banach-space/llvm-tutor

banach-space/llvm-tutor

行业候选
语言 C++标签 llvm-passllvm-tutorllvm-irllvm-tutorialllvm-pluginscompilersllvmtutorial数据更新 2026-11-24 06:50:13 · 仓库 2026-11-23

一段话介绍

面向 LLVM 入门开发者的参考教程,提供一组可独立构建和测试的 LLVM 通道示例,当前基于 LLVM 23。它在树外针对已安装的 LLVM 二进制构建,不必从源码编译整个 LLVM,并附带 CMake 脚本、LIT 测试和说明。源文件中有实现注释,示例还配有参考输入。

本站整理,非 GitHub 官方 description。

官方 description(GitHub API 原样)
A collection of out-of-tree LLVM passes for teaching and learning
3,457累计星
452Fork
—峰值日增
0上榜次数
总榜
暂未入榜
日榜
暂未入榜
周榜
暂未入榜
月榜
暂未入榜

官方快照(gh_history.db,2026-11-25):总榜 未进 Top50 · 日榜 未进 Top50 · 周榜未满 7 天基线(官方不生成) · 月榜暂无官方口径;下方四卡为站内趋势聚合(周卡按上榜次数,非官方 7 日增量窗)。

行业与场景 教育 暂无可用场景

更多信息

以下三段按该项目自己的 GitHub README 章节摘录(可合理截断并标明);README 没有对应章节的留空,不编造。

我的用法
可运行 pip install lit。
特点或设计要点
项目说明文档见 https://github.com/banach-space/llvm-tutor/blob/main/inputs。
局限和适用边界
该项目在 Ubuntu 23.04 和 Mac OS X 11.7 测试,构建需 LLVM 23、支持 C++17 的编译器与 CMake 3.20+,运行需 clang-23 和 opt。
星标走势还差一天的数据,明天就能看到曲线
每天 10:30 记一次星标,连续两天后自动生成曲线
首次发现 — · 最近在榜 2026-11-12 · 语言 C++ · 贡献者 —
c++

GitHub 项目主页介绍

来自 GitHub 仓库 README / 主页介绍正文,正文较长,已截断:保留前 20000 字符(原始 54,779 字节),完整内容见 GitHub 仓库。

llvm-tutor
=========
[![Apple Silicon](https://github.com/banach-space/llvm-tutor/actions/workflows/apple-silicon.yml/badge.svg?branch=main)](https://github.com/banach-space/llvm-tutor/actions/workflows/apple-silicon.yml)
[![x86-Ubuntu](https://github.com/banach-space/llvm-tutor/actions/workflows/x86-ubuntu.yml/badge.svg?branch=main)](https://github.com/banach-space/llvm-tutor/actions/workflows/x86-ubuntu.yml)


Example LLVM passes - based on **LLVM 23**

**llvm-tutor** is a collection of self-contained reference LLVM passes. It's a
tutorial that targets novice and aspiring LLVM developers. Key features:

* **Out-of-tree** - builds against a binary LLVM installation (no need to build LLVM from sources)
* **Complete** - includes `CMake` build scripts, LIT tests, CI set-up and documentation
* **Modern** - based on the latest version of LLVM (and updated with every release)

### Overview
LLVM implements a very rich, powerful and popular API. However, like many
complex technologies, it can be quite daunting and overwhelming to learn and
master. The goal of this LLVM tutorial is to showcase that LLVM can in fact be
easy and fun to work with. This is demonstrated through a range of self-contained,
testable LLVM passes, which are implemented using idiomatic LLVM.

This document explains how to set-up your environment, build and run the
examples, and go about debugging. It contains a high-level overview of the
implemented examples and contains some background information on writing LLVM
passes. The source files, apart from the code itself, contain comments that
will guide you through the implementation. All examples are complemented with
[LIT](https://llvm.org/docs/TestingGuide.html) tests and reference [input
files](https://github.com/banach-space/llvm-tutor/blob/main/inputs).

Visit [**clang-tutor**](https://github.com/banach-space/clang-tutor/) if you
are interested in similar tutorial for Clang.

### Table of Contents
* [HelloWorld: Your First Pass](#helloworld-your-first-pass)
* Part 1: **llvm-tutor** in more detail
  * [Development Environment](#development-environment)
  * [Building & Testing](#building--testing)
  * [Overview of the Passes](#overview-of-the-passes)
  * [Debugging](#debugging)
* Part 2: Passes In LLVM
  * [Analysis vs Transformation Pass](#analysis-vs-transformation-pass)
  * [Dynamic vs Static Plugins](#dynamic-vs-static-plugins)
  * [Optimisation Passes Inside LLVM](#optimisation-passes-inside-llvm)
  * [Optimisation Passes Inside LLVM](#optimisation-passes-inside-llvm)
* [Contributing](#contributing)
* [References](#references)


HelloWorld: Your First Pass
===========================
The **HelloWorld** pass from
[HelloWorld.cpp](https://github.com/banach-space/llvm-tutor/blob/main/HelloWorld/HelloWorld.cpp)
is a self-contained *reference example*. The corresponding
[CMakeLists.txt](https://github.com/banach-space/llvm-tutor/blob/main/HelloWorld/CMakeLists.txt)
implements the minimum set-up for an out-of-source pass.

For every function defined in the input module, **HelloWorld** prints its name
and the number of arguments that it takes. You can build it like this:

```bash
export LLVM_DIR=<installation/dir/of/llvm/23>
mkdir build
cd build
cmake -DLT_LLVM_INSTALL_DIR=$LLVM_DIR <source/dir/llvm/tutor>/HelloWorld/
make
```

Before you can test it, you need to prepare an input file:

```bash
# Generate an LLVM test file
$LLVM_DIR/bin/clang -O1 -S -emit-llvm <source/dir/llvm/tutor>/inputs/input_for_hello.c -o input_for_hello.ll
```

Finally, run **HelloWorld** with
[**opt**](http://llvm.org/docs/CommandGuide/opt.html) (use `libHelloWorld.so`
on Linux and `libHelloWorld.dylib` on Mac OS):

```bash
# Run the pass
$LLVM_DIR/bin/opt -load-pass-plugin ./libHelloWorld.{so|dylib} -passes=hello-world -disable-output input_for_hello.ll
# Expected output
(llvm-tutor) Hello from: foo
(llvm-tutor)   number of arguments: 1
(llvm-tutor) Hello from: bar
(llvm-tutor)   number of arguments: 2
(llvm-tutor) Hello from: fez
(llvm-tutor)   number of arguments: 3
(llvm-tutor) Hello from: main
(llvm-tutor)   number of arguments: 2
```

The **HelloWorld** pass doesn't modify the input module. The `-disable-output`
flag is used to prevent **opt** from printing the output bitcode file.

Development Environment
=======================
## Platform Support And Requirements
This project has been tested on **Ubuntu 23.04** and **Mac OS X 11.7**. In
order to build **llvm-tutor** you will need:
  * LLVM 23
  * C++ compiler that supports C++17
  * CMake 3.20 or higher

In order to run the passes, you will need:
  * **clang-23** (to generate input LLVM files)
  * [**opt**](http://llvm.org/docs/CommandGuide/opt.html) (to run the passes)

There are additional requirements for tests (these will be satisfied by
installing LLVM 23):
  * [**lit**](https://llvm.org/docs/CommandGuide/lit.html) (aka **llvm-lit**,
    LLVM tool for executing the tests)
  * [**FileCheck**](https://llvm.org/docs/CommandGuide/FileCheck.html) (LIT
    requirement, it's used to check whether tests generate the expected output)

## Installing LLVM 23 on Mac OS X
On Darwin you can install LLVM 23 with [Homebrew](https://brew.sh/):

```bash
brew install llvm@23
```

If you already have an older version of LLVM installed, you can upgrade it to
LLVM 23 like this:

```bash
brew upgrade llvm
```

Once the installation (or upgrade) is complete, all the required header files,
libraries and tools will be located in `/opt/homebrew/opt/llvm/`.

## Installing LLVM 23 on Ubuntu
On Ubuntu Jammy Jellyfish, you can install modern LLVM from the official
[repository](http://apt.llvm.org/):

```bash
wget -O - https://apt.llvm.org/llvm-snapshot.gpg.key | sudo apt-key add -
sudo apt-add-repository "deb http://apt.llvm.org/jammy/ llvm-toolchain-jammy-23 main"
sudo apt-get update
sudo apt-get install -y llvm-23 llvm-23-dev llvm-23-tools clang-23
```
This will install all the required header files, libraries and tools in
`/usr/lib/llvm-23/`.

## Building LLVM 23 From Sources
Building from sources can be slow and tricky to debug. It is not necessary, but
might be your preferred way of obtaining LLVM 23. The following steps will work
on Linux and Mac OS X:

```bash
git clone https://github.com/llvm/llvm-project.git
cd llvm-project
git checkout release/23.x
mkdir build
cd build
cmake -DCMAKE_BUILD_TYPE=Release -DLLVM_TARGETS_TO_BUILD=host -DLLVM_ENABLE_PROJECTS=clang <llvm-project/root/dir>/llvm/
cmake --build .
```
For more details read the [official
documentation](https://llvm.org/docs/CMake.html).

Building & Testing
===================
## Building
You can build **llvm-tutor** (and all the provided pass plugins) as follows:

```bash
cd <build/dir>
cmake -DLT_LLVM_INSTALL_DIR=<installation/dir/of/llvm/23> <source/dir/llvm/tutor>
make
```

The `LT_LLVM_INSTALL_DIR` variable should be set to the root of either the
installation or build directory of LLVM 23. It is used to locate the
corresponding `LLVMConfig.cmake` script that is used to set the include and
library paths.

## Testing
In order to run **llvm-tutor** tests, you need to install **llvm-lit** (aka
**lit**). It's not bundled with LLVM 23 packages, but you can install it with
**pip**:

```bash
# Install lit - note that this installs lit globally
pip install lit
```
Running the tests is as simple as:

```bash
$ lit <build_dir>/test
```
Voilà! You should see all tests passing.

## LLVM Plugins as shared objects
In **llvm-tutor** every LLVM pass is implemented in a separate shared object
(you can learn more about shared objects
[here](http://www.yolinux.com/TUTORIALS/LibraryArchives-StaticAndDynamic.html)).
These shared objects are essentially dynamically loadable plugins for **opt**.
All plugins are built in the `<build/dir>/lib` directory.

Note that the extension of dynamically loaded shared objects differs between
Linux and Mac OS. For example, for the **HelloWorld** pass you will get:

* `libHelloWorld.so` on Linux
* `libHelloWorld.dylib` on MacOS.

For the sake of consistency, in this README.md file all examples use the `*.so`
extension. When working on Mac OS, use `*.dylib` instead.

Overview of The Passes
======================
The available passes are categorised as either Analysis, Transformation or CFG.
The difference between Analysis and Transformation passes is rather
self-explanatory ([here](#analysis-vs-transformation-pass) is a more technical
breakdown). A CFG pass is simply a Transformation pass that modifies the Control
Flow Graph. This is frequently a bit more complex and requires some extra bookkeeping,
hence a dedicated category.

In the following table the passes are grouped thematically and ordered by the
level of complexity.

| Name      | Description     | Category |
|-----------|-----------------|------|
|[**HelloWorld**](#helloworld-your-first-pass) | visits all functions and prints their names | Analysis |
|[**OpcodeCounter**](#opcodecounter) | prints a summary of LLVM IR opcodes in the input module | Analysis |
|[**InjectFuncCall**](#injectfunccall) | instruments the input module by inserting calls to `printf` | Transformation |
|[**StaticCallCounter**](#staticcallcounter) | counts direct function calls at compile-time (static analysis) | Analysis |
|[**DynamicCallCounter**](#dynamiccallcounter) | counts direct function calls at run-time (dynamic analysis) | Transformation |
|[**MBASub**](#mbasub) | obfuscate integer `sub` instructions | Transformation |
|[**MBAAdd**](#mbaadd) | obfuscate 8-bit integer `add` instructions | Transformation |
|[**FindFCmpEq**](#findfcmpeq) | finds floating-point equality comparisons | Analysis |
|[**ConvertFCmpEq**](#convertfcmpeq) | converts direct floating-point equality comparisons to difference comparisons | Transformation |
|[**RIV**](#riv) | finds reachable integer values for each basic block | Analysis |
|[**DuplicateBB**](#duplicatebb) | duplicates basic blocks, requires **RIV** analysis results | CFG |
|[**MergeBB**](#mergebb) | merges duplicated basic blocks | CFG |

Once you've [built](#building--testing) this project, you can experiment with
every pass separately. All passes, except for
[**HelloWorld**](#helloworld-your-first-pass), are described in more details
below.

LLVM passes work with LLVM IR files. You can generate one like this:

```bash
export LLVM_DIR=<installation/dir/of/llvm/23>
# Textual form
$LLVM_DIR/bin/clang -O1 -emit-llvm input.c -S -o out.ll
# Binary/bit-code form
$LLVM_DIR/bin/clang -O1 -emit-llvm input.c -c -o out.bc
```
It doesn't matter whether you choose the binary, `*.bc` (default), or
textual/LLVM assembly form (`.ll`, requires the `-S` flag). Obviously, the
latter is more human-readable. Similar logic applies to **opt** - by default it
generates `*.bc` files. You can use `-S` to have the output written as `*.ll`
files instead.

Note that `clang` adds the `optnone` [function
attribute](https://llvm.org/docs/LangRef.html#function-attributes) if either

* no optimization level is specified, or
* `-O0` is specified.

If you want to compile at `-O0`, you need to specify `-O0 -Xclang
-disable-O0-optnone` or define a static
[isRequired](https://llvm.org/docs/WritingAnLLVMNewPMPass.html#required-passes)
method in your pass.  Alternatively, you can specify `-O1` or higher.
Otherwise the new pass manager will register the pass but your pass will not be
executed.

As noted [earlier](#llvm-plugins-as-shared-objecs), all examples in this file
use the `*.so` extension for pass plugins. When working on Mac OS, use
`*.dylib` instead.

## OpcodeCounter
**OpcodeCounter** is an Analysis pass that prints a summary of the [LLVM IR
opcodes](https://github.com/llvm/llvm-project/blob/release/23.x/llvm/lib/IR/Instruction.cpp#L397-L480)
encountered in every function in the input module. This pass can be [run
automatically](#auto-registration-with-optimisation-pipelines) with one of the
pre-defined optimisation pipelines. However, let's use our tried and tested method
first.

### Run the pass
We will use
[input_for_cc.c](https://github.com/banach-space/llvm-tutor/blob/main/inputs/input_for_cc.c)
to test **OpcodeCounter**. Since **OpcodeCounter** is an Analysis pass, we want
**opt** to _print_ its results. To this end, we will use a [printing
pass](#printing-passes-for-the-new-pass-manager) that corresponds to
**OpcodeCounter**. This pass is called `print<opcode-counter>`. No extra
arguments are needed, but it's a good idea to add `-disable-output` to prevent
**opt** from printing the output LLVM IR module - we are only interested in the
results of the analysis rather than the module itself. In fact, as this pass
does not modify the input IR, the output module would be identical to the
input anyway.

```bash
export LLVM_DIR=<installation/dir/of/llvm/23>
# Generate an LLVM file to analyze
$LLVM_DIR/bin/clang -emit-llvm -c <source_dir>/inputs/input_for_cc.c -o input_for_cc.bc
# Run the pass through opt
$LLVM_DIR/bin/opt -load-pass-plugin <build_dir>/lib/libOpcodeCounter.so --passes="print<opcode-counter>" -disable-output input_for_cc.bc
```

For `main`, **OpcodeCounter** prints the following summary (note that when running the pass,
a summary for other functions defined in `input_for_cc.bc` is also printed):

```
=================================================
LLVM-TUTOR: OpcodeCounter results for `main`
=================================================
OPCODE               #N TIMES USED
-------------------------------------------------
load                 2
br                   4
icmp                 1
add                  1
ret                  1
alloca               2
store                4
call                 4
-------------------------------------------------
```

### Auto-registration with optimisation pipelines
You can run **OpcodeCounter** by simply specifying an optimisation level (e.g.
`-O{1|2|3|s}`). This is achieved through auto-registration with the existing
optimisation pass pipelines. Note that you still have to specify the plugin
file to be loaded:

```bash
$LLVM_DIR/bin/opt -load-pass-plugin <build_dir>/lib/libOpcodeCounter.so --passes='default<O1>' input_for_cc.bc
```

This is implemented in
[OpcodeCounter.cpp](https://github.com/banach-space/llvm-tutor/blob/main/lib/OpcodeCounter.cpp),
on
[line 106](https://github.com/banach-space/llvm-tutor/blob/main/lib/OpcodeCounter.cpp#L106-L110).

## InjectFuncCall
This pass is a _HelloWorld_ example for _code instrumentation_. For every function
defined in the input module, **InjectFuncCall** will add (_inject_) the following
call to [`printf`](https://en.cppreference.com/w/cpp/io/c/fprintf):

```C
printf("(llvm-tutor) Hello from: %s\n(llvm-tutor)   number of arguments: %d\n", FuncName, FuncNumArgs)
```
This call is added at the beginning of each function (i.e. before any other
instruction). `FuncName` is the name of the function and `FuncNumArgs` is the
number of arguments that the function takes.

### Run the pass
We will use
[input_for_hello.c](https://github.com/banach-space/llvm-tutor/blob/main/inputs/input_for_hello.c)
to test **InjectFuncCall**:

```bash
export LLVM_DIR=<installation/dir/of/llvm/23>
# Generate an LLVM file to analyze
$LLVM_DIR/bin/clang -O0 -emit-llvm -c <source_dir>/inputs/input_for_hello.c -o input_for_hello.bc
# Run the pass through opt
$LLVM_DIR/bin/opt -load-pass-plugin <build_dir>/lib/libInjectFuncCall.so --passes="inject-func-call" input_for_hello.bc -o instrumented.bin
```
This generates `instrumented.bin`, which is the instrumented version of
`input_for_hello.bc`. In order to verify that **InjectFuncCall** worked as
expected, you can either check the output file (and verify that it contains
extra calls to `printf`) or run it:

```
$LLVM_DIR/bin/lli instrumented.bin
(llvm-tutor) Hello from: main
(llvm-tutor)   number of arguments: 2
(llvm-tutor) Hello from: foo
(llvm-tutor)   number of arguments: 1
(llvm-tutor) Hello from: bar
(llvm-tutor)   number of arguments: 2
(llvm-tutor) Hello from: foo
(llvm-tutor)   number of arguments: 1
(llvm-tutor) Hello from: fez
(llvm-tutor)   number of arguments: 3
(llvm-tutor) Hello from: bar
(llvm-tutor)   number of arguments: 2
(llvm-tutor) Hello from: foo
(llvm-tutor)   number of arguments: 1
```

### InjectFuncCall vs HelloWorld
You might have noticed that **InjectFuncCall** is somewhat similar to
[**HelloWorld**](#helloworld-your-first-pass). In both cases the pass visits
all functions, prints their names and the number of arguments. The difference
between the two passes becomes quite apparent when you compare the output
generated for the same input file, e.g. `input_for_hello.c`. The number of
times `Hello from` is printed is either:
* once per every function call in the case of **InjectFuncCall**, or
* once per function definition in the case of **HelloWorld**.

This makes perfect sense and hints how different the two passes are. Whether to
print `Hello from` is determined at either:
* run-time for **InjectFuncCall**, or
* compile-time for **HelloWorld**.

Also, note that in the case of **InjectFuncCall** we had to first run the pass
with **opt** and then execute the instrumented IR module in order to see the
output.  For **HelloWorld** it was sufficient to run the pass with **opt**.

## StaticCallCounter
The **StaticCallCounter** pass counts the number of _static_ function calls in
the input LLVM module. _Static_ refers to the fact that these function calls
are compile-time calls (i.e. visible during the compilation). This is in
contrast to _dynamic_ function calls, i.e. function calls encountered at
run-time (when the compiled module is run). The distinction becomes apparent
when analysing functions calls within loops, e.g.:
```c
  for (i = 0; i < 10; i++)
    foo();
```
Although at run-time `foo` will be executed 10 times, **StaticCallCounter**
will report only 1 function call.

This pass will only consider direct functions calls. Functions calls via
function pointers are not taken into account.

### Run the pass through **opt**
We will use
[input_for_cc.c](https://github.com/banach-space/llvm-tutor/blob/main/inputs/input_for_cc.c)
to test **StaticCallCounter**:

```bash
export LLVM_DIR=<installation/dir/of/llvm/23>
# Generate an LLVM file to analyze
$LLVM_DIR/bin/clang -emit-llvm -c <source_dir>/inputs/input_for_cc.c -o input_for_cc.bc
# Run the pass through opt
$LLVM_DIR/bin/opt -load-pass-plugin <build_dir>/lib/libStaticCallCounter.so -passes="print<static-cc>" -disable-output input_for_cc.bc
```
You should see the following output:

```
=================================================
LLVM-TUTOR: static analysis results
=================================================
NAME                 #N DIRECT CALLS
-------------------------------------------------
foo                  3
bar                  2
fez                  1
-------------------------------------------------
```

Note that in order to print the output, you will have to use the printing pass
that corresponds to **StaticCallCounter** (by passing
`-passes="print<static-cc>"` to **opt**). We discussed printing passes in more
detail [here](#run-the-pass).

### Run the pass through `static`
You can run **StaticCallCounter** through a standalone tool called `static`.
`static` is an LLVM based tool implemented in
[StaticMain.cpp](https://github.com/banach-space/llvm-tutor/blob/main/tools/StaticMain.cpp).
It is a command line wrapper that allows you to run **StaticCallCounter**
without the need for **opt**:

```bash
<build_dir>/bin/static input_for_cc.bc
```
It is an example of a relatively basic static analysis tool. Its implementation
demonstrates how basic pass management in LLVM works (i.e. it handles that for
itself instead of relying on **opt**).

## DynamicCallCounter
The **DynamicCallCounter** pass counts the number of _run-time_ (i.e.
encountered during the execution) function calls. It does so by inserting
call-counting instructions that are executed every time a function is called.
Only calls to functions that are _defined_ in the input module are counted.
This pa
↑