Loop Unfolding in LLVM

Hello,

I am looking for a loop unfolding procedure implemented in LLVM that helps to transform a while-loop to n-layer If-statements. The transformation should be on IR, although the example below is illustrated on the source level.

original loop:

<i> WHILE (condition) DO
         action
 ENDWHILE</i>

Expected unfolded loop (2-layer):

 *IF (condition) THEN*

 *action*

 *IF (condition) THEN*

 *action*

<i>               WHILE (condition) DO
                    action
               ENDWHILE
</i>

ENDIF

ENDIF

(I thought such transformation is somewhat standard but do not find it the related API of LLVM:loop: http://llvm.org/docs/doxygen/html/classllvm_1_1Loop.html)

Thanks for your help.

Sincerely,

What is the use-case that makes this better than the following?

WHILE (condition) DO
action
IF (condition) THEN
action
IF (condition) THEN
action
ENDIF
ENDIF
ENDWHILE

If your loop normally gets executed a lot of times, then even this should be better, with one fewer duplication of “action”?

WHILE (condition) DO
action
IF (condition) THEN
action
ENDIF

ENDWHILE

Thanks Bruce. I agree your way to unfold can be shown more interesting.

My question was how to do this kind of unfolding in LLVM ? Because such program transformation is standard in compiler textbooks, one may expect it is already implemented in LLVM, so we do not need to do this by ourselves (such as, detecting the loop head, inserting conditional statement, copying basic blocks, etc, which can be tedious). As mentioned earlier, I would like to unfold the loops at the IR level, although the source code was being used as illustration.

Thanks.

Unfortunately I didn’t have the answer to your question. There is unrolling, but it’s normally for loops where you know in advance how many interactions there will be, so you don’t need tests between the copies of the body.