Question

To find the number of instructions in a loop using llvm loop pass. I couldn't get much info in the documentation. Our test file:

#include<stdio.h>
int main(void)
{
    int a,b;
    for(a=0;a<10;a++){
  b=1;
  b=20;
  b=33;
}
return 0;
}

IR file:

 ; ModuleID = 'test.c'
 target datalayout = "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:32:64-f32:32:32-f64:32:64-v64:64:64-v128:128:128-a0:0:64-     f80:32:32-n8:16:32-S128"
 target triple = "i386-pc-linux-gnu"

 define i32 @main() nounwind {
 entry:
   %retval = alloca i32, align 4
   %a = alloca i32, align 4
   %b = alloca i32, align 4
   store i32 0, i32* %retval
   store i32 0, i32* %a, align 4
   br label %for.cond

 for.cond:                                         ; preds = %for.inc, %entry
   %0 = load i32* %a, align 4
   %cmp = icmp slt i32 %0, 10
   br i1 %cmp, label %for.body, label %for.end

 for.body:                                         ; preds = %for.cond
   store i32 1, i32* %b, align 4
   store i32 20, i32* %b, align 4
   store i32 33, i32* %b, align 4
   br label %for.inc

 for.inc:                                          ; preds = %for.body
   %1 = load i32* %a, align 4
   %inc = add nsw i32 %1, 1
   store i32 %inc, i32* %a, align 4
   br label %for.cond

 for.end:                                          ; preds = %for.cond
   ret i32 0
 }

i've to write a loop pass to find the no of instructions in loop body.

Was it helpful?

Solution

You can iterate over all the basic blocks in a Loop object. So if you want the number statically, you can use something like this:

bool runOnLoop(Loop * L, LPPassManager &LPM) {
  int Count = 0;
  for (auto Iter = L->block_begin(), End = L->block_end(); Iter != End; ++Iter) {
    Count += Iter->size();
  }
  // Do something with Count
  return false;
}

If you want the dynamic count of instructions, you'd have to assign each loop a counter and then have each block in the loop increment that counter according to its size. Notice that that may lead to a block having multiple counters in case the loop is nested.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top