I am trying to use Clang to find all the loops at the source code level of an input source file. My code currently can identify for-loops in the source file and printout the line number. It also seems to find the while-loops, but it does not printout the line number.

Here is the relevant code snippet.

      for (auto it = sourceCFG->begin(); it != sourceCFG->end(); ++it)
      {
        CFGBlock *block = *it;
        if (block->getLoopTarget())
        {
          const Stmt *stmt = block->getLoopTarget();
          printf("Loop entry point: %d\n", block->getBlockID());
          for (auto it2 = block->begin(); it2 != block->end(); ++it2)
          {
            CFGElement elem = *it2;
            if (elem.getKind() == CFGElement::Kind::Statement)
            {
              const Stmt *stmt = elem.castAs<CFGStmt>().getStmt();
              SourceRange range = stmt->getSourceRange();
              SourceManager &sm = context->getSourceManager();
              range.dump(sm);
            }
            else {
              printf("never show up anything\n");
            }
          }
        }
      }

The output is the following

Loop entry point: 1
</home/weifan/llvm-tools/clang+llvm-16.0.3-x86_64-linux-gnu-ubuntu-22.04/test_bare_loops.cpp:50:17, col:18>
Loop entry point: 2
Loop entry point: 10
Loop entry point: 12
Loop entry point: 20
</home/weifan/llvm-tools/clang+llvm-16.0.3-x86_64-linux-gnu-ubuntu-22.04/test_bare_loops.cpp:26:17, col:18>
Loop entry point: 21
</home/weifan/llvm-tools/clang+llvm-16.0.3-x86_64-linux-gnu-ubuntu-22.04/test_bare_loops.cpp:27:18, col:19>
Loop entry point: 29
Loop entry point: 35
</home/weifan/llvm-tools/clang+llvm-16.0.3-x86_64-linux-gnu-ubuntu-
22.04/test_bare_loops.cpp:8:18, col:19>

I have verified that for loop entry point that the SourceManager provides a line number is a for-loop. For the rest that the SourceManager does not provide should be the while loop. Additionally, if I use the sourceCFG->dump(), I can indeed see some CFGBlocks do not have code fragment associated, like below

 [B2]
   Preds (1): B3
   Succs (1): B7

Nor did I see any while in the dump.

So my questions are:

  1. why this behavior?
  2. How I can retrieve the line number of the while loop via clang/llvm?

Thanks a lot!

I am quite new to clang/llvm/c++

1

There are 1 best solutions below

0
Kokoro On

Ok, I am too dumb to realize I should have called the SourceManager to dump the Stmt at const Stmt *stmt = block->getLoopTarget(); right away. This would reveal while-loops as well.