Book Image

LLVM Cookbook

Book Image

LLVM Cookbook

Overview of this book

Table of Contents (16 chapters)
LLVM Cookbook
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Writing an analysis pass


The analysis pass provides higher-level information about IR without actually changing the IR. The results that the analysis pass provides can be used by another analysis pass to compute its result. Also, once an analysis pass calculates the result, its result can be used several times by different passes until the IR on which this pass was run is changed. In this recipe, we will write an analysis pass that counts and outputs the number of opcodes used in a function.

Getting ready

First of all, we write the test code on which we will be running our pass:

$ cat testcode.c
int func(int a, int b){
  int sum = 0;
  int iter;
  for (iter = 0; iter < a; iter++) {
    int iter1;
    for (iter1 = 0; iter1 < b; iter1++) {
      sum += iter > iter1 ? 1 : 0;
    }
  }
  return sum;
}

Transform this into a .bc file, which we will use as the input to the analysis pass:

$ clang -c -emit-llvm testcode.c -o testcode.bc

Now create the file containing the pass source code in...