Transforming LLVM IR

In this recipe, we will see how we can transform the IR from one form to another using the opt tool. We will see different optimizations being applied to IR code.

Getting ready

You need to have the opt tool installed.

How to do it...

The opt tool runs the transformation pass as in the following command:

$opt –passname input.ll –o output.ll
  1. Let's take an actual example now. We create the LLVM IR equivalent to the C code used in the recipe Converting a C source code to LLVM assembly:
    $ cat multiply.c
    int mult() {
    int a =5;
    int b = 3;
    int c = a * b;
    return c;
    }
    
  2. Converting and outputting it, we get the unoptimized output:
    $ clang -emit-llvm -S multiply.c -o multiply.ll
    $ cat multiply.ll
    ; ModuleID = 'multiply.c'
    target datalayout ...

Get LLVM Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.