[cfe-dev] Implementing -Wunused-variables

Douglas Gregor dgregor at apple.com
Mon Oct 5 14:39:59 PDT 2009


On Oct 5, 2009, at 1:37 PM, Oscar Bonilla wrote:

> Hm, after playing with my patch a little I see it's not quite right.
>
> struct s1 {
> 	unsigned int i;
> };
>
> will produce an "unused variable 'i'" warning. This is a better patch.

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?

	- Doug



More information about the cfe-dev mailing list