c++optimizationdead-code

How can I know which parts in the code are never used?


I have legacy C++ code that I'm supposed to remove unused code from. The problem is that the code base is large.

How can I find out which code is never called/never used?


Solution

  • There are two varieties of unused code:

    For the first kind, a good compiler can help:

    For the second kind, it's much more difficult. Statically it requires whole program analysis, and even though link time optimization may actually remove dead code, in practice the program has been so much transformed at the time it is performed that it is near impossible to convey meaningful information to the user.

    There are therefore two approaches:

    If you are extremely interested in the subject, and have the time and inclination to actually work out a tool by yourself, I would suggest using the Clang libraries to build such a tool.

    1. Use the Clang library to get an AST (abstract syntax tree)
    2. Perform a mark-and-sweep analysis from the entry points onward

    Because Clang will parse the code for you, and perform overload resolution, you won't have to deal with the C++ languages rules, and you'll be able to concentrate on the problem at hand.

    However this kind of technique cannot identify the virtual overrides that are unused, since they could be called by third-party code you cannot reason about.