I am trying to write up a transformation for the following code where instead of incrementing the loop variable by 1, I increment it by 2 ie.
for (i=0; i < THRES; i++) {
//do something
}
gets transformed to
for (i=0; i < THRES; i+=2) {
//do something
}
I am thinking of transforming the llvm bit-code in the following way.
Iterate over the function for the original code till I get the basicBlock for the for loop, then iterate over the instructions till I get the increment instruction and then add the same increment instruction so that the increment happens twice.
I am still getting familiar with the llvm infrastructure and I am not sure if the above approach is even going to work. It’ll be great if someone can suggest a better or more concrete way of doing the above transformation ? Is there already something similar in the source tree that can I look up for ideas ?
getCanonicalInductionVariable is a good example of finding IVs without iterating over instructions. But you may need to generalize it a bit for your purpose.
A completely general approach to IV analysis is ScalarEvolution. You can query the expression for a loop header phi using ScalarEvolution::getSCEV. If it returns SCEVAddRecExpr with getLoop() == ThisLoop, then you've found an IV. You can build a new IV by replacing the "step" with SCEVAddExpr(1 + OrigStep). To materialize it in IR, you need to use a SCEVExpander. ...probably more complicated than you need.