[cfe-dev] Fwd: -Wunreachable-code and templates

David Blaikie dblaikie at gmail.com
Wed Nov 30 00:09:18 PST 2011


[sorry, wrong list - moving to cfe-dev]

I'm just wondering if anyone's already working on addressing the
current shortcomings around -Wunreachable-code in regards to
templates.

Take the following simple example:


$ cat unreachable.cpp
int func1();
int func2();
template<bool b>
int func() {
 return !b ? func1() : func2();
}

int main() {
 return func<true>() + func<false>();
}
$ clang++ -Wunreachable-code unreachable.cpp
unreachable.cpp:5:15: warning: will never be executed [-Wunreachable-code]
 return !b ? func1() : func2();
             ^~~~~
unreachable.cpp:9:10: note: in instantiation of function template
specialization 'func<true>' requested here
 return func<true>() + func<false>();
        ^
unreachable.cpp:5:25: warning: will never be executed [-Wunreachable-code]
 return !b ? func1() : func2();
                       ^~~~~
unreachable.cpp:9:25: note: in instantiation of function template
specialization 'func<false>' requested here
 return func<true>() + func<false>();
                       ^
2 warnings generated.


I have at least two (possibly naive) ideas about how to handle this:

1) Visit templates & skip instantiations. This is even consistent with
some existing code (see CFG.cpp:441-ish, where the Expr *S is checked
for type/value dependence & the condition is not evaluated if that is
the case - in fact that's never the case because
AnalysisBasedWarnings.cpp:821 skips analyzing any dependent context.
Instead we could remove the check in AnalysisBasedWarnings.cpp and use
the check in CFG.cpp (& add another check to ignore the actual
template instantiations)). This, I believe, should remove the false
positives with a minimum of fuss. It will also remove a bunch of
correct positive reports from specific template instantiations (for
example if we only instantiated func<true> above, the false case is
unreachable but would not produce a warning)

2) A more interesting option would be to visit the instantiations, but
instead of reporting on the instantiation, build a CFG of the original
template (this would require effectively inter-function analysis -
across all the instantiations of a function template). Once all the
instantiations have been visited we could look at any blocks still
marked unreachable in the original template & produce warnings for
those. My only query here would be where to store the CFG for these
templates & when to visit them to ensure all the instantiations had
already been visited (probably a map as a member of Sema and visit
them at the end of sema - though these may have significant perf
(mostly space - the time is already being spent walking each
instantiation) impact)

So - anyone else already working on this? Existing PRs I should look
at? Other design ideas people have already had?

Thanks,
- David




More information about the cfe-dev mailing list