Various levels of optimization

There are various levels of optimization, starting at 0 and going up to 3 (there is also s for space optimization). The code gets more and more optimized as the optimization level increases. Let's try to explore the various optimization levels.

Getting ready...

Various optimization levels can be understood by running the opt command-line interface on LLVM IR. For this, an example C program can first be converted to IR using the Clang frontend.

  1. Open an example.c file and write the following code in it:
    $ vi  example.c
    int main(int argc, char **argv) {
      int i, j, k, t = 0;
      for(i = 0; i < 10; i++) {
        for(j = 0; j < 10; j++) {
          for(k = 0; k < 10; k++) {
            t++;
          }
        }
        for(j = 0; j < 10; j++) {
          t++;
        }
      }
      for(i = 0; i < 20; i++) {
        for(j = 0; j < 20; j++) {
          t++;
        }
        for(j = 0; j < 20; j++) {
          t++;
        }
      }
      return t;
    }
  2. Now convert this into LLVM IR using the clang command, as shown here:
    $ clang –S –O0 –emit-llvm example.c
    

    A new file, example.ll, will be generated, containing LLVM IR. This file will be used to demonstrate the various optimization levels available.

How to do it…

Do the following steps:

  1. The opt command-line tool can be run on the IR-generated example.ll file:
    $ opt –O0 –S example.ll
    

    The –O0 syntax specifies the least optimization level.

  2. Similarly, you can run other optimization levels:
    $ opt –O1 –S example.ll
    $ opt –O2 –S example.ll
    $ opt –O3 –S example.ll
    

How it works…

The opt command-line interface takes the example.ll file as the input and runs the series of passes specified in each optimization level. It can repeat some passes in the same optimization level. To see which passes are being used in each optimization level, you have to add the --debug-pass=Structure command-line option with the previous opt commands.

See Also

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.79.20