blob: dfd8f92cdc55630fe99cdac870722f573adde5b6 [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"
18#include "clang/AST/Expr.h"
Ted Kremenek1c1700f2007-08-20 16:18:38 +000019#include "clang/AST/ExprCXX.h"
Ted Kremenek225a14c2008-06-16 18:00:42 +000020#include "clang/AST/ExprObjC.h"
Chris Lattner2e64c072007-08-10 20:18:51 +000021#include "clang/Lex/Preprocessor.h"
22#include "clang/Lex/LiteralSupport.h"
23#include "clang/Basic/SourceManager.h"
24#include "clang/Basic/Diagnostic.h"
25#include "clang/Basic/LangOptions.h"
26#include "clang/Basic/TargetInfo.h"
Eli Friedman798e4d52008-05-16 17:51:27 +000027#include "llvm/ADT/OwningPtr.h"
Chris Lattner2e64c072007-08-10 20:18:51 +000028#include "llvm/ADT/SmallString.h"
29#include "llvm/ADT/StringExtras.h"
Ted Kremenek30c66752007-11-25 00:58:00 +000030#include "SemaUtil.h"
Chris Lattner2e64c072007-08-10 20:18:51 +000031using namespace clang;
32
33/// CheckFunctionCall - Check a direct function call for various correctness
34/// and safety properties not strictly enforced by the C type system.
Eli Friedmand0e9d092008-05-14 19:38:39 +000035Action::ExprResult
Eli Friedman798e4d52008-05-16 17:51:27 +000036Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCallRaw) {
37 llvm::OwningPtr<CallExpr> TheCall(TheCallRaw);
Chris Lattner2e64c072007-08-10 20:18:51 +000038 // Get the IdentifierInfo* for the called function.
39 IdentifierInfo *FnInfo = FDecl->getIdentifier();
40
Chris Lattnerf22a8502007-12-19 23:59:04 +000041 switch (FnInfo->getBuiltinID()) {
42 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner83bd5eb2007-12-28 05:29:59 +000043 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner7c8d1af2007-12-20 00:26:33 +000044 "Wrong # arguments to builtin CFStringMakeConstantString");
Eli Friedman798e4d52008-05-16 17:51:27 +000045 if (CheckBuiltinCFStringArgument(TheCall->getArg(0)))
Eli Friedmand0e9d092008-05-14 19:38:39 +000046 return true;
Eli Friedman798e4d52008-05-16 17:51:27 +000047 return TheCall.take();
Ted Kremenek7a0654c2008-07-09 17:58:53 +000048 case Builtin::BI__builtin_stdarg_start:
Chris Lattnerf22a8502007-12-19 23:59:04 +000049 case Builtin::BI__builtin_va_start:
Chris Lattner2a674dc2008-06-30 18:32:54 +000050 if (SemaBuiltinVAStart(TheCall.get()))
Eli Friedmand0e9d092008-05-14 19:38:39 +000051 return true;
Eli Friedman798e4d52008-05-16 17:51:27 +000052 return TheCall.take();
Chris Lattner7c8d1af2007-12-20 00:26:33 +000053 case Builtin::BI__builtin_isgreater:
54 case Builtin::BI__builtin_isgreaterequal:
55 case Builtin::BI__builtin_isless:
56 case Builtin::BI__builtin_islessequal:
57 case Builtin::BI__builtin_islessgreater:
58 case Builtin::BI__builtin_isunordered:
Eli Friedman798e4d52008-05-16 17:51:27 +000059 if (SemaBuiltinUnorderedCompare(TheCall.get()))
Eli Friedmand0e9d092008-05-14 19:38:39 +000060 return true;
Eli Friedman798e4d52008-05-16 17:51:27 +000061 return TheCall.take();
Eli Friedman8c50c622008-05-20 08:23:37 +000062 case Builtin::BI__builtin_return_address:
63 case Builtin::BI__builtin_frame_address:
64 if (SemaBuiltinStackAddress(TheCall.get()))
65 return true;
66 return TheCall.take();
Eli Friedmand0e9d092008-05-14 19:38:39 +000067 case Builtin::BI__builtin_shufflevector:
Eli Friedman798e4d52008-05-16 17:51:27 +000068 return SemaBuiltinShuffleVector(TheCall.get());
Daniel Dunbar5b0de852008-07-21 22:59:13 +000069 case Builtin::BI__builtin_prefetch:
70 if (SemaBuiltinPrefetch(TheCall.get()))
71 return true;
72 return TheCall.take();
Anders Carlssone7e7aa22007-08-17 05:31:46 +000073 }
74
Chris Lattner2e64c072007-08-10 20:18:51 +000075 // Search the KnownFunctionIDs for the identifier.
76 unsigned i = 0, e = id_num_known_functions;
Ted Kremenek081ed872007-08-14 17:39:48 +000077 for (; i != e; ++i) { if (KnownFunctionIDs[i] == FnInfo) break; }
Eli Friedman798e4d52008-05-16 17:51:27 +000078 if (i == e) return TheCall.take();
Chris Lattner2e64c072007-08-10 20:18:51 +000079
80 // Printf checking.
81 if (i <= id_vprintf) {
Ted Kremenek081ed872007-08-14 17:39:48 +000082 // Retrieve the index of the format string parameter and determine
83 // if the function is passed a va_arg argument.
Chris Lattner2e64c072007-08-10 20:18:51 +000084 unsigned format_idx = 0;
Ted Kremenek081ed872007-08-14 17:39:48 +000085 bool HasVAListArg = false;
86
Chris Lattner2e64c072007-08-10 20:18:51 +000087 switch (i) {
Chris Lattnerf22a8502007-12-19 23:59:04 +000088 default: assert(false && "No format string argument index.");
89 case id_printf: format_idx = 0; break;
90 case id_fprintf: format_idx = 1; break;
91 case id_sprintf: format_idx = 1; break;
92 case id_snprintf: format_idx = 2; break;
93 case id_asprintf: format_idx = 1; break;
Ted Kremenek225a14c2008-06-16 18:00:42 +000094 case id_NSLog: format_idx = 0; break;
Chris Lattnerf22a8502007-12-19 23:59:04 +000095 case id_vsnprintf: format_idx = 2; HasVAListArg = true; break;
96 case id_vasprintf: format_idx = 1; HasVAListArg = true; break;
97 case id_vfprintf: format_idx = 1; HasVAListArg = true; break;
98 case id_vsprintf: format_idx = 1; HasVAListArg = true; break;
99 case id_vprintf: format_idx = 0; HasVAListArg = true; break;
Ted Kremenek081ed872007-08-14 17:39:48 +0000100 }
101
Eli Friedman798e4d52008-05-16 17:51:27 +0000102 CheckPrintfArguments(TheCall.get(), HasVAListArg, format_idx);
Chris Lattner2e64c072007-08-10 20:18:51 +0000103 }
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000104
Eli Friedman798e4d52008-05-16 17:51:27 +0000105 return TheCall.take();
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000106}
107
108/// CheckBuiltinCFStringArgument - Checks that the argument to the builtin
109/// CFString constructor is correct
Chris Lattnerda050402007-08-25 05:30:33 +0000110bool Sema::CheckBuiltinCFStringArgument(Expr* Arg) {
Chris Lattner7a48d9c2008-02-13 01:02:39 +0000111 Arg = Arg->IgnoreParenCasts();
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000112
113 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
114
115 if (!Literal || Literal->isWide()) {
116 Diag(Arg->getLocStart(),
117 diag::err_cfstring_literal_not_string_constant,
118 Arg->getSourceRange());
Anders Carlsson3e9b43b2007-08-17 15:44:17 +0000119 return true;
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000120 }
121
122 const char *Data = Literal->getStrData();
123 unsigned Length = Literal->getByteLength();
124
125 for (unsigned i = 0; i < Length; ++i) {
126 if (!isascii(Data[i])) {
127 Diag(PP.AdvanceToTokenCharacter(Arg->getLocStart(), i + 1),
128 diag::warn_cfstring_literal_contains_non_ascii_character,
129 Arg->getSourceRange());
130 break;
131 }
132
133 if (!Data[i]) {
134 Diag(PP.AdvanceToTokenCharacter(Arg->getLocStart(), i + 1),
135 diag::warn_cfstring_literal_contains_nul_character,
136 Arg->getSourceRange());
137 break;
138 }
139 }
140
Anders Carlsson3e9b43b2007-08-17 15:44:17 +0000141 return false;
Chris Lattner2e64c072007-08-10 20:18:51 +0000142}
143
Chris Lattner3b933692007-12-20 00:05:45 +0000144/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
145/// Emit an error and return true on failure, return false on success.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000146bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
147 Expr *Fn = TheCall->getCallee();
148 if (TheCall->getNumArgs() > 2) {
149 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerf22a8502007-12-19 23:59:04 +0000150 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000151 SourceRange(TheCall->getArg(2)->getLocStart(),
152 (*(TheCall->arg_end()-1))->getLocEnd()));
Chris Lattnerf22a8502007-12-19 23:59:04 +0000153 return true;
154 }
155
Chris Lattner3b933692007-12-20 00:05:45 +0000156 // Determine whether the current function is variadic or not.
157 bool isVariadic;
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000158 if (getCurFunctionDecl())
Chris Lattner3b933692007-12-20 00:05:45 +0000159 isVariadic =
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000160 cast<FunctionTypeProto>(getCurFunctionDecl()->getType())->isVariadic();
Chris Lattnerf22a8502007-12-19 23:59:04 +0000161 else
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000162 isVariadic = getCurMethodDecl()->isVariadic();
Chris Lattnerf22a8502007-12-19 23:59:04 +0000163
Chris Lattner3b933692007-12-20 00:05:45 +0000164 if (!isVariadic) {
Chris Lattnerf22a8502007-12-19 23:59:04 +0000165 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
166 return true;
167 }
168
169 // Verify that the second argument to the builtin is the last argument of the
170 // current function or method.
171 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson924556e2008-02-13 01:22:59 +0000172 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Anders Carlssonc27156b2008-02-11 04:20:54 +0000173
174 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
175 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattnerf22a8502007-12-19 23:59:04 +0000176 // FIXME: This isn't correct for methods (results in bogus warning).
177 // Get the last formal in the current function.
Anders Carlssonc27156b2008-02-11 04:20:54 +0000178 const ParmVarDecl *LastArg;
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000179 if (getCurFunctionDecl())
180 LastArg = *(getCurFunctionDecl()->param_end()-1);
Chris Lattnerf22a8502007-12-19 23:59:04 +0000181 else
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000182 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattnerf22a8502007-12-19 23:59:04 +0000183 SecondArgIsLastNamedArgument = PV == LastArg;
184 }
185 }
186
187 if (!SecondArgIsLastNamedArgument)
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000188 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattnerf22a8502007-12-19 23:59:04 +0000189 diag::warn_second_parameter_of_va_start_not_last_named_argument);
190 return false;
Eli Friedman8c50c622008-05-20 08:23:37 +0000191}
Chris Lattnerf22a8502007-12-19 23:59:04 +0000192
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000193/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
194/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000195bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
196 if (TheCall->getNumArgs() < 2)
197 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args);
198 if (TheCall->getNumArgs() > 2)
199 return Diag(TheCall->getArg(2)->getLocStart(),
200 diag::err_typecheck_call_too_many_args,
201 SourceRange(TheCall->getArg(2)->getLocStart(),
202 (*(TheCall->arg_end()-1))->getLocEnd()));
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000203
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000204 Expr *OrigArg0 = TheCall->getArg(0);
205 Expr *OrigArg1 = TheCall->getArg(1);
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000206
207 // Do standard promotions between the two arguments, returning their common
208 // type.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000209 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000210
211 // If the common type isn't a real floating type, then the arguments were
212 // invalid for this operation.
213 if (!Res->isRealFloatingType())
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000214 return Diag(OrigArg0->getLocStart(),
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000215 diag::err_typecheck_call_invalid_ordered_compare,
216 OrigArg0->getType().getAsString(),
217 OrigArg1->getType().getAsString(),
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000218 SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd()));
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000219
220 return false;
221}
222
Eli Friedman8c50c622008-05-20 08:23:37 +0000223bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) {
224 // The signature for these builtins is exact; the only thing we need
225 // to check is that the argument is a constant.
226 SourceLocation Loc;
Chris Lattner941c0102008-08-10 02:05:13 +0000227 if (!TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc))
Eli Friedman8c50c622008-05-20 08:23:37 +0000228 return Diag(Loc, diag::err_stack_const_level, TheCall->getSourceRange());
Chris Lattner941c0102008-08-10 02:05:13 +0000229
Eli Friedman8c50c622008-05-20 08:23:37 +0000230 return false;
231}
232
Eli Friedmand0e9d092008-05-14 19:38:39 +0000233/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
234// This is declared to take (...), so we have to check everything.
235Action::ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
236 if (TheCall->getNumArgs() < 3)
237 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args,
238 TheCall->getSourceRange());
239
240 QualType FAType = TheCall->getArg(0)->getType();
241 QualType SAType = TheCall->getArg(1)->getType();
242
243 if (!FAType->isVectorType() || !SAType->isVectorType()) {
244 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector,
245 SourceRange(TheCall->getArg(0)->getLocStart(),
246 TheCall->getArg(1)->getLocEnd()));
Eli Friedmand0e9d092008-05-14 19:38:39 +0000247 return true;
248 }
249
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000250 if (Context.getCanonicalType(FAType).getUnqualifiedType() !=
251 Context.getCanonicalType(SAType).getUnqualifiedType()) {
Eli Friedmand0e9d092008-05-14 19:38:39 +0000252 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector,
253 SourceRange(TheCall->getArg(0)->getLocStart(),
254 TheCall->getArg(1)->getLocEnd()));
Eli Friedmand0e9d092008-05-14 19:38:39 +0000255 return true;
256 }
257
258 unsigned numElements = FAType->getAsVectorType()->getNumElements();
259 if (TheCall->getNumArgs() != numElements+2) {
260 if (TheCall->getNumArgs() < numElements+2)
Chris Lattner941c0102008-08-10 02:05:13 +0000261 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args,
262 TheCall->getSourceRange());
263 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args,
264 TheCall->getSourceRange());
Eli Friedmand0e9d092008-05-14 19:38:39 +0000265 }
266
267 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
268 llvm::APSInt Result(32);
Chris Lattner941c0102008-08-10 02:05:13 +0000269 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
270 return Diag(TheCall->getLocStart(),
271 diag::err_shufflevector_nonconstant_argument,
272 TheCall->getArg(i)->getSourceRange());
273
274 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
275 return Diag(TheCall->getLocStart(),
276 diag::err_shufflevector_argument_too_large,
277 TheCall->getArg(i)->getSourceRange());
Eli Friedmand0e9d092008-05-14 19:38:39 +0000278 }
279
280 llvm::SmallVector<Expr*, 32> exprs;
281
Chris Lattner941c0102008-08-10 02:05:13 +0000282 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand0e9d092008-05-14 19:38:39 +0000283 exprs.push_back(TheCall->getArg(i));
284 TheCall->setArg(i, 0);
285 }
286
Chris Lattner941c0102008-08-10 02:05:13 +0000287 return new ShuffleVectorExpr(exprs.begin(), numElements+2, FAType,
288 TheCall->getCallee()->getLocStart(),
289 TheCall->getRParenLoc());
Eli Friedmand0e9d092008-05-14 19:38:39 +0000290}
Chris Lattnerf22a8502007-12-19 23:59:04 +0000291
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000292/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
293// This is declared to take (const void*, ...) and can take two
294// optional constant int args.
295bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
296 unsigned numArgs = TheCall->getNumArgs();
297 bool res = false;
298
299 if (numArgs > 3) {
300 res |= Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args,
301 TheCall->getSourceRange());
302 }
303
304 // Argument 0 is checked for us and the remaining arguments must be
305 // constant integers.
306 for (unsigned i=1; i<numArgs; ++i) {
307 Expr *Arg = TheCall->getArg(i);
308 QualType RWType = Arg->getType();
309
310 const BuiltinType *BT = RWType->getAsBuiltinType();
311 // FIXME: 32 is wrong, needs to be proper width of Int
312 llvm::APSInt Result(32);
313 if (!BT || BT->getKind() != BuiltinType::Int ||
314 !Arg->isIntegerConstantExpr(Result, Context)) {
315 if (Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument,
316 SourceRange(Arg->getLocStart(), Arg->getLocEnd()))) {
317 res = true;
318 continue;
319 }
320 }
321
322 // FIXME: gcc issues a warning and rewrites these to 0. These
323 // seems especially odd for the third argument since the default
324 // is 3.
325 if (i==1) {
326 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 1)
327 res |= Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_range,
328 "0", "1",
329 SourceRange(Arg->getLocStart(), Arg->getLocEnd()));
330 } else {
331 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3)
332 res |= Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_range,
333 "0", "3",
334 SourceRange(Arg->getLocStart(), Arg->getLocEnd()));
335 }
336 }
337
338 return res;
339}
340
Chris Lattner2e64c072007-08-10 20:18:51 +0000341/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Ted Kremenek081ed872007-08-14 17:39:48 +0000342/// correct use of format strings.
343///
344/// HasVAListArg - A predicate indicating whether the printf-like
345/// function is passed an explicit va_arg argument (e.g., vprintf)
346///
347/// format_idx - The index into Args for the format string.
348///
349/// Improper format strings to functions in the printf family can be
350/// the source of bizarre bugs and very serious security holes. A
351/// good source of information is available in the following paper
352/// (which includes additional references):
Chris Lattner2e64c072007-08-10 20:18:51 +0000353///
354/// FormatGuard: Automatic Protection From printf Format String
355/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremenek081ed872007-08-14 17:39:48 +0000356///
357/// Functionality implemented:
358///
359/// We can statically check the following properties for string
360/// literal format strings for non v.*printf functions (where the
361/// arguments are passed directly):
362//
363/// (1) Are the number of format conversions equal to the number of
364/// data arguments?
365///
366/// (2) Does each format conversion correctly match the type of the
367/// corresponding data argument? (TODO)
368///
369/// Moreover, for all printf functions we can:
370///
371/// (3) Check for a missing format string (when not caught by type checking).
372///
373/// (4) Check for no-operation flags; e.g. using "#" with format
374/// conversion 'c' (TODO)
375///
376/// (5) Check the use of '%n', a major source of security holes.
377///
378/// (6) Check for malformed format conversions that don't specify anything.
379///
380/// (7) Check for empty format strings. e.g: printf("");
381///
382/// (8) Check that the format string is a wide literal.
383///
Ted Kremenekc2804c22008-03-03 16:50:00 +0000384/// (9) Also check the arguments of functions with the __format__ attribute.
385/// (TODO).
386///
Ted Kremenek081ed872007-08-14 17:39:48 +0000387/// All of these checks can be done by parsing the format string.
388///
389/// For now, we ONLY do (1), (3), (5), (6), (7), and (8).
Chris Lattner2e64c072007-08-10 20:18:51 +0000390void
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000391Sema::CheckPrintfArguments(CallExpr *TheCall, bool HasVAListArg,
392 unsigned format_idx) {
393 Expr *Fn = TheCall->getCallee();
394
Ted Kremenek081ed872007-08-14 17:39:48 +0000395 // CHECK: printf-like function is called with no format string.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000396 if (format_idx >= TheCall->getNumArgs()) {
397 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string,
Ted Kremenek081ed872007-08-14 17:39:48 +0000398 Fn->getSourceRange());
399 return;
400 }
401
Chris Lattner7a48d9c2008-02-13 01:02:39 +0000402 Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Chris Lattnere65acc12007-08-25 05:36:18 +0000403
Chris Lattner2e64c072007-08-10 20:18:51 +0000404 // CHECK: format string is not a string literal.
405 //
Ted Kremenek081ed872007-08-14 17:39:48 +0000406 // Dynamically generated format strings are difficult to
407 // automatically vet at compile time. Requiring that format strings
408 // are string literals: (1) permits the checking of format strings by
409 // the compiler and thereby (2) can practically remove the source of
410 // many format string exploits.
Ted Kremenek225a14c2008-06-16 18:00:42 +0000411
412 // Format string can be either ObjC string (e.g. @"%d") or
413 // C string (e.g. "%d")
414 // ObjC string uses the same format specifiers as C string, so we can use
415 // the same format string checking logic for both ObjC and C strings.
416 ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(OrigFormatExpr);
417 StringLiteral *FExpr = NULL;
418
419 if(ObjCFExpr != NULL)
420 FExpr = ObjCFExpr->getString();
421 else
422 FExpr = dyn_cast<StringLiteral>(OrigFormatExpr);
423
Ted Kremenek081ed872007-08-14 17:39:48 +0000424 if (FExpr == NULL) {
Ted Kremenek19398b62007-12-17 19:03:13 +0000425 // For vprintf* functions (i.e., HasVAListArg==true), we add a
426 // special check to see if the format string is a function parameter
427 // of the function calling the printf function. If the function
428 // has an attribute indicating it is a printf-like function, then we
429 // should suppress warnings concerning non-literals being used in a call
430 // to a vprintf function. For example:
431 //
432 // void
433 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...) {
434 // va_list ap;
435 // va_start(ap, fmt);
436 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
437 // ...
438 //
439 //
440 // FIXME: We don't have full attribute support yet, so just check to see
441 // if the argument is a DeclRefExpr that references a parameter. We'll
442 // add proper support for checking the attribute later.
443 if (HasVAListArg)
Chris Lattner3d5a8f32007-12-28 05:38:24 +0000444 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(OrigFormatExpr))
445 if (isa<ParmVarDecl>(DR->getDecl()))
Ted Kremenek19398b62007-12-17 19:03:13 +0000446 return;
447
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000448 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek6077e2f2008-07-25 22:03:03 +0000449 diag::warn_printf_not_string_constant,
450 OrigFormatExpr->getSourceRange());
Ted Kremenek081ed872007-08-14 17:39:48 +0000451 return;
452 }
453
454 // CHECK: is the format string a wide literal?
455 if (FExpr->isWide()) {
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000456 Diag(FExpr->getLocStart(),
Ted Kremenek6077e2f2008-07-25 22:03:03 +0000457 diag::warn_printf_format_string_is_wide_literal,
458 OrigFormatExpr->getSourceRange());
Ted Kremenek081ed872007-08-14 17:39:48 +0000459 return;
460 }
461
462 // Str - The format string. NOTE: this is NOT null-terminated!
463 const char * const Str = FExpr->getStrData();
464
465 // CHECK: empty format string?
466 const unsigned StrLen = FExpr->getByteLength();
467
468 if (StrLen == 0) {
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000469 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string,
Ted Kremenek6077e2f2008-07-25 22:03:03 +0000470 OrigFormatExpr->getSourceRange());
Ted Kremenek081ed872007-08-14 17:39:48 +0000471 return;
472 }
473
474 // We process the format string using a binary state machine. The
475 // current state is stored in CurrentState.
476 enum {
477 state_OrdChr,
478 state_Conversion
479 } CurrentState = state_OrdChr;
480
481 // numConversions - The number of conversions seen so far. This is
482 // incremented as we traverse the format string.
483 unsigned numConversions = 0;
484
485 // numDataArgs - The number of data arguments after the format
486 // string. This can only be determined for non vprintf-like
487 // functions. For those functions, this value is 1 (the sole
488 // va_arg argument).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000489 unsigned numDataArgs = TheCall->getNumArgs()-(format_idx+1);
Ted Kremenek081ed872007-08-14 17:39:48 +0000490
491 // Inspect the format string.
492 unsigned StrIdx = 0;
493
494 // LastConversionIdx - Index within the format string where we last saw
495 // a '%' character that starts a new format conversion.
496 unsigned LastConversionIdx = 0;
497
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000498 for (; StrIdx < StrLen; ++StrIdx) {
Chris Lattner3d5a8f32007-12-28 05:38:24 +0000499
Ted Kremenek081ed872007-08-14 17:39:48 +0000500 // Is the number of detected conversion conversions greater than
501 // the number of matching data arguments? If so, stop.
502 if (!HasVAListArg && numConversions > numDataArgs) break;
503
504 // Handle "\0"
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000505 if (Str[StrIdx] == '\0') {
Ted Kremenek081ed872007-08-14 17:39:48 +0000506 // The string returned by getStrData() is not null-terminated,
507 // so the presence of a null character is likely an error.
Chris Lattner3d5a8f32007-12-28 05:38:24 +0000508 Diag(PP.AdvanceToTokenCharacter(FExpr->getLocStart(), StrIdx+1),
509 diag::warn_printf_format_string_contains_null_char,
Ted Kremenek6077e2f2008-07-25 22:03:03 +0000510 OrigFormatExpr->getSourceRange());
Ted Kremenek081ed872007-08-14 17:39:48 +0000511 return;
512 }
513
514 // Ordinary characters (not processing a format conversion).
515 if (CurrentState == state_OrdChr) {
516 if (Str[StrIdx] == '%') {
517 CurrentState = state_Conversion;
518 LastConversionIdx = StrIdx;
519 }
520 continue;
521 }
522
523 // Seen '%'. Now processing a format conversion.
524 switch (Str[StrIdx]) {
Chris Lattner68d88f02007-12-28 05:31:15 +0000525 // Handle dynamic precision or width specifier.
526 case '*': {
527 ++numConversions;
528
529 if (!HasVAListArg && numConversions > numDataArgs) {
Chris Lattner68d88f02007-12-28 05:31:15 +0000530 SourceLocation Loc = FExpr->getLocStart();
531 Loc = PP.AdvanceToTokenCharacter(Loc, StrIdx+1);
Ted Kremenek035d8792007-10-12 20:51:52 +0000532
Ted Kremenek035d8792007-10-12 20:51:52 +0000533 if (Str[StrIdx-1] == '.')
Chris Lattner68d88f02007-12-28 05:31:15 +0000534 Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg,
Ted Kremenek6077e2f2008-07-25 22:03:03 +0000535 OrigFormatExpr->getSourceRange());
Ted Kremenek035d8792007-10-12 20:51:52 +0000536 else
Chris Lattner68d88f02007-12-28 05:31:15 +0000537 Diag(Loc, diag::warn_printf_asterisk_width_missing_arg,
Ted Kremenek6077e2f2008-07-25 22:03:03 +0000538 OrigFormatExpr->getSourceRange());
Ted Kremenek035d8792007-10-12 20:51:52 +0000539
Chris Lattner68d88f02007-12-28 05:31:15 +0000540 // Don't do any more checking. We'll just emit spurious errors.
541 return;
Ted Kremenek035d8792007-10-12 20:51:52 +0000542 }
Chris Lattner68d88f02007-12-28 05:31:15 +0000543
544 // Perform type checking on width/precision specifier.
545 Expr *E = TheCall->getArg(format_idx+numConversions);
546 if (const BuiltinType *BT = E->getType()->getAsBuiltinType())
547 if (BT->getKind() == BuiltinType::Int)
548 break;
Ted Kremenek081ed872007-08-14 17:39:48 +0000549
Chris Lattner68d88f02007-12-28 05:31:15 +0000550 SourceLocation Loc =
551 PP.AdvanceToTokenCharacter(FExpr->getLocStart(), StrIdx+1);
552
553 if (Str[StrIdx-1] == '.')
554 Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type,
555 E->getType().getAsString(), E->getSourceRange());
556 else
557 Diag(Loc, diag::warn_printf_asterisk_width_wrong_type,
558 E->getType().getAsString(), E->getSourceRange());
559
560 break;
561 }
562
563 // Characters which can terminate a format conversion
564 // (e.g. "%d"). Characters that specify length modifiers or
565 // other flags are handled by the default case below.
566 //
567 // FIXME: additional checks will go into the following cases.
568 case 'i':
569 case 'd':
570 case 'o':
571 case 'u':
572 case 'x':
573 case 'X':
574 case 'D':
575 case 'O':
576 case 'U':
577 case 'e':
578 case 'E':
579 case 'f':
580 case 'F':
581 case 'g':
582 case 'G':
583 case 'a':
584 case 'A':
585 case 'c':
586 case 'C':
587 case 'S':
588 case 's':
589 case 'p':
590 ++numConversions;
591 CurrentState = state_OrdChr;
592 break;
593
594 // CHECK: Are we using "%n"? Issue a warning.
595 case 'n': {
596 ++numConversions;
597 CurrentState = state_OrdChr;
598 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
599 LastConversionIdx+1);
600
Ted Kremenek6077e2f2008-07-25 22:03:03 +0000601 Diag(Loc, diag::warn_printf_write_back, OrigFormatExpr->getSourceRange());
Chris Lattner68d88f02007-12-28 05:31:15 +0000602 break;
603 }
Ted Kremenek225a14c2008-06-16 18:00:42 +0000604
605 // Handle "%@"
606 case '@':
607 // %@ is allowed in ObjC format strings only.
608 if(ObjCFExpr != NULL)
609 CurrentState = state_OrdChr;
610 else {
611 // Issue a warning: invalid format conversion.
612 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
613 LastConversionIdx+1);
614
615 Diag(Loc, diag::warn_printf_invalid_conversion,
616 std::string(Str+LastConversionIdx,
617 Str+std::min(LastConversionIdx+2, StrLen)),
Ted Kremenek6077e2f2008-07-25 22:03:03 +0000618 OrigFormatExpr->getSourceRange());
Ted Kremenek225a14c2008-06-16 18:00:42 +0000619 }
620 ++numConversions;
621 break;
622
Chris Lattner68d88f02007-12-28 05:31:15 +0000623 // Handle "%%"
624 case '%':
625 // Sanity check: Was the first "%" character the previous one?
626 // If not, we will assume that we have a malformed format
627 // conversion, and that the current "%" character is the start
628 // of a new conversion.
629 if (StrIdx - LastConversionIdx == 1)
630 CurrentState = state_OrdChr;
631 else {
632 // Issue a warning: invalid format conversion.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000633 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
634 LastConversionIdx+1);
Chris Lattner68d88f02007-12-28 05:31:15 +0000635
636 Diag(Loc, diag::warn_printf_invalid_conversion,
637 std::string(Str+LastConversionIdx, Str+StrIdx),
Ted Kremenek6077e2f2008-07-25 22:03:03 +0000638 OrigFormatExpr->getSourceRange());
Chris Lattner68d88f02007-12-28 05:31:15 +0000639
640 // This conversion is broken. Advance to the next format
641 // conversion.
642 LastConversionIdx = StrIdx;
643 ++numConversions;
Ted Kremenek081ed872007-08-14 17:39:48 +0000644 }
Chris Lattner68d88f02007-12-28 05:31:15 +0000645 break;
Ted Kremenek081ed872007-08-14 17:39:48 +0000646
Chris Lattner68d88f02007-12-28 05:31:15 +0000647 default:
648 // This case catches all other characters: flags, widths, etc.
649 // We should eventually process those as well.
650 break;
Ted Kremenek081ed872007-08-14 17:39:48 +0000651 }
652 }
653
654 if (CurrentState == state_Conversion) {
655 // Issue a warning: invalid format conversion.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000656 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
657 LastConversionIdx+1);
Ted Kremenek081ed872007-08-14 17:39:48 +0000658
659 Diag(Loc, diag::warn_printf_invalid_conversion,
Chris Lattner6f65d202007-08-26 17:38:22 +0000660 std::string(Str+LastConversionIdx,
661 Str+std::min(LastConversionIdx+2, StrLen)),
Ted Kremenek6077e2f2008-07-25 22:03:03 +0000662 OrigFormatExpr->getSourceRange());
Ted Kremenek081ed872007-08-14 17:39:48 +0000663 return;
664 }
665
666 if (!HasVAListArg) {
667 // CHECK: Does the number of format conversions exceed the number
668 // of data arguments?
669 if (numConversions > numDataArgs) {
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000670 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
671 LastConversionIdx);
Ted Kremenek081ed872007-08-14 17:39:48 +0000672
673 Diag(Loc, diag::warn_printf_insufficient_data_args,
Ted Kremenek6077e2f2008-07-25 22:03:03 +0000674 OrigFormatExpr->getSourceRange());
Ted Kremenek081ed872007-08-14 17:39:48 +0000675 }
676 // CHECK: Does the number of data arguments exceed the number of
677 // format conversions in the format string?
678 else if (numConversions < numDataArgs)
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000679 Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(),
Ted Kremenek6077e2f2008-07-25 22:03:03 +0000680 diag::warn_printf_too_many_data_args,
681 OrigFormatExpr->getSourceRange());
Ted Kremenek081ed872007-08-14 17:39:48 +0000682 }
683}
Ted Kremenek45925ab2007-08-17 16:46:58 +0000684
685//===--- CHECK: Return Address of Stack Variable --------------------------===//
686
687static DeclRefExpr* EvalVal(Expr *E);
688static DeclRefExpr* EvalAddr(Expr* E);
689
690/// CheckReturnStackAddr - Check if a return statement returns the address
691/// of a stack variable.
692void
693Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
694 SourceLocation ReturnLoc) {
Chris Lattner7a48d9c2008-02-13 01:02:39 +0000695
Ted Kremenek45925ab2007-08-17 16:46:58 +0000696 // Perform checking for returned stack addresses.
697 if (lhsType->isPointerType()) {
698 if (DeclRefExpr *DR = EvalAddr(RetValExp))
699 Diag(DR->getLocStart(), diag::warn_ret_stack_addr,
700 DR->getDecl()->getIdentifier()->getName(),
701 RetValExp->getSourceRange());
702 }
703 // Perform checking for stack values returned by reference.
704 else if (lhsType->isReferenceType()) {
Ted Kremenek1456f202007-08-27 16:39:17 +0000705 // Check for an implicit cast to a reference.
706 if (ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(RetValExp))
707 if (DeclRefExpr *DR = EvalVal(I->getSubExpr()))
708 Diag(DR->getLocStart(), diag::warn_ret_stack_ref,
709 DR->getDecl()->getIdentifier()->getName(),
710 RetValExp->getSourceRange());
Ted Kremenek45925ab2007-08-17 16:46:58 +0000711 }
712}
713
714/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
715/// check if the expression in a return statement evaluates to an address
716/// to a location on the stack. The recursion is used to traverse the
717/// AST of the return expression, with recursion backtracking when we
718/// encounter a subexpression that (1) clearly does not lead to the address
719/// of a stack variable or (2) is something we cannot determine leads to
720/// the address of a stack variable based on such local checking.
721///
Ted Kremenekda1300a2007-08-28 17:02:55 +0000722/// EvalAddr processes expressions that are pointers that are used as
723/// references (and not L-values). EvalVal handles all other values.
Ted Kremenek45925ab2007-08-17 16:46:58 +0000724/// At the base case of the recursion is a check for a DeclRefExpr* in
725/// the refers to a stack variable.
726///
727/// This implementation handles:
728///
729/// * pointer-to-pointer casts
730/// * implicit conversions from array references to pointers
731/// * taking the address of fields
732/// * arbitrary interplay between "&" and "*" operators
733/// * pointer arithmetic from an address of a stack variable
734/// * taking the address of an array element where the array is on the stack
735static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek45925ab2007-08-17 16:46:58 +0000736 // We should only be called for evaluating pointer expressions.
Chris Lattner68d88f02007-12-28 05:31:15 +0000737 assert((E->getType()->isPointerType() ||
Ted Kremenek42730c52008-01-07 19:49:32 +0000738 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner68d88f02007-12-28 05:31:15 +0000739 "EvalAddr only works on pointers");
Ted Kremenek45925ab2007-08-17 16:46:58 +0000740
741 // Our "symbolic interpreter" is just a dispatch off the currently
742 // viewed AST node. We then recursively traverse the AST by calling
743 // EvalAddr and EvalVal appropriately.
744 switch (E->getStmtClass()) {
Chris Lattner68d88f02007-12-28 05:31:15 +0000745 case Stmt::ParenExprClass:
746 // Ignore parentheses.
747 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek45925ab2007-08-17 16:46:58 +0000748
Chris Lattner68d88f02007-12-28 05:31:15 +0000749 case Stmt::UnaryOperatorClass: {
750 // The only unary operator that make sense to handle here
751 // is AddrOf. All others don't make sense as pointers.
752 UnaryOperator *U = cast<UnaryOperator>(E);
Ted Kremenek45925ab2007-08-17 16:46:58 +0000753
Chris Lattner68d88f02007-12-28 05:31:15 +0000754 if (U->getOpcode() == UnaryOperator::AddrOf)
755 return EvalVal(U->getSubExpr());
756 else
Ted Kremenek45925ab2007-08-17 16:46:58 +0000757 return NULL;
758 }
Chris Lattner68d88f02007-12-28 05:31:15 +0000759
760 case Stmt::BinaryOperatorClass: {
761 // Handle pointer arithmetic. All other binary operators are not valid
762 // in this context.
763 BinaryOperator *B = cast<BinaryOperator>(E);
764 BinaryOperator::Opcode op = B->getOpcode();
765
766 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
767 return NULL;
768
769 Expr *Base = B->getLHS();
770
771 // Determine which argument is the real pointer base. It could be
772 // the RHS argument instead of the LHS.
773 if (!Base->getType()->isPointerType()) Base = B->getRHS();
774
775 assert (Base->getType()->isPointerType());
776 return EvalAddr(Base);
777 }
778
779 // For conditional operators we need to see if either the LHS or RHS are
780 // valid DeclRefExpr*s. If one of them is valid, we return it.
781 case Stmt::ConditionalOperatorClass: {
782 ConditionalOperator *C = cast<ConditionalOperator>(E);
783
784 // Handle the GNU extension for missing LHS.
785 if (Expr *lhsExpr = C->getLHS())
786 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
787 return LHS;
788
789 return EvalAddr(C->getRHS());
790 }
791
Ted Kremenekea19edd2008-08-07 00:49:01 +0000792 // For casts, we need to handle conversions from arrays to
793 // pointer values, and pointer-to-pointer conversions.
794 case Stmt::CastExprClass:
Chris Lattner68d88f02007-12-28 05:31:15 +0000795 case Stmt::ImplicitCastExprClass: {
Chris Lattner68d88f02007-12-28 05:31:15 +0000796
Ted Kremenekea19edd2008-08-07 00:49:01 +0000797 Expr* SubExpr;
798
799 if (ImplicitCastExpr *IE = dyn_cast<ImplicitCastExpr>(E))
800 SubExpr = IE->getSubExpr();
Chris Lattner68d88f02007-12-28 05:31:15 +0000801 else
Ted Kremenekea19edd2008-08-07 00:49:01 +0000802 SubExpr = cast<CastExpr>(E)->getSubExpr();
803
804 QualType T = SubExpr->getType();
805
806 if (T->isPointerType() || T->isObjCQualifiedIdType())
807 return EvalAddr(SubExpr);
808 else if (T->isArrayType())
Chris Lattner68d88f02007-12-28 05:31:15 +0000809 return EvalVal(SubExpr);
Chris Lattner68d88f02007-12-28 05:31:15 +0000810 else
Ted Kremenekea19edd2008-08-07 00:49:01 +0000811 return 0;
Chris Lattner68d88f02007-12-28 05:31:15 +0000812 }
813
814 // C++ casts. For dynamic casts, static casts, and const casts, we
815 // are always converting from a pointer-to-pointer, so we just blow
816 // through the cast. In the case the dynamic cast doesn't fail
817 // (and return NULL), we take the conservative route and report cases
818 // where we return the address of a stack variable. For Reinterpre
819 case Stmt::CXXCastExprClass: {
820 CXXCastExpr *C = cast<CXXCastExpr>(E);
821
822 if (C->getOpcode() == CXXCastExpr::ReinterpretCast) {
823 Expr *S = C->getSubExpr();
824 if (S->getType()->isPointerType())
825 return EvalAddr(S);
826 else
827 return NULL;
828 }
829 else
830 return EvalAddr(C->getSubExpr());
831 }
832
833 // Everything else: we simply don't reason about them.
834 default:
835 return NULL;
836 }
Ted Kremenek45925ab2007-08-17 16:46:58 +0000837}
838
839
840/// EvalVal - This function is complements EvalAddr in the mutual recursion.
841/// See the comments for EvalAddr for more details.
842static DeclRefExpr* EvalVal(Expr *E) {
843
Ted Kremenekda1300a2007-08-28 17:02:55 +0000844 // We should only be called for evaluating non-pointer expressions, or
845 // expressions with a pointer type that are not used as references but instead
846 // are l-values (e.g., DeclRefExpr with a pointer type).
847
Ted Kremenek45925ab2007-08-17 16:46:58 +0000848 // Our "symbolic interpreter" is just a dispatch off the currently
849 // viewed AST node. We then recursively traverse the AST by calling
850 // EvalAddr and EvalVal appropriately.
851 switch (E->getStmtClass()) {
Ted Kremenek45925ab2007-08-17 16:46:58 +0000852 case Stmt::DeclRefExprClass: {
853 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
854 // at code that refers to a variable's name. We check if it has local
855 // storage within the function, and if so, return the expression.
856 DeclRefExpr *DR = cast<DeclRefExpr>(E);
857
858 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
859 if(V->hasLocalStorage()) return DR;
860
861 return NULL;
862 }
863
864 case Stmt::ParenExprClass:
865 // Ignore parentheses.
866 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
867
868 case Stmt::UnaryOperatorClass: {
869 // The only unary operator that make sense to handle here
870 // is Deref. All others don't resolve to a "name." This includes
871 // handling all sorts of rvalues passed to a unary operator.
872 UnaryOperator *U = cast<UnaryOperator>(E);
873
874 if (U->getOpcode() == UnaryOperator::Deref)
875 return EvalAddr(U->getSubExpr());
876
877 return NULL;
878 }
879
880 case Stmt::ArraySubscriptExprClass: {
881 // Array subscripts are potential references to data on the stack. We
882 // retrieve the DeclRefExpr* for the array variable if it indeed
883 // has local storage.
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000884 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek45925ab2007-08-17 16:46:58 +0000885 }
886
887 case Stmt::ConditionalOperatorClass: {
888 // For conditional operators we need to see if either the LHS or RHS are
889 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
890 ConditionalOperator *C = cast<ConditionalOperator>(E);
891
Anders Carlsson37365fc2007-11-30 19:04:31 +0000892 // Handle the GNU extension for missing LHS.
893 if (Expr *lhsExpr = C->getLHS())
894 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
895 return LHS;
896
897 return EvalVal(C->getRHS());
Ted Kremenek45925ab2007-08-17 16:46:58 +0000898 }
899
900 // Accesses to members are potential references to data on the stack.
901 case Stmt::MemberExprClass: {
902 MemberExpr *M = cast<MemberExpr>(E);
903
904 // Check for indirect access. We only want direct field accesses.
905 if (!M->isArrow())
906 return EvalVal(M->getBase());
907 else
908 return NULL;
909 }
910
911 // Everything else: we simply don't reason about them.
912 default:
913 return NULL;
914 }
915}
Ted Kremenek30c66752007-11-25 00:58:00 +0000916
917//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
918
919/// Check for comparisons of floating point operands using != and ==.
920/// Issue a warning if these are no self-comparisons, as they are not likely
921/// to do what the programmer intended.
922void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
923 bool EmitWarning = true;
924
Ted Kremenek87e30c52008-01-17 16:57:34 +0000925 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek24c61682008-01-17 17:55:13 +0000926 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek30c66752007-11-25 00:58:00 +0000927
928 // Special case: check for x == x (which is OK).
929 // Do not emit warnings for such cases.
930 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
931 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
932 if (DRL->getDecl() == DRR->getDecl())
933 EmitWarning = false;
934
Ted Kremenek33159832007-11-29 00:59:04 +0000935
936 // Special case: check for comparisons against literals that can be exactly
937 // represented by APFloat. In such cases, do not emit a warning. This
938 // is a heuristic: often comparison against such literals are used to
939 // detect if a value in a variable has not changed. This clearly can
940 // lead to false negatives.
941 if (EmitWarning) {
942 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
943 if (FLL->isExact())
944 EmitWarning = false;
945 }
946 else
947 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
948 if (FLR->isExact())
949 EmitWarning = false;
950 }
951 }
952
Ted Kremenek30c66752007-11-25 00:58:00 +0000953 // Check for comparisons with builtin types.
954 if (EmitWarning)
955 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
956 if (isCallBuiltin(CL))
957 EmitWarning = false;
958
959 if (EmitWarning)
960 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
961 if (isCallBuiltin(CR))
962 EmitWarning = false;
963
964 // Emit the diagnostic.
965 if (EmitWarning)
966 Diag(loc, diag::warn_floatingpoint_eq,
967 lex->getSourceRange(),rex->getSourceRange());
968}