blob: f759133a0517bc1cd51b2491a823ed8e8d1a92db [file] [log] [blame]
Chris Lattner2e64c072007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner2e64c072007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements extra semantic analysis beyond what is enforced
11// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
15#include "Sema.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/Decl.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chris Lattner2e64c072007-08-10 20:18:51 +000019#include "clang/AST/Expr.h"
Ted Kremenek1c1700f2007-08-20 16:18:38 +000020#include "clang/AST/ExprCXX.h"
Ted Kremenek225a14c2008-06-16 18:00:42 +000021#include "clang/AST/ExprObjC.h"
Chris Lattner2e64c072007-08-10 20:18:51 +000022#include "clang/Lex/Preprocessor.h"
23#include "clang/Lex/LiteralSupport.h"
24#include "clang/Basic/SourceManager.h"
25#include "clang/Basic/Diagnostic.h"
26#include "clang/Basic/LangOptions.h"
27#include "clang/Basic/TargetInfo.h"
Eli Friedman798e4d52008-05-16 17:51:27 +000028#include "llvm/ADT/OwningPtr.h"
Chris Lattner2e64c072007-08-10 20:18:51 +000029#include "llvm/ADT/SmallString.h"
30#include "llvm/ADT/StringExtras.h"
Ted Kremenek30c66752007-11-25 00:58:00 +000031#include "SemaUtil.h"
Chris Lattner2e64c072007-08-10 20:18:51 +000032using namespace clang;
33
34/// CheckFunctionCall - Check a direct function call for various correctness
35/// and safety properties not strictly enforced by the C type system.
Eli Friedmand0e9d092008-05-14 19:38:39 +000036Action::ExprResult
Eli Friedman798e4d52008-05-16 17:51:27 +000037Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCallRaw) {
38 llvm::OwningPtr<CallExpr> TheCall(TheCallRaw);
Chris Lattner2e64c072007-08-10 20:18:51 +000039 // Get the IdentifierInfo* for the called function.
40 IdentifierInfo *FnInfo = FDecl->getIdentifier();
41
Chris Lattnerf22a8502007-12-19 23:59:04 +000042 switch (FnInfo->getBuiltinID()) {
43 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner83bd5eb2007-12-28 05:29:59 +000044 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner7c8d1af2007-12-20 00:26:33 +000045 "Wrong # arguments to builtin CFStringMakeConstantString");
Eli Friedman798e4d52008-05-16 17:51:27 +000046 if (CheckBuiltinCFStringArgument(TheCall->getArg(0)))
Eli Friedmand0e9d092008-05-14 19:38:39 +000047 return true;
Eli Friedman798e4d52008-05-16 17:51:27 +000048 return TheCall.take();
Ted Kremenek7a0654c2008-07-09 17:58:53 +000049 case Builtin::BI__builtin_stdarg_start:
Chris Lattnerf22a8502007-12-19 23:59:04 +000050 case Builtin::BI__builtin_va_start:
Chris Lattner2a674dc2008-06-30 18:32:54 +000051 if (SemaBuiltinVAStart(TheCall.get()))
Eli Friedmand0e9d092008-05-14 19:38:39 +000052 return true;
Eli Friedman798e4d52008-05-16 17:51:27 +000053 return TheCall.take();
Chris Lattner7c8d1af2007-12-20 00:26:33 +000054 case Builtin::BI__builtin_isgreater:
55 case Builtin::BI__builtin_isgreaterequal:
56 case Builtin::BI__builtin_isless:
57 case Builtin::BI__builtin_islessequal:
58 case Builtin::BI__builtin_islessgreater:
59 case Builtin::BI__builtin_isunordered:
Eli Friedman798e4d52008-05-16 17:51:27 +000060 if (SemaBuiltinUnorderedCompare(TheCall.get()))
Eli Friedmand0e9d092008-05-14 19:38:39 +000061 return true;
Eli Friedman798e4d52008-05-16 17:51:27 +000062 return TheCall.take();
Eli Friedman8c50c622008-05-20 08:23:37 +000063 case Builtin::BI__builtin_return_address:
64 case Builtin::BI__builtin_frame_address:
65 if (SemaBuiltinStackAddress(TheCall.get()))
66 return true;
67 return TheCall.take();
Eli Friedmand0e9d092008-05-14 19:38:39 +000068 case Builtin::BI__builtin_shufflevector:
Eli Friedman798e4d52008-05-16 17:51:27 +000069 return SemaBuiltinShuffleVector(TheCall.get());
Daniel Dunbar5b0de852008-07-21 22:59:13 +000070 case Builtin::BI__builtin_prefetch:
71 if (SemaBuiltinPrefetch(TheCall.get()))
72 return true;
73 return TheCall.take();
Anders Carlssone7e7aa22007-08-17 05:31:46 +000074 }
75
Chris Lattner2e64c072007-08-10 20:18:51 +000076 // Search the KnownFunctionIDs for the identifier.
77 unsigned i = 0, e = id_num_known_functions;
Ted Kremenek081ed872007-08-14 17:39:48 +000078 for (; i != e; ++i) { if (KnownFunctionIDs[i] == FnInfo) break; }
Eli Friedman798e4d52008-05-16 17:51:27 +000079 if (i == e) return TheCall.take();
Chris Lattner2e64c072007-08-10 20:18:51 +000080
81 // Printf checking.
82 if (i <= id_vprintf) {
Ted Kremenek081ed872007-08-14 17:39:48 +000083 // Retrieve the index of the format string parameter and determine
84 // if the function is passed a va_arg argument.
Chris Lattner2e64c072007-08-10 20:18:51 +000085 unsigned format_idx = 0;
Ted Kremenek081ed872007-08-14 17:39:48 +000086 bool HasVAListArg = false;
87
Chris Lattner2e64c072007-08-10 20:18:51 +000088 switch (i) {
Chris Lattnerf22a8502007-12-19 23:59:04 +000089 default: assert(false && "No format string argument index.");
90 case id_printf: format_idx = 0; break;
91 case id_fprintf: format_idx = 1; break;
92 case id_sprintf: format_idx = 1; break;
93 case id_snprintf: format_idx = 2; break;
94 case id_asprintf: format_idx = 1; break;
Ted Kremenek225a14c2008-06-16 18:00:42 +000095 case id_NSLog: format_idx = 0; break;
Chris Lattnerf22a8502007-12-19 23:59:04 +000096 case id_vsnprintf: format_idx = 2; HasVAListArg = true; break;
97 case id_vasprintf: format_idx = 1; HasVAListArg = true; break;
98 case id_vfprintf: format_idx = 1; HasVAListArg = true; break;
99 case id_vsprintf: format_idx = 1; HasVAListArg = true; break;
100 case id_vprintf: format_idx = 0; HasVAListArg = true; break;
Ted Kremenek081ed872007-08-14 17:39:48 +0000101 }
102
Eli Friedman798e4d52008-05-16 17:51:27 +0000103 CheckPrintfArguments(TheCall.get(), HasVAListArg, format_idx);
Chris Lattner2e64c072007-08-10 20:18:51 +0000104 }
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000105
Eli Friedman798e4d52008-05-16 17:51:27 +0000106 return TheCall.take();
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000107}
108
109/// CheckBuiltinCFStringArgument - Checks that the argument to the builtin
110/// CFString constructor is correct
Chris Lattnerda050402007-08-25 05:30:33 +0000111bool Sema::CheckBuiltinCFStringArgument(Expr* Arg) {
Chris Lattner7a48d9c2008-02-13 01:02:39 +0000112 Arg = Arg->IgnoreParenCasts();
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000113
114 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
115
116 if (!Literal || Literal->isWide()) {
117 Diag(Arg->getLocStart(),
118 diag::err_cfstring_literal_not_string_constant,
119 Arg->getSourceRange());
Anders Carlsson3e9b43b2007-08-17 15:44:17 +0000120 return true;
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000121 }
122
123 const char *Data = Literal->getStrData();
124 unsigned Length = Literal->getByteLength();
125
126 for (unsigned i = 0; i < Length; ++i) {
127 if (!isascii(Data[i])) {
128 Diag(PP.AdvanceToTokenCharacter(Arg->getLocStart(), i + 1),
129 diag::warn_cfstring_literal_contains_non_ascii_character,
130 Arg->getSourceRange());
131 break;
132 }
133
134 if (!Data[i]) {
135 Diag(PP.AdvanceToTokenCharacter(Arg->getLocStart(), i + 1),
136 diag::warn_cfstring_literal_contains_nul_character,
137 Arg->getSourceRange());
138 break;
139 }
140 }
141
Anders Carlsson3e9b43b2007-08-17 15:44:17 +0000142 return false;
Chris Lattner2e64c072007-08-10 20:18:51 +0000143}
144
Chris Lattner3b933692007-12-20 00:05:45 +0000145/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
146/// Emit an error and return true on failure, return false on success.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000147bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
148 Expr *Fn = TheCall->getCallee();
149 if (TheCall->getNumArgs() > 2) {
150 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerf22a8502007-12-19 23:59:04 +0000151 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000152 SourceRange(TheCall->getArg(2)->getLocStart(),
153 (*(TheCall->arg_end()-1))->getLocEnd()));
Chris Lattnerf22a8502007-12-19 23:59:04 +0000154 return true;
155 }
156
Chris Lattner3b933692007-12-20 00:05:45 +0000157 // Determine whether the current function is variadic or not.
158 bool isVariadic;
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000159 if (getCurFunctionDecl())
Chris Lattner3b933692007-12-20 00:05:45 +0000160 isVariadic =
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000161 cast<FunctionTypeProto>(getCurFunctionDecl()->getType())->isVariadic();
Chris Lattnerf22a8502007-12-19 23:59:04 +0000162 else
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000163 isVariadic = getCurMethodDecl()->isVariadic();
Chris Lattnerf22a8502007-12-19 23:59:04 +0000164
Chris Lattner3b933692007-12-20 00:05:45 +0000165 if (!isVariadic) {
Chris Lattnerf22a8502007-12-19 23:59:04 +0000166 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
167 return true;
168 }
169
170 // Verify that the second argument to the builtin is the last argument of the
171 // current function or method.
172 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson924556e2008-02-13 01:22:59 +0000173 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Anders Carlssonc27156b2008-02-11 04:20:54 +0000174
175 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
176 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattnerf22a8502007-12-19 23:59:04 +0000177 // FIXME: This isn't correct for methods (results in bogus warning).
178 // Get the last formal in the current function.
Anders Carlssonc27156b2008-02-11 04:20:54 +0000179 const ParmVarDecl *LastArg;
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000180 if (getCurFunctionDecl())
181 LastArg = *(getCurFunctionDecl()->param_end()-1);
Chris Lattnerf22a8502007-12-19 23:59:04 +0000182 else
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000183 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattnerf22a8502007-12-19 23:59:04 +0000184 SecondArgIsLastNamedArgument = PV == LastArg;
185 }
186 }
187
188 if (!SecondArgIsLastNamedArgument)
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000189 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattnerf22a8502007-12-19 23:59:04 +0000190 diag::warn_second_parameter_of_va_start_not_last_named_argument);
191 return false;
Eli Friedman8c50c622008-05-20 08:23:37 +0000192}
Chris Lattnerf22a8502007-12-19 23:59:04 +0000193
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000194/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
195/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000196bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
197 if (TheCall->getNumArgs() < 2)
198 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args);
199 if (TheCall->getNumArgs() > 2)
200 return Diag(TheCall->getArg(2)->getLocStart(),
201 diag::err_typecheck_call_too_many_args,
202 SourceRange(TheCall->getArg(2)->getLocStart(),
203 (*(TheCall->arg_end()-1))->getLocEnd()));
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000204
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000205 Expr *OrigArg0 = TheCall->getArg(0);
206 Expr *OrigArg1 = TheCall->getArg(1);
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000207
208 // Do standard promotions between the two arguments, returning their common
209 // type.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000210 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000211
212 // If the common type isn't a real floating type, then the arguments were
213 // invalid for this operation.
214 if (!Res->isRealFloatingType())
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000215 return Diag(OrigArg0->getLocStart(),
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000216 diag::err_typecheck_call_invalid_ordered_compare,
217 OrigArg0->getType().getAsString(),
218 OrigArg1->getType().getAsString(),
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000219 SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd()));
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000220
221 return false;
222}
223
Eli Friedman8c50c622008-05-20 08:23:37 +0000224bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) {
225 // The signature for these builtins is exact; the only thing we need
226 // to check is that the argument is a constant.
227 SourceLocation Loc;
Chris Lattner941c0102008-08-10 02:05:13 +0000228 if (!TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc))
Eli Friedman8c50c622008-05-20 08:23:37 +0000229 return Diag(Loc, diag::err_stack_const_level, TheCall->getSourceRange());
Chris Lattner941c0102008-08-10 02:05:13 +0000230
Eli Friedman8c50c622008-05-20 08:23:37 +0000231 return false;
232}
233
Eli Friedmand0e9d092008-05-14 19:38:39 +0000234/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
235// This is declared to take (...), so we have to check everything.
236Action::ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
237 if (TheCall->getNumArgs() < 3)
238 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args,
239 TheCall->getSourceRange());
240
241 QualType FAType = TheCall->getArg(0)->getType();
242 QualType SAType = TheCall->getArg(1)->getType();
243
244 if (!FAType->isVectorType() || !SAType->isVectorType()) {
245 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector,
246 SourceRange(TheCall->getArg(0)->getLocStart(),
247 TheCall->getArg(1)->getLocEnd()));
Eli Friedmand0e9d092008-05-14 19:38:39 +0000248 return true;
249 }
250
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000251 if (Context.getCanonicalType(FAType).getUnqualifiedType() !=
252 Context.getCanonicalType(SAType).getUnqualifiedType()) {
Eli Friedmand0e9d092008-05-14 19:38:39 +0000253 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector,
254 SourceRange(TheCall->getArg(0)->getLocStart(),
255 TheCall->getArg(1)->getLocEnd()));
Eli Friedmand0e9d092008-05-14 19:38:39 +0000256 return true;
257 }
258
259 unsigned numElements = FAType->getAsVectorType()->getNumElements();
260 if (TheCall->getNumArgs() != numElements+2) {
261 if (TheCall->getNumArgs() < numElements+2)
Chris Lattner941c0102008-08-10 02:05:13 +0000262 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args,
263 TheCall->getSourceRange());
264 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args,
265 TheCall->getSourceRange());
Eli Friedmand0e9d092008-05-14 19:38:39 +0000266 }
267
268 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
269 llvm::APSInt Result(32);
Chris Lattner941c0102008-08-10 02:05:13 +0000270 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
271 return Diag(TheCall->getLocStart(),
272 diag::err_shufflevector_nonconstant_argument,
273 TheCall->getArg(i)->getSourceRange());
274
275 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
276 return Diag(TheCall->getLocStart(),
277 diag::err_shufflevector_argument_too_large,
278 TheCall->getArg(i)->getSourceRange());
Eli Friedmand0e9d092008-05-14 19:38:39 +0000279 }
280
281 llvm::SmallVector<Expr*, 32> exprs;
282
Chris Lattner941c0102008-08-10 02:05:13 +0000283 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand0e9d092008-05-14 19:38:39 +0000284 exprs.push_back(TheCall->getArg(i));
285 TheCall->setArg(i, 0);
286 }
287
Chris Lattner941c0102008-08-10 02:05:13 +0000288 return new ShuffleVectorExpr(exprs.begin(), numElements+2, FAType,
289 TheCall->getCallee()->getLocStart(),
290 TheCall->getRParenLoc());
Eli Friedmand0e9d092008-05-14 19:38:39 +0000291}
Chris Lattnerf22a8502007-12-19 23:59:04 +0000292
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000293/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
294// This is declared to take (const void*, ...) and can take two
295// optional constant int args.
296bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
297 unsigned numArgs = TheCall->getNumArgs();
298 bool res = false;
299
300 if (numArgs > 3) {
301 res |= Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args,
302 TheCall->getSourceRange());
303 }
304
305 // Argument 0 is checked for us and the remaining arguments must be
306 // constant integers.
307 for (unsigned i=1; i<numArgs; ++i) {
308 Expr *Arg = TheCall->getArg(i);
309 QualType RWType = Arg->getType();
310
311 const BuiltinType *BT = RWType->getAsBuiltinType();
312 // FIXME: 32 is wrong, needs to be proper width of Int
313 llvm::APSInt Result(32);
314 if (!BT || BT->getKind() != BuiltinType::Int ||
315 !Arg->isIntegerConstantExpr(Result, Context)) {
316 if (Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument,
317 SourceRange(Arg->getLocStart(), Arg->getLocEnd()))) {
318 res = true;
319 continue;
320 }
321 }
322
323 // FIXME: gcc issues a warning and rewrites these to 0. These
324 // seems especially odd for the third argument since the default
325 // is 3.
326 if (i==1) {
327 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 1)
328 res |= Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_range,
329 "0", "1",
330 SourceRange(Arg->getLocStart(), Arg->getLocEnd()));
331 } else {
332 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3)
333 res |= Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_range,
334 "0", "3",
335 SourceRange(Arg->getLocStart(), Arg->getLocEnd()));
336 }
337 }
338
339 return res;
340}
341
Chris Lattner2e64c072007-08-10 20:18:51 +0000342/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Ted Kremenek081ed872007-08-14 17:39:48 +0000343/// correct use of format strings.
344///
345/// HasVAListArg - A predicate indicating whether the printf-like
346/// function is passed an explicit va_arg argument (e.g., vprintf)
347///
348/// format_idx - The index into Args for the format string.
349///
350/// Improper format strings to functions in the printf family can be
351/// the source of bizarre bugs and very serious security holes. A
352/// good source of information is available in the following paper
353/// (which includes additional references):
Chris Lattner2e64c072007-08-10 20:18:51 +0000354///
355/// FormatGuard: Automatic Protection From printf Format String
356/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremenek081ed872007-08-14 17:39:48 +0000357///
358/// Functionality implemented:
359///
360/// We can statically check the following properties for string
361/// literal format strings for non v.*printf functions (where the
362/// arguments are passed directly):
363//
364/// (1) Are the number of format conversions equal to the number of
365/// data arguments?
366///
367/// (2) Does each format conversion correctly match the type of the
368/// corresponding data argument? (TODO)
369///
370/// Moreover, for all printf functions we can:
371///
372/// (3) Check for a missing format string (when not caught by type checking).
373///
374/// (4) Check for no-operation flags; e.g. using "#" with format
375/// conversion 'c' (TODO)
376///
377/// (5) Check the use of '%n', a major source of security holes.
378///
379/// (6) Check for malformed format conversions that don't specify anything.
380///
381/// (7) Check for empty format strings. e.g: printf("");
382///
383/// (8) Check that the format string is a wide literal.
384///
Ted Kremenekc2804c22008-03-03 16:50:00 +0000385/// (9) Also check the arguments of functions with the __format__ attribute.
386/// (TODO).
387///
Ted Kremenek081ed872007-08-14 17:39:48 +0000388/// All of these checks can be done by parsing the format string.
389///
390/// For now, we ONLY do (1), (3), (5), (6), (7), and (8).
Chris Lattner2e64c072007-08-10 20:18:51 +0000391void
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000392Sema::CheckPrintfArguments(CallExpr *TheCall, bool HasVAListArg,
393 unsigned format_idx) {
394 Expr *Fn = TheCall->getCallee();
395
Ted Kremenek081ed872007-08-14 17:39:48 +0000396 // CHECK: printf-like function is called with no format string.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000397 if (format_idx >= TheCall->getNumArgs()) {
398 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string,
Ted Kremenek081ed872007-08-14 17:39:48 +0000399 Fn->getSourceRange());
400 return;
401 }
402
Chris Lattner7a48d9c2008-02-13 01:02:39 +0000403 Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Chris Lattnere65acc12007-08-25 05:36:18 +0000404
Chris Lattner2e64c072007-08-10 20:18:51 +0000405 // CHECK: format string is not a string literal.
406 //
Ted Kremenek081ed872007-08-14 17:39:48 +0000407 // Dynamically generated format strings are difficult to
408 // automatically vet at compile time. Requiring that format strings
409 // are string literals: (1) permits the checking of format strings by
410 // the compiler and thereby (2) can practically remove the source of
411 // many format string exploits.
Ted Kremenek225a14c2008-06-16 18:00:42 +0000412
413 // Format string can be either ObjC string (e.g. @"%d") or
414 // C string (e.g. "%d")
415 // ObjC string uses the same format specifiers as C string, so we can use
416 // the same format string checking logic for both ObjC and C strings.
417 ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(OrigFormatExpr);
418 StringLiteral *FExpr = NULL;
419
420 if(ObjCFExpr != NULL)
421 FExpr = ObjCFExpr->getString();
422 else
423 FExpr = dyn_cast<StringLiteral>(OrigFormatExpr);
424
Ted Kremenek081ed872007-08-14 17:39:48 +0000425 if (FExpr == NULL) {
Ted Kremenek19398b62007-12-17 19:03:13 +0000426 // For vprintf* functions (i.e., HasVAListArg==true), we add a
427 // special check to see if the format string is a function parameter
428 // of the function calling the printf function. If the function
429 // has an attribute indicating it is a printf-like function, then we
430 // should suppress warnings concerning non-literals being used in a call
431 // to a vprintf function. For example:
432 //
433 // void
434 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...) {
435 // va_list ap;
436 // va_start(ap, fmt);
437 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
438 // ...
439 //
440 //
441 // FIXME: We don't have full attribute support yet, so just check to see
442 // if the argument is a DeclRefExpr that references a parameter. We'll
443 // add proper support for checking the attribute later.
444 if (HasVAListArg)
Chris Lattner3d5a8f32007-12-28 05:38:24 +0000445 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(OrigFormatExpr))
446 if (isa<ParmVarDecl>(DR->getDecl()))
Ted Kremenek19398b62007-12-17 19:03:13 +0000447 return;
448
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000449 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek6077e2f2008-07-25 22:03:03 +0000450 diag::warn_printf_not_string_constant,
451 OrigFormatExpr->getSourceRange());
Ted Kremenek081ed872007-08-14 17:39:48 +0000452 return;
453 }
454
455 // CHECK: is the format string a wide literal?
456 if (FExpr->isWide()) {
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000457 Diag(FExpr->getLocStart(),
Ted Kremenek6077e2f2008-07-25 22:03:03 +0000458 diag::warn_printf_format_string_is_wide_literal,
459 OrigFormatExpr->getSourceRange());
Ted Kremenek081ed872007-08-14 17:39:48 +0000460 return;
461 }
462
463 // Str - The format string. NOTE: this is NOT null-terminated!
464 const char * const Str = FExpr->getStrData();
465
466 // CHECK: empty format string?
467 const unsigned StrLen = FExpr->getByteLength();
468
469 if (StrLen == 0) {
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000470 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string,
Ted Kremenek6077e2f2008-07-25 22:03:03 +0000471 OrigFormatExpr->getSourceRange());
Ted Kremenek081ed872007-08-14 17:39:48 +0000472 return;
473 }
474
475 // We process the format string using a binary state machine. The
476 // current state is stored in CurrentState.
477 enum {
478 state_OrdChr,
479 state_Conversion
480 } CurrentState = state_OrdChr;
481
482 // numConversions - The number of conversions seen so far. This is
483 // incremented as we traverse the format string.
484 unsigned numConversions = 0;
485
486 // numDataArgs - The number of data arguments after the format
487 // string. This can only be determined for non vprintf-like
488 // functions. For those functions, this value is 1 (the sole
489 // va_arg argument).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000490 unsigned numDataArgs = TheCall->getNumArgs()-(format_idx+1);
Ted Kremenek081ed872007-08-14 17:39:48 +0000491
492 // Inspect the format string.
493 unsigned StrIdx = 0;
494
495 // LastConversionIdx - Index within the format string where we last saw
496 // a '%' character that starts a new format conversion.
497 unsigned LastConversionIdx = 0;
498
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000499 for (; StrIdx < StrLen; ++StrIdx) {
Chris Lattner3d5a8f32007-12-28 05:38:24 +0000500
Ted Kremenek081ed872007-08-14 17:39:48 +0000501 // Is the number of detected conversion conversions greater than
502 // the number of matching data arguments? If so, stop.
503 if (!HasVAListArg && numConversions > numDataArgs) break;
504
505 // Handle "\0"
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000506 if (Str[StrIdx] == '\0') {
Ted Kremenek081ed872007-08-14 17:39:48 +0000507 // The string returned by getStrData() is not null-terminated,
508 // so the presence of a null character is likely an error.
Chris Lattner3d5a8f32007-12-28 05:38:24 +0000509 Diag(PP.AdvanceToTokenCharacter(FExpr->getLocStart(), StrIdx+1),
510 diag::warn_printf_format_string_contains_null_char,
Ted Kremenek6077e2f2008-07-25 22:03:03 +0000511 OrigFormatExpr->getSourceRange());
Ted Kremenek081ed872007-08-14 17:39:48 +0000512 return;
513 }
514
515 // Ordinary characters (not processing a format conversion).
516 if (CurrentState == state_OrdChr) {
517 if (Str[StrIdx] == '%') {
518 CurrentState = state_Conversion;
519 LastConversionIdx = StrIdx;
520 }
521 continue;
522 }
523
524 // Seen '%'. Now processing a format conversion.
525 switch (Str[StrIdx]) {
Chris Lattner68d88f02007-12-28 05:31:15 +0000526 // Handle dynamic precision or width specifier.
527 case '*': {
528 ++numConversions;
529
530 if (!HasVAListArg && numConversions > numDataArgs) {
Chris Lattner68d88f02007-12-28 05:31:15 +0000531 SourceLocation Loc = FExpr->getLocStart();
532 Loc = PP.AdvanceToTokenCharacter(Loc, StrIdx+1);
Ted Kremenek035d8792007-10-12 20:51:52 +0000533
Ted Kremenek035d8792007-10-12 20:51:52 +0000534 if (Str[StrIdx-1] == '.')
Chris Lattner68d88f02007-12-28 05:31:15 +0000535 Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg,
Ted Kremenek6077e2f2008-07-25 22:03:03 +0000536 OrigFormatExpr->getSourceRange());
Ted Kremenek035d8792007-10-12 20:51:52 +0000537 else
Chris Lattner68d88f02007-12-28 05:31:15 +0000538 Diag(Loc, diag::warn_printf_asterisk_width_missing_arg,
Ted Kremenek6077e2f2008-07-25 22:03:03 +0000539 OrigFormatExpr->getSourceRange());
Ted Kremenek035d8792007-10-12 20:51:52 +0000540
Chris Lattner68d88f02007-12-28 05:31:15 +0000541 // Don't do any more checking. We'll just emit spurious errors.
542 return;
Ted Kremenek035d8792007-10-12 20:51:52 +0000543 }
Chris Lattner68d88f02007-12-28 05:31:15 +0000544
545 // Perform type checking on width/precision specifier.
546 Expr *E = TheCall->getArg(format_idx+numConversions);
547 if (const BuiltinType *BT = E->getType()->getAsBuiltinType())
548 if (BT->getKind() == BuiltinType::Int)
549 break;
Ted Kremenek081ed872007-08-14 17:39:48 +0000550
Chris Lattner68d88f02007-12-28 05:31:15 +0000551 SourceLocation Loc =
552 PP.AdvanceToTokenCharacter(FExpr->getLocStart(), StrIdx+1);
553
554 if (Str[StrIdx-1] == '.')
555 Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type,
556 E->getType().getAsString(), E->getSourceRange());
557 else
558 Diag(Loc, diag::warn_printf_asterisk_width_wrong_type,
559 E->getType().getAsString(), E->getSourceRange());
560
561 break;
562 }
563
564 // Characters which can terminate a format conversion
565 // (e.g. "%d"). Characters that specify length modifiers or
566 // other flags are handled by the default case below.
567 //
568 // FIXME: additional checks will go into the following cases.
569 case 'i':
570 case 'd':
571 case 'o':
572 case 'u':
573 case 'x':
574 case 'X':
575 case 'D':
576 case 'O':
577 case 'U':
578 case 'e':
579 case 'E':
580 case 'f':
581 case 'F':
582 case 'g':
583 case 'G':
584 case 'a':
585 case 'A':
586 case 'c':
587 case 'C':
588 case 'S':
589 case 's':
590 case 'p':
591 ++numConversions;
592 CurrentState = state_OrdChr;
593 break;
594
595 // CHECK: Are we using "%n"? Issue a warning.
596 case 'n': {
597 ++numConversions;
598 CurrentState = state_OrdChr;
599 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
600 LastConversionIdx+1);
601
Ted Kremenek6077e2f2008-07-25 22:03:03 +0000602 Diag(Loc, diag::warn_printf_write_back, OrigFormatExpr->getSourceRange());
Chris Lattner68d88f02007-12-28 05:31:15 +0000603 break;
604 }
Ted Kremenek225a14c2008-06-16 18:00:42 +0000605
606 // Handle "%@"
607 case '@':
608 // %@ is allowed in ObjC format strings only.
609 if(ObjCFExpr != NULL)
610 CurrentState = state_OrdChr;
611 else {
612 // Issue a warning: invalid format conversion.
613 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
614 LastConversionIdx+1);
615
616 Diag(Loc, diag::warn_printf_invalid_conversion,
617 std::string(Str+LastConversionIdx,
618 Str+std::min(LastConversionIdx+2, StrLen)),
Ted Kremenek6077e2f2008-07-25 22:03:03 +0000619 OrigFormatExpr->getSourceRange());
Ted Kremenek225a14c2008-06-16 18:00:42 +0000620 }
621 ++numConversions;
622 break;
623
Chris Lattner68d88f02007-12-28 05:31:15 +0000624 // Handle "%%"
625 case '%':
626 // Sanity check: Was the first "%" character the previous one?
627 // If not, we will assume that we have a malformed format
628 // conversion, and that the current "%" character is the start
629 // of a new conversion.
630 if (StrIdx - LastConversionIdx == 1)
631 CurrentState = state_OrdChr;
632 else {
633 // Issue a warning: invalid format conversion.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000634 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
635 LastConversionIdx+1);
Chris Lattner68d88f02007-12-28 05:31:15 +0000636
637 Diag(Loc, diag::warn_printf_invalid_conversion,
638 std::string(Str+LastConversionIdx, Str+StrIdx),
Ted Kremenek6077e2f2008-07-25 22:03:03 +0000639 OrigFormatExpr->getSourceRange());
Chris Lattner68d88f02007-12-28 05:31:15 +0000640
641 // This conversion is broken. Advance to the next format
642 // conversion.
643 LastConversionIdx = StrIdx;
644 ++numConversions;
Ted Kremenek081ed872007-08-14 17:39:48 +0000645 }
Chris Lattner68d88f02007-12-28 05:31:15 +0000646 break;
Ted Kremenek081ed872007-08-14 17:39:48 +0000647
Chris Lattner68d88f02007-12-28 05:31:15 +0000648 default:
649 // This case catches all other characters: flags, widths, etc.
650 // We should eventually process those as well.
651 break;
Ted Kremenek081ed872007-08-14 17:39:48 +0000652 }
653 }
654
655 if (CurrentState == state_Conversion) {
656 // Issue a warning: invalid format conversion.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000657 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
658 LastConversionIdx+1);
Ted Kremenek081ed872007-08-14 17:39:48 +0000659
660 Diag(Loc, diag::warn_printf_invalid_conversion,
Chris Lattner6f65d202007-08-26 17:38:22 +0000661 std::string(Str+LastConversionIdx,
662 Str+std::min(LastConversionIdx+2, StrLen)),
Ted Kremenek6077e2f2008-07-25 22:03:03 +0000663 OrigFormatExpr->getSourceRange());
Ted Kremenek081ed872007-08-14 17:39:48 +0000664 return;
665 }
666
667 if (!HasVAListArg) {
668 // CHECK: Does the number of format conversions exceed the number
669 // of data arguments?
670 if (numConversions > numDataArgs) {
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000671 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
672 LastConversionIdx);
Ted Kremenek081ed872007-08-14 17:39:48 +0000673
674 Diag(Loc, diag::warn_printf_insufficient_data_args,
Ted Kremenek6077e2f2008-07-25 22:03:03 +0000675 OrigFormatExpr->getSourceRange());
Ted Kremenek081ed872007-08-14 17:39:48 +0000676 }
677 // CHECK: Does the number of data arguments exceed the number of
678 // format conversions in the format string?
679 else if (numConversions < numDataArgs)
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000680 Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(),
Ted Kremenek6077e2f2008-07-25 22:03:03 +0000681 diag::warn_printf_too_many_data_args,
682 OrigFormatExpr->getSourceRange());
Ted Kremenek081ed872007-08-14 17:39:48 +0000683 }
684}
Ted Kremenek45925ab2007-08-17 16:46:58 +0000685
686//===--- CHECK: Return Address of Stack Variable --------------------------===//
687
688static DeclRefExpr* EvalVal(Expr *E);
689static DeclRefExpr* EvalAddr(Expr* E);
690
691/// CheckReturnStackAddr - Check if a return statement returns the address
692/// of a stack variable.
693void
694Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
695 SourceLocation ReturnLoc) {
Chris Lattner7a48d9c2008-02-13 01:02:39 +0000696
Ted Kremenek45925ab2007-08-17 16:46:58 +0000697 // Perform checking for returned stack addresses.
698 if (lhsType->isPointerType()) {
699 if (DeclRefExpr *DR = EvalAddr(RetValExp))
700 Diag(DR->getLocStart(), diag::warn_ret_stack_addr,
701 DR->getDecl()->getIdentifier()->getName(),
702 RetValExp->getSourceRange());
703 }
704 // Perform checking for stack values returned by reference.
705 else if (lhsType->isReferenceType()) {
Ted Kremenek1456f202007-08-27 16:39:17 +0000706 // Check for an implicit cast to a reference.
707 if (ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(RetValExp))
708 if (DeclRefExpr *DR = EvalVal(I->getSubExpr()))
709 Diag(DR->getLocStart(), diag::warn_ret_stack_ref,
710 DR->getDecl()->getIdentifier()->getName(),
711 RetValExp->getSourceRange());
Ted Kremenek45925ab2007-08-17 16:46:58 +0000712 }
713}
714
715/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
716/// check if the expression in a return statement evaluates to an address
717/// to a location on the stack. The recursion is used to traverse the
718/// AST of the return expression, with recursion backtracking when we
719/// encounter a subexpression that (1) clearly does not lead to the address
720/// of a stack variable or (2) is something we cannot determine leads to
721/// the address of a stack variable based on such local checking.
722///
Ted Kremenekda1300a2007-08-28 17:02:55 +0000723/// EvalAddr processes expressions that are pointers that are used as
724/// references (and not L-values). EvalVal handles all other values.
Ted Kremenek45925ab2007-08-17 16:46:58 +0000725/// At the base case of the recursion is a check for a DeclRefExpr* in
726/// the refers to a stack variable.
727///
728/// This implementation handles:
729///
730/// * pointer-to-pointer casts
731/// * implicit conversions from array references to pointers
732/// * taking the address of fields
733/// * arbitrary interplay between "&" and "*" operators
734/// * pointer arithmetic from an address of a stack variable
735/// * taking the address of an array element where the array is on the stack
736static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek45925ab2007-08-17 16:46:58 +0000737 // We should only be called for evaluating pointer expressions.
Chris Lattner68d88f02007-12-28 05:31:15 +0000738 assert((E->getType()->isPointerType() ||
Ted Kremenek42730c52008-01-07 19:49:32 +0000739 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner68d88f02007-12-28 05:31:15 +0000740 "EvalAddr only works on pointers");
Ted Kremenek45925ab2007-08-17 16:46:58 +0000741
742 // Our "symbolic interpreter" is just a dispatch off the currently
743 // viewed AST node. We then recursively traverse the AST by calling
744 // EvalAddr and EvalVal appropriately.
745 switch (E->getStmtClass()) {
Chris Lattner68d88f02007-12-28 05:31:15 +0000746 case Stmt::ParenExprClass:
747 // Ignore parentheses.
748 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek45925ab2007-08-17 16:46:58 +0000749
Chris Lattner68d88f02007-12-28 05:31:15 +0000750 case Stmt::UnaryOperatorClass: {
751 // The only unary operator that make sense to handle here
752 // is AddrOf. All others don't make sense as pointers.
753 UnaryOperator *U = cast<UnaryOperator>(E);
Ted Kremenek45925ab2007-08-17 16:46:58 +0000754
Chris Lattner68d88f02007-12-28 05:31:15 +0000755 if (U->getOpcode() == UnaryOperator::AddrOf)
756 return EvalVal(U->getSubExpr());
757 else
Ted Kremenek45925ab2007-08-17 16:46:58 +0000758 return NULL;
759 }
Chris Lattner68d88f02007-12-28 05:31:15 +0000760
761 case Stmt::BinaryOperatorClass: {
762 // Handle pointer arithmetic. All other binary operators are not valid
763 // in this context.
764 BinaryOperator *B = cast<BinaryOperator>(E);
765 BinaryOperator::Opcode op = B->getOpcode();
766
767 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
768 return NULL;
769
770 Expr *Base = B->getLHS();
771
772 // Determine which argument is the real pointer base. It could be
773 // the RHS argument instead of the LHS.
774 if (!Base->getType()->isPointerType()) Base = B->getRHS();
775
776 assert (Base->getType()->isPointerType());
777 return EvalAddr(Base);
778 }
779
780 // For conditional operators we need to see if either the LHS or RHS are
781 // valid DeclRefExpr*s. If one of them is valid, we return it.
782 case Stmt::ConditionalOperatorClass: {
783 ConditionalOperator *C = cast<ConditionalOperator>(E);
784
785 // Handle the GNU extension for missing LHS.
786 if (Expr *lhsExpr = C->getLHS())
787 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
788 return LHS;
789
790 return EvalAddr(C->getRHS());
791 }
792
Ted Kremenekea19edd2008-08-07 00:49:01 +0000793 // For casts, we need to handle conversions from arrays to
794 // pointer values, and pointer-to-pointer conversions.
795 case Stmt::CastExprClass:
Chris Lattner68d88f02007-12-28 05:31:15 +0000796 case Stmt::ImplicitCastExprClass: {
Chris Lattner68d88f02007-12-28 05:31:15 +0000797
Ted Kremenekea19edd2008-08-07 00:49:01 +0000798 Expr* SubExpr;
799
800 if (ImplicitCastExpr *IE = dyn_cast<ImplicitCastExpr>(E))
801 SubExpr = IE->getSubExpr();
Chris Lattner68d88f02007-12-28 05:31:15 +0000802 else
Ted Kremenekea19edd2008-08-07 00:49:01 +0000803 SubExpr = cast<CastExpr>(E)->getSubExpr();
804
805 QualType T = SubExpr->getType();
806
807 if (T->isPointerType() || T->isObjCQualifiedIdType())
808 return EvalAddr(SubExpr);
809 else if (T->isArrayType())
Chris Lattner68d88f02007-12-28 05:31:15 +0000810 return EvalVal(SubExpr);
Chris Lattner68d88f02007-12-28 05:31:15 +0000811 else
Ted Kremenekea19edd2008-08-07 00:49:01 +0000812 return 0;
Chris Lattner68d88f02007-12-28 05:31:15 +0000813 }
814
815 // C++ casts. For dynamic casts, static casts, and const casts, we
816 // are always converting from a pointer-to-pointer, so we just blow
817 // through the cast. In the case the dynamic cast doesn't fail
818 // (and return NULL), we take the conservative route and report cases
819 // where we return the address of a stack variable. For Reinterpre
820 case Stmt::CXXCastExprClass: {
821 CXXCastExpr *C = cast<CXXCastExpr>(E);
822
823 if (C->getOpcode() == CXXCastExpr::ReinterpretCast) {
824 Expr *S = C->getSubExpr();
825 if (S->getType()->isPointerType())
826 return EvalAddr(S);
827 else
828 return NULL;
829 }
830 else
831 return EvalAddr(C->getSubExpr());
832 }
833
834 // Everything else: we simply don't reason about them.
835 default:
836 return NULL;
837 }
Ted Kremenek45925ab2007-08-17 16:46:58 +0000838}
839
840
841/// EvalVal - This function is complements EvalAddr in the mutual recursion.
842/// See the comments for EvalAddr for more details.
843static DeclRefExpr* EvalVal(Expr *E) {
844
Ted Kremenekda1300a2007-08-28 17:02:55 +0000845 // We should only be called for evaluating non-pointer expressions, or
846 // expressions with a pointer type that are not used as references but instead
847 // are l-values (e.g., DeclRefExpr with a pointer type).
848
Ted Kremenek45925ab2007-08-17 16:46:58 +0000849 // Our "symbolic interpreter" is just a dispatch off the currently
850 // viewed AST node. We then recursively traverse the AST by calling
851 // EvalAddr and EvalVal appropriately.
852 switch (E->getStmtClass()) {
Ted Kremenek45925ab2007-08-17 16:46:58 +0000853 case Stmt::DeclRefExprClass: {
854 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
855 // at code that refers to a variable's name. We check if it has local
856 // storage within the function, and if so, return the expression.
857 DeclRefExpr *DR = cast<DeclRefExpr>(E);
858
859 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
860 if(V->hasLocalStorage()) return DR;
861
862 return NULL;
863 }
864
865 case Stmt::ParenExprClass:
866 // Ignore parentheses.
867 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
868
869 case Stmt::UnaryOperatorClass: {
870 // The only unary operator that make sense to handle here
871 // is Deref. All others don't resolve to a "name." This includes
872 // handling all sorts of rvalues passed to a unary operator.
873 UnaryOperator *U = cast<UnaryOperator>(E);
874
875 if (U->getOpcode() == UnaryOperator::Deref)
876 return EvalAddr(U->getSubExpr());
877
878 return NULL;
879 }
880
881 case Stmt::ArraySubscriptExprClass: {
882 // Array subscripts are potential references to data on the stack. We
883 // retrieve the DeclRefExpr* for the array variable if it indeed
884 // has local storage.
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000885 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek45925ab2007-08-17 16:46:58 +0000886 }
887
888 case Stmt::ConditionalOperatorClass: {
889 // For conditional operators we need to see if either the LHS or RHS are
890 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
891 ConditionalOperator *C = cast<ConditionalOperator>(E);
892
Anders Carlsson37365fc2007-11-30 19:04:31 +0000893 // Handle the GNU extension for missing LHS.
894 if (Expr *lhsExpr = C->getLHS())
895 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
896 return LHS;
897
898 return EvalVal(C->getRHS());
Ted Kremenek45925ab2007-08-17 16:46:58 +0000899 }
900
901 // Accesses to members are potential references to data on the stack.
902 case Stmt::MemberExprClass: {
903 MemberExpr *M = cast<MemberExpr>(E);
904
905 // Check for indirect access. We only want direct field accesses.
906 if (!M->isArrow())
907 return EvalVal(M->getBase());
908 else
909 return NULL;
910 }
911
912 // Everything else: we simply don't reason about them.
913 default:
914 return NULL;
915 }
916}
Ted Kremenek30c66752007-11-25 00:58:00 +0000917
918//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
919
920/// Check for comparisons of floating point operands using != and ==.
921/// Issue a warning if these are no self-comparisons, as they are not likely
922/// to do what the programmer intended.
923void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
924 bool EmitWarning = true;
925
Ted Kremenek87e30c52008-01-17 16:57:34 +0000926 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek24c61682008-01-17 17:55:13 +0000927 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek30c66752007-11-25 00:58:00 +0000928
929 // Special case: check for x == x (which is OK).
930 // Do not emit warnings for such cases.
931 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
932 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
933 if (DRL->getDecl() == DRR->getDecl())
934 EmitWarning = false;
935
Ted Kremenek33159832007-11-29 00:59:04 +0000936
937 // Special case: check for comparisons against literals that can be exactly
938 // represented by APFloat. In such cases, do not emit a warning. This
939 // is a heuristic: often comparison against such literals are used to
940 // detect if a value in a variable has not changed. This clearly can
941 // lead to false negatives.
942 if (EmitWarning) {
943 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
944 if (FLL->isExact())
945 EmitWarning = false;
946 }
947 else
948 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
949 if (FLR->isExact())
950 EmitWarning = false;
951 }
952 }
953
Ted Kremenek30c66752007-11-25 00:58:00 +0000954 // Check for comparisons with builtin types.
955 if (EmitWarning)
956 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
957 if (isCallBuiltin(CL))
958 EmitWarning = false;
959
960 if (EmitWarning)
961 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
962 if (isCallBuiltin(CR))
963 EmitWarning = false;
964
965 // Emit the diagnostic.
966 if (EmitWarning)
967 Diag(loc, diag::warn_floatingpoint_eq,
968 lex->getSourceRange(),rex->getSourceRange());
969}