[cfe-dev] Implementing -Wunused-variables

Oscar Bonilla ob at bitmover.com
Mon Oct 5 21:46:18 PDT 2009


On Oct 5, 2009, at 2:39 PM, Douglas Gregor wrote:
> This condition:
>
> +    if (isa<VarDecl>(D) && !isa<ParmVarDecl>(D) &&
> +	!D->isUsed() && !D->hasAttr<UnusedAttr>())
> +	    Diag(D->getLocation(), diag::warn_unused_variable) << D- 
> >getDeclName();
>
> is a good start, but I think you only want to complain about  
> function-local variables, e.g., by checking that
>
> 	D->getDeclContext()->isFunctionOrMethod()
>
> There are a few other issues that need to be resolved:
>
>  1) If a variable is only used in an unevaluated context (such as  
> the operand of a sizeof expression), it will incorrectly complain  
> that the variable is unused:
>
> void g() {
>  int i;
>  (void)sizeof(i);
> }
>
>  2) It incorrectly complains about variables in templates:
>
> template<typename T> void f() {
>  T t;
>  t = 17;
> }
>
> With this warning, it makes sense to enable the warning when  
> compiling a small-to-medium---sized C application and then look at  
> where the warning triggers. Did it complain too often? Did GCC  
> correctly complain about something that Clang missed?

That's how I found my previous error, I compiled a product that I'm  
working on and got all sorts of warnings. The problem is that "normal"  
code doesn't have unused variables, so you have to artificially  
introduce them or compile new code with it.

My first thought was that parameters should have the same problem, but  
they are special-cased in MarkDeclaraionReferenced(). I added a  
special case for Variables too, is this right?

Here's what I have:

The patch: 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: ob.patch
Type: application/octet-stream
Size: 1955 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20091005/6a04a149/attachment.obj>
-------------- next part --------------

The testcases:
llvm/tools/clang/test/Sema/warn-unused-variables.c 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: warn-unused-variables.c
Type: application/octet-stream
Size: 265 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20091005/6a04a149/attachment-0001.obj>
-------------- next part --------------

llvm/tools/clang/test/SemaCXX/warn-unused-variables.c 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: warn-unused-variables.cpp
Type: application/octet-stream
Size: 107 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20091005/6a04a149/attachment-0002.obj>
-------------- next part --------------


Is this any better?

Cheers,

-Oscar

P.S. I will wait for your okay before updating the bug report this  
time :)



More information about the cfe-dev mailing list