blob: 82fa177bdaf21881fca4447b2060fc8571285bd8 [file] [log] [blame]
Chris Lattner59907c42007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-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 Lattner59907c42007-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 Kremenek23245122007-08-20 16:18:38 +000019#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000020#include "clang/AST/ExprObjC.h"
Chris Lattner59907c42007-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 Friedmane8018702008-05-16 17:51:27 +000027#include "llvm/ADT/OwningPtr.h"
Chris Lattner59907c42007-08-10 20:18:51 +000028#include "llvm/ADT/SmallString.h"
29#include "llvm/ADT/StringExtras.h"
Ted Kremenek588e5eb2007-11-25 00:58:00 +000030#include "SemaUtil.h"
Chris Lattner59907c42007-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 Friedmand38617c2008-05-14 19:38:39 +000035Action::ExprResult
Eli Friedmane8018702008-05-16 17:51:27 +000036Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCallRaw) {
37 llvm::OwningPtr<CallExpr> TheCall(TheCallRaw);
Chris Lattner59907c42007-08-10 20:18:51 +000038 // Get the IdentifierInfo* for the called function.
39 IdentifierInfo *FnInfo = FDecl->getIdentifier();
40
Chris Lattner30ce3442007-12-19 23:59:04 +000041 switch (FnInfo->getBuiltinID()) {
42 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +000043 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +000044 "Wrong # arguments to builtin CFStringMakeConstantString");
Eli Friedmane8018702008-05-16 17:51:27 +000045 if (CheckBuiltinCFStringArgument(TheCall->getArg(0)))
Eli Friedmand38617c2008-05-14 19:38:39 +000046 return true;
Eli Friedmane8018702008-05-16 17:51:27 +000047 return TheCall.take();
Ted Kremenek49ff7a12008-07-09 17:58:53 +000048 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +000049 case Builtin::BI__builtin_va_start:
Chris Lattnerb7cfe882008-06-30 18:32:54 +000050 if (SemaBuiltinVAStart(TheCall.get()))
Eli Friedmand38617c2008-05-14 19:38:39 +000051 return true;
Eli Friedmane8018702008-05-16 17:51:27 +000052 return TheCall.take();
Chris Lattner1b9a0792007-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 Friedmane8018702008-05-16 17:51:27 +000059 if (SemaBuiltinUnorderedCompare(TheCall.get()))
Eli Friedmand38617c2008-05-14 19:38:39 +000060 return true;
Eli Friedmane8018702008-05-16 17:51:27 +000061 return TheCall.take();
Eli Friedman6cfda232008-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 Friedmand38617c2008-05-14 19:38:39 +000067 case Builtin::BI__builtin_shufflevector:
Eli Friedmane8018702008-05-16 17:51:27 +000068 return SemaBuiltinShuffleVector(TheCall.get());
Daniel Dunbar4493f792008-07-21 22:59:13 +000069 case Builtin::BI__builtin_prefetch:
70 if (SemaBuiltinPrefetch(TheCall.get()))
71 return true;
72 return TheCall.take();
Anders Carlsson71993dd2007-08-17 05:31:46 +000073 }
74
Chris Lattner59907c42007-08-10 20:18:51 +000075 // Search the KnownFunctionIDs for the identifier.
76 unsigned i = 0, e = id_num_known_functions;
Ted Kremenek71895b92007-08-14 17:39:48 +000077 for (; i != e; ++i) { if (KnownFunctionIDs[i] == FnInfo) break; }
Eli Friedmane8018702008-05-16 17:51:27 +000078 if (i == e) return TheCall.take();
Chris Lattner59907c42007-08-10 20:18:51 +000079
80 // Printf checking.
81 if (i <= id_vprintf) {
Ted Kremenek71895b92007-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 Lattner59907c42007-08-10 20:18:51 +000084 unsigned format_idx = 0;
Ted Kremenek71895b92007-08-14 17:39:48 +000085 bool HasVAListArg = false;
86
Chris Lattner59907c42007-08-10 20:18:51 +000087 switch (i) {
Chris Lattner30ce3442007-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 Kremenek7ff22b22008-06-16 18:00:42 +000094 case id_NSLog: format_idx = 0; break;
Chris Lattner30ce3442007-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 Kremenek71895b92007-08-14 17:39:48 +0000100 }
101
Eli Friedmane8018702008-05-16 17:51:27 +0000102 CheckPrintfArguments(TheCall.get(), HasVAListArg, format_idx);
Chris Lattner59907c42007-08-10 20:18:51 +0000103 }
Anders Carlsson71993dd2007-08-17 05:31:46 +0000104
Eli Friedmane8018702008-05-16 17:51:27 +0000105 return TheCall.take();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000106}
107
108/// CheckBuiltinCFStringArgument - Checks that the argument to the builtin
109/// CFString constructor is correct
Chris Lattnercc6f65d2007-08-25 05:30:33 +0000110bool Sema::CheckBuiltinCFStringArgument(Expr* Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000111 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-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 Carlsson9cdc4d32007-08-17 15:44:17 +0000119 return true;
Anders Carlsson71993dd2007-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 Carlsson9cdc4d32007-08-17 15:44:17 +0000141 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000142}
143
Chris Lattnerc27c6652007-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 Lattner925e60d2007-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 Lattner30ce3442007-12-19 23:59:04 +0000150 diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
Chris Lattner925e60d2007-12-28 05:29:59 +0000151 SourceRange(TheCall->getArg(2)->getLocStart(),
152 (*(TheCall->arg_end()-1))->getLocEnd()));
Chris Lattner30ce3442007-12-19 23:59:04 +0000153 return true;
154 }
155
Chris Lattnerc27c6652007-12-20 00:05:45 +0000156 // Determine whether the current function is variadic or not.
157 bool isVariadic;
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000158 if (getCurFunctionDecl())
Chris Lattnerc27c6652007-12-20 00:05:45 +0000159 isVariadic =
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000160 cast<FunctionTypeProto>(getCurFunctionDecl()->getType())->isVariadic();
Chris Lattner30ce3442007-12-19 23:59:04 +0000161 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000162 isVariadic = getCurMethodDecl()->isVariadic();
Chris Lattner30ce3442007-12-19 23:59:04 +0000163
Chris Lattnerc27c6652007-12-20 00:05:45 +0000164 if (!isVariadic) {
Chris Lattner30ce3442007-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 Carlssone2c14102008-02-13 01:22:59 +0000172 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Anders Carlsson88cf2262008-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 Lattner30ce3442007-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 Carlsson88cf2262008-02-11 04:20:54 +0000178 const ParmVarDecl *LastArg;
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000179 if (getCurFunctionDecl())
180 LastArg = *(getCurFunctionDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000181 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000182 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000183 SecondArgIsLastNamedArgument = PV == LastArg;
184 }
185 }
186
187 if (!SecondArgIsLastNamedArgument)
Chris Lattner925e60d2007-12-28 05:29:59 +0000188 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000189 diag::warn_second_parameter_of_va_start_not_last_named_argument);
190 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000191}
Chris Lattner30ce3442007-12-19 23:59:04 +0000192
Chris Lattner1b9a0792007-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 Lattner925e60d2007-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 Lattner1b9a0792007-12-20 00:26:33 +0000203
Chris Lattner925e60d2007-12-28 05:29:59 +0000204 Expr *OrigArg0 = TheCall->getArg(0);
205 Expr *OrigArg1 = TheCall->getArg(1);
Chris Lattner1b9a0792007-12-20 00:26:33 +0000206
207 // Do standard promotions between the two arguments, returning their common
208 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000209 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Chris Lattner1b9a0792007-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 Lattner925e60d2007-12-28 05:29:59 +0000214 return Diag(OrigArg0->getLocStart(),
Chris Lattner1b9a0792007-12-20 00:26:33 +0000215 diag::err_typecheck_call_invalid_ordered_compare,
216 OrigArg0->getType().getAsString(),
217 OrigArg1->getType().getAsString(),
Chris Lattner925e60d2007-12-28 05:29:59 +0000218 SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd()));
Chris Lattner1b9a0792007-12-20 00:26:33 +0000219
220 return false;
221}
222
Eli Friedman6cfda232008-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;
227 if (!TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc)) {
228 return Diag(Loc, diag::err_stack_const_level, TheCall->getSourceRange());
229 }
230 return false;
231}
232
Eli Friedmand38617c2008-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 Friedmand38617c2008-05-14 19:38:39 +0000247 return true;
248 }
249
Eli Friedmanba2561a2008-05-16 17:54:49 +0000250 if (FAType.getCanonicalType().getUnqualifiedType() !=
251 SAType.getCanonicalType().getUnqualifiedType()) {
Eli Friedmand38617c2008-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 Friedmand38617c2008-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)
261 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args,
262 TheCall->getSourceRange());
263 else
264 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args,
265 TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000266 return true;
267 }
268
269 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
270 llvm::APSInt Result(32);
271 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) {
272 Diag(TheCall->getLocStart(),
273 diag::err_shufflevector_nonconstant_argument,
274 TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000275 return true;
276 }
277 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) {
278 Diag(TheCall->getLocStart(),
279 diag::err_shufflevector_argument_too_large,
280 TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000281 return true;
282 }
283 }
284
285 llvm::SmallVector<Expr*, 32> exprs;
286
287 for (unsigned i = 0; i < TheCall->getNumArgs(); i++) {
288 exprs.push_back(TheCall->getArg(i));
289 TheCall->setArg(i, 0);
290 }
291
292 ShuffleVectorExpr* E = new ShuffleVectorExpr(
293 exprs.begin(), numElements+2, FAType,
294 TheCall->getCallee()->getLocStart(),
295 TheCall->getRParenLoc());
Eli Friedmand38617c2008-05-14 19:38:39 +0000296
297 return E;
298}
Chris Lattner30ce3442007-12-19 23:59:04 +0000299
Daniel Dunbar4493f792008-07-21 22:59:13 +0000300/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
301// This is declared to take (const void*, ...) and can take two
302// optional constant int args.
303bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
304 unsigned numArgs = TheCall->getNumArgs();
305 bool res = false;
306
307 if (numArgs > 3) {
308 res |= Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args,
309 TheCall->getSourceRange());
310 }
311
312 // Argument 0 is checked for us and the remaining arguments must be
313 // constant integers.
314 for (unsigned i=1; i<numArgs; ++i) {
315 Expr *Arg = TheCall->getArg(i);
316 QualType RWType = Arg->getType();
317
318 const BuiltinType *BT = RWType->getAsBuiltinType();
319 // FIXME: 32 is wrong, needs to be proper width of Int
320 llvm::APSInt Result(32);
321 if (!BT || BT->getKind() != BuiltinType::Int ||
322 !Arg->isIntegerConstantExpr(Result, Context)) {
323 if (Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument,
324 SourceRange(Arg->getLocStart(), Arg->getLocEnd()))) {
325 res = true;
326 continue;
327 }
328 }
329
330 // FIXME: gcc issues a warning and rewrites these to 0. These
331 // seems especially odd for the third argument since the default
332 // is 3.
333 if (i==1) {
334 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 1)
335 res |= Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_range,
336 "0", "1",
337 SourceRange(Arg->getLocStart(), Arg->getLocEnd()));
338 } else {
339 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3)
340 res |= Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_range,
341 "0", "3",
342 SourceRange(Arg->getLocStart(), Arg->getLocEnd()));
343 }
344 }
345
346 return res;
347}
348
Chris Lattner59907c42007-08-10 20:18:51 +0000349/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Ted Kremenek71895b92007-08-14 17:39:48 +0000350/// correct use of format strings.
351///
352/// HasVAListArg - A predicate indicating whether the printf-like
353/// function is passed an explicit va_arg argument (e.g., vprintf)
354///
355/// format_idx - The index into Args for the format string.
356///
357/// Improper format strings to functions in the printf family can be
358/// the source of bizarre bugs and very serious security holes. A
359/// good source of information is available in the following paper
360/// (which includes additional references):
Chris Lattner59907c42007-08-10 20:18:51 +0000361///
362/// FormatGuard: Automatic Protection From printf Format String
363/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremenek71895b92007-08-14 17:39:48 +0000364///
365/// Functionality implemented:
366///
367/// We can statically check the following properties for string
368/// literal format strings for non v.*printf functions (where the
369/// arguments are passed directly):
370//
371/// (1) Are the number of format conversions equal to the number of
372/// data arguments?
373///
374/// (2) Does each format conversion correctly match the type of the
375/// corresponding data argument? (TODO)
376///
377/// Moreover, for all printf functions we can:
378///
379/// (3) Check for a missing format string (when not caught by type checking).
380///
381/// (4) Check for no-operation flags; e.g. using "#" with format
382/// conversion 'c' (TODO)
383///
384/// (5) Check the use of '%n', a major source of security holes.
385///
386/// (6) Check for malformed format conversions that don't specify anything.
387///
388/// (7) Check for empty format strings. e.g: printf("");
389///
390/// (8) Check that the format string is a wide literal.
391///
Ted Kremenek6d439592008-03-03 16:50:00 +0000392/// (9) Also check the arguments of functions with the __format__ attribute.
393/// (TODO).
394///
Ted Kremenek71895b92007-08-14 17:39:48 +0000395/// All of these checks can be done by parsing the format string.
396///
397/// For now, we ONLY do (1), (3), (5), (6), (7), and (8).
Chris Lattner59907c42007-08-10 20:18:51 +0000398void
Chris Lattner925e60d2007-12-28 05:29:59 +0000399Sema::CheckPrintfArguments(CallExpr *TheCall, bool HasVAListArg,
400 unsigned format_idx) {
401 Expr *Fn = TheCall->getCallee();
402
Ted Kremenek71895b92007-08-14 17:39:48 +0000403 // CHECK: printf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +0000404 if (format_idx >= TheCall->getNumArgs()) {
405 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string,
Ted Kremenek71895b92007-08-14 17:39:48 +0000406 Fn->getSourceRange());
407 return;
408 }
409
Chris Lattner56f34942008-02-13 01:02:39 +0000410 Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Chris Lattner459e8482007-08-25 05:36:18 +0000411
Chris Lattner59907c42007-08-10 20:18:51 +0000412 // CHECK: format string is not a string literal.
413 //
Ted Kremenek71895b92007-08-14 17:39:48 +0000414 // Dynamically generated format strings are difficult to
415 // automatically vet at compile time. Requiring that format strings
416 // are string literals: (1) permits the checking of format strings by
417 // the compiler and thereby (2) can practically remove the source of
418 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000419
420 // Format string can be either ObjC string (e.g. @"%d") or
421 // C string (e.g. "%d")
422 // ObjC string uses the same format specifiers as C string, so we can use
423 // the same format string checking logic for both ObjC and C strings.
424 ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(OrigFormatExpr);
425 StringLiteral *FExpr = NULL;
426
427 if(ObjCFExpr != NULL)
428 FExpr = ObjCFExpr->getString();
429 else
430 FExpr = dyn_cast<StringLiteral>(OrigFormatExpr);
431
Ted Kremenek71895b92007-08-14 17:39:48 +0000432 if (FExpr == NULL) {
Ted Kremenek4a336462007-12-17 19:03:13 +0000433 // For vprintf* functions (i.e., HasVAListArg==true), we add a
434 // special check to see if the format string is a function parameter
435 // of the function calling the printf function. If the function
436 // has an attribute indicating it is a printf-like function, then we
437 // should suppress warnings concerning non-literals being used in a call
438 // to a vprintf function. For example:
439 //
440 // void
441 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...) {
442 // va_list ap;
443 // va_start(ap, fmt);
444 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
445 // ...
446 //
447 //
448 // FIXME: We don't have full attribute support yet, so just check to see
449 // if the argument is a DeclRefExpr that references a parameter. We'll
450 // add proper support for checking the attribute later.
451 if (HasVAListArg)
Chris Lattner998568f2007-12-28 05:38:24 +0000452 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(OrigFormatExpr))
453 if (isa<ParmVarDecl>(DR->getDecl()))
Ted Kremenek4a336462007-12-17 19:03:13 +0000454 return;
455
Chris Lattner925e60d2007-12-28 05:29:59 +0000456 Diag(TheCall->getArg(format_idx)->getLocStart(),
457 diag::warn_printf_not_string_constant, Fn->getSourceRange());
Ted Kremenek71895b92007-08-14 17:39:48 +0000458 return;
459 }
460
461 // CHECK: is the format string a wide literal?
462 if (FExpr->isWide()) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000463 Diag(FExpr->getLocStart(),
464 diag::warn_printf_format_string_is_wide_literal, Fn->getSourceRange());
Ted Kremenek71895b92007-08-14 17:39:48 +0000465 return;
466 }
467
468 // Str - The format string. NOTE: this is NOT null-terminated!
469 const char * const Str = FExpr->getStrData();
470
471 // CHECK: empty format string?
472 const unsigned StrLen = FExpr->getByteLength();
473
474 if (StrLen == 0) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000475 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string,
476 Fn->getSourceRange());
Ted Kremenek71895b92007-08-14 17:39:48 +0000477 return;
478 }
479
480 // We process the format string using a binary state machine. The
481 // current state is stored in CurrentState.
482 enum {
483 state_OrdChr,
484 state_Conversion
485 } CurrentState = state_OrdChr;
486
487 // numConversions - The number of conversions seen so far. This is
488 // incremented as we traverse the format string.
489 unsigned numConversions = 0;
490
491 // numDataArgs - The number of data arguments after the format
492 // string. This can only be determined for non vprintf-like
493 // functions. For those functions, this value is 1 (the sole
494 // va_arg argument).
Chris Lattner925e60d2007-12-28 05:29:59 +0000495 unsigned numDataArgs = TheCall->getNumArgs()-(format_idx+1);
Ted Kremenek71895b92007-08-14 17:39:48 +0000496
497 // Inspect the format string.
498 unsigned StrIdx = 0;
499
500 // LastConversionIdx - Index within the format string where we last saw
501 // a '%' character that starts a new format conversion.
502 unsigned LastConversionIdx = 0;
503
Chris Lattner925e60d2007-12-28 05:29:59 +0000504 for (; StrIdx < StrLen; ++StrIdx) {
Chris Lattner998568f2007-12-28 05:38:24 +0000505
Ted Kremenek71895b92007-08-14 17:39:48 +0000506 // Is the number of detected conversion conversions greater than
507 // the number of matching data arguments? If so, stop.
508 if (!HasVAListArg && numConversions > numDataArgs) break;
509
510 // Handle "\0"
Chris Lattner925e60d2007-12-28 05:29:59 +0000511 if (Str[StrIdx] == '\0') {
Ted Kremenek71895b92007-08-14 17:39:48 +0000512 // The string returned by getStrData() is not null-terminated,
513 // so the presence of a null character is likely an error.
Chris Lattner998568f2007-12-28 05:38:24 +0000514 Diag(PP.AdvanceToTokenCharacter(FExpr->getLocStart(), StrIdx+1),
515 diag::warn_printf_format_string_contains_null_char,
Ted Kremenek71895b92007-08-14 17:39:48 +0000516 Fn->getSourceRange());
Ted Kremenek71895b92007-08-14 17:39:48 +0000517 return;
518 }
519
520 // Ordinary characters (not processing a format conversion).
521 if (CurrentState == state_OrdChr) {
522 if (Str[StrIdx] == '%') {
523 CurrentState = state_Conversion;
524 LastConversionIdx = StrIdx;
525 }
526 continue;
527 }
528
529 // Seen '%'. Now processing a format conversion.
530 switch (Str[StrIdx]) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000531 // Handle dynamic precision or width specifier.
532 case '*': {
533 ++numConversions;
534
535 if (!HasVAListArg && numConversions > numDataArgs) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000536 SourceLocation Loc = FExpr->getLocStart();
537 Loc = PP.AdvanceToTokenCharacter(Loc, StrIdx+1);
Ted Kremenek580b6642007-10-12 20:51:52 +0000538
Ted Kremenek580b6642007-10-12 20:51:52 +0000539 if (Str[StrIdx-1] == '.')
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000540 Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg,
541 Fn->getSourceRange());
Ted Kremenek580b6642007-10-12 20:51:52 +0000542 else
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000543 Diag(Loc, diag::warn_printf_asterisk_width_missing_arg,
544 Fn->getSourceRange());
Ted Kremenek580b6642007-10-12 20:51:52 +0000545
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000546 // Don't do any more checking. We'll just emit spurious errors.
547 return;
Ted Kremenek580b6642007-10-12 20:51:52 +0000548 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000549
550 // Perform type checking on width/precision specifier.
551 Expr *E = TheCall->getArg(format_idx+numConversions);
552 if (const BuiltinType *BT = E->getType()->getAsBuiltinType())
553 if (BT->getKind() == BuiltinType::Int)
554 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000555
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000556 SourceLocation Loc =
557 PP.AdvanceToTokenCharacter(FExpr->getLocStart(), StrIdx+1);
558
559 if (Str[StrIdx-1] == '.')
560 Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type,
561 E->getType().getAsString(), E->getSourceRange());
562 else
563 Diag(Loc, diag::warn_printf_asterisk_width_wrong_type,
564 E->getType().getAsString(), E->getSourceRange());
565
566 break;
567 }
568
569 // Characters which can terminate a format conversion
570 // (e.g. "%d"). Characters that specify length modifiers or
571 // other flags are handled by the default case below.
572 //
573 // FIXME: additional checks will go into the following cases.
574 case 'i':
575 case 'd':
576 case 'o':
577 case 'u':
578 case 'x':
579 case 'X':
580 case 'D':
581 case 'O':
582 case 'U':
583 case 'e':
584 case 'E':
585 case 'f':
586 case 'F':
587 case 'g':
588 case 'G':
589 case 'a':
590 case 'A':
591 case 'c':
592 case 'C':
593 case 'S':
594 case 's':
595 case 'p':
596 ++numConversions;
597 CurrentState = state_OrdChr;
598 break;
599
600 // CHECK: Are we using "%n"? Issue a warning.
601 case 'n': {
602 ++numConversions;
603 CurrentState = state_OrdChr;
604 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
605 LastConversionIdx+1);
606
607 Diag(Loc, diag::warn_printf_write_back, Fn->getSourceRange());
608 break;
609 }
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000610
611 // Handle "%@"
612 case '@':
613 // %@ is allowed in ObjC format strings only.
614 if(ObjCFExpr != NULL)
615 CurrentState = state_OrdChr;
616 else {
617 // Issue a warning: invalid format conversion.
618 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
619 LastConversionIdx+1);
620
621 Diag(Loc, diag::warn_printf_invalid_conversion,
622 std::string(Str+LastConversionIdx,
623 Str+std::min(LastConversionIdx+2, StrLen)),
624 Fn->getSourceRange());
625 }
626 ++numConversions;
627 break;
628
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000629 // Handle "%%"
630 case '%':
631 // Sanity check: Was the first "%" character the previous one?
632 // If not, we will assume that we have a malformed format
633 // conversion, and that the current "%" character is the start
634 // of a new conversion.
635 if (StrIdx - LastConversionIdx == 1)
636 CurrentState = state_OrdChr;
637 else {
638 // Issue a warning: invalid format conversion.
Chris Lattner925e60d2007-12-28 05:29:59 +0000639 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
640 LastConversionIdx+1);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000641
642 Diag(Loc, diag::warn_printf_invalid_conversion,
643 std::string(Str+LastConversionIdx, Str+StrIdx),
644 Fn->getSourceRange());
645
646 // This conversion is broken. Advance to the next format
647 // conversion.
648 LastConversionIdx = StrIdx;
649 ++numConversions;
Ted Kremenek71895b92007-08-14 17:39:48 +0000650 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000651 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000652
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000653 default:
654 // This case catches all other characters: flags, widths, etc.
655 // We should eventually process those as well.
656 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000657 }
658 }
659
660 if (CurrentState == state_Conversion) {
661 // Issue a warning: invalid format conversion.
Chris Lattner925e60d2007-12-28 05:29:59 +0000662 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
663 LastConversionIdx+1);
Ted Kremenek71895b92007-08-14 17:39:48 +0000664
665 Diag(Loc, diag::warn_printf_invalid_conversion,
Chris Lattnera9e2ea12007-08-26 17:38:22 +0000666 std::string(Str+LastConversionIdx,
667 Str+std::min(LastConversionIdx+2, StrLen)),
Ted Kremenek71895b92007-08-14 17:39:48 +0000668 Fn->getSourceRange());
669 return;
670 }
671
672 if (!HasVAListArg) {
673 // CHECK: Does the number of format conversions exceed the number
674 // of data arguments?
675 if (numConversions > numDataArgs) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000676 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
677 LastConversionIdx);
Ted Kremenek71895b92007-08-14 17:39:48 +0000678
679 Diag(Loc, diag::warn_printf_insufficient_data_args,
680 Fn->getSourceRange());
681 }
682 // CHECK: Does the number of data arguments exceed the number of
683 // format conversions in the format string?
684 else if (numConversions < numDataArgs)
Chris Lattner925e60d2007-12-28 05:29:59 +0000685 Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(),
Ted Kremenek71895b92007-08-14 17:39:48 +0000686 diag::warn_printf_too_many_data_args, Fn->getSourceRange());
687 }
688}
Ted Kremenek06de2762007-08-17 16:46:58 +0000689
690//===--- CHECK: Return Address of Stack Variable --------------------------===//
691
692static DeclRefExpr* EvalVal(Expr *E);
693static DeclRefExpr* EvalAddr(Expr* E);
694
695/// CheckReturnStackAddr - Check if a return statement returns the address
696/// of a stack variable.
697void
698Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
699 SourceLocation ReturnLoc) {
Chris Lattner56f34942008-02-13 01:02:39 +0000700
Ted Kremenek06de2762007-08-17 16:46:58 +0000701 // Perform checking for returned stack addresses.
702 if (lhsType->isPointerType()) {
703 if (DeclRefExpr *DR = EvalAddr(RetValExp))
704 Diag(DR->getLocStart(), diag::warn_ret_stack_addr,
705 DR->getDecl()->getIdentifier()->getName(),
706 RetValExp->getSourceRange());
707 }
708 // Perform checking for stack values returned by reference.
709 else if (lhsType->isReferenceType()) {
Ted Kremenek96eabe02007-08-27 16:39:17 +0000710 // Check for an implicit cast to a reference.
711 if (ImplicitCastExpr *I = dyn_cast<ImplicitCastExpr>(RetValExp))
712 if (DeclRefExpr *DR = EvalVal(I->getSubExpr()))
713 Diag(DR->getLocStart(), diag::warn_ret_stack_ref,
714 DR->getDecl()->getIdentifier()->getName(),
715 RetValExp->getSourceRange());
Ted Kremenek06de2762007-08-17 16:46:58 +0000716 }
717}
718
719/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
720/// check if the expression in a return statement evaluates to an address
721/// to a location on the stack. The recursion is used to traverse the
722/// AST of the return expression, with recursion backtracking when we
723/// encounter a subexpression that (1) clearly does not lead to the address
724/// of a stack variable or (2) is something we cannot determine leads to
725/// the address of a stack variable based on such local checking.
726///
Ted Kremeneke8c600f2007-08-28 17:02:55 +0000727/// EvalAddr processes expressions that are pointers that are used as
728/// references (and not L-values). EvalVal handles all other values.
Ted Kremenek06de2762007-08-17 16:46:58 +0000729/// At the base case of the recursion is a check for a DeclRefExpr* in
730/// the refers to a stack variable.
731///
732/// This implementation handles:
733///
734/// * pointer-to-pointer casts
735/// * implicit conversions from array references to pointers
736/// * taking the address of fields
737/// * arbitrary interplay between "&" and "*" operators
738/// * pointer arithmetic from an address of a stack variable
739/// * taking the address of an array element where the array is on the stack
740static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek06de2762007-08-17 16:46:58 +0000741 // We should only be called for evaluating pointer expressions.
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000742 assert((E->getType()->isPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000743 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000744 "EvalAddr only works on pointers");
Ted Kremenek06de2762007-08-17 16:46:58 +0000745
746 // Our "symbolic interpreter" is just a dispatch off the currently
747 // viewed AST node. We then recursively traverse the AST by calling
748 // EvalAddr and EvalVal appropriately.
749 switch (E->getStmtClass()) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000750 case Stmt::ParenExprClass:
751 // Ignore parentheses.
752 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek06de2762007-08-17 16:46:58 +0000753
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000754 case Stmt::UnaryOperatorClass: {
755 // The only unary operator that make sense to handle here
756 // is AddrOf. All others don't make sense as pointers.
757 UnaryOperator *U = cast<UnaryOperator>(E);
Ted Kremenek06de2762007-08-17 16:46:58 +0000758
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000759 if (U->getOpcode() == UnaryOperator::AddrOf)
760 return EvalVal(U->getSubExpr());
761 else
Ted Kremenek06de2762007-08-17 16:46:58 +0000762 return NULL;
763 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000764
765 case Stmt::BinaryOperatorClass: {
766 // Handle pointer arithmetic. All other binary operators are not valid
767 // in this context.
768 BinaryOperator *B = cast<BinaryOperator>(E);
769 BinaryOperator::Opcode op = B->getOpcode();
770
771 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
772 return NULL;
773
774 Expr *Base = B->getLHS();
775
776 // Determine which argument is the real pointer base. It could be
777 // the RHS argument instead of the LHS.
778 if (!Base->getType()->isPointerType()) Base = B->getRHS();
779
780 assert (Base->getType()->isPointerType());
781 return EvalAddr(Base);
782 }
783
784 // For conditional operators we need to see if either the LHS or RHS are
785 // valid DeclRefExpr*s. If one of them is valid, we return it.
786 case Stmt::ConditionalOperatorClass: {
787 ConditionalOperator *C = cast<ConditionalOperator>(E);
788
789 // Handle the GNU extension for missing LHS.
790 if (Expr *lhsExpr = C->getLHS())
791 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
792 return LHS;
793
794 return EvalAddr(C->getRHS());
795 }
796
797 // For implicit casts, we need to handle conversions from arrays to
798 // pointer values, and implicit pointer-to-pointer conversions.
799 case Stmt::ImplicitCastExprClass: {
800 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
801 Expr* SubExpr = IE->getSubExpr();
802
803 if (SubExpr->getType()->isPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000804 SubExpr->getType()->isObjCQualifiedIdType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000805 return EvalAddr(SubExpr);
806 else
807 return EvalVal(SubExpr);
808 }
809
810 // For casts, we handle pointer-to-pointer conversions (which
811 // is essentially a no-op from our mini-interpreter's standpoint).
812 // For other casts we abort.
813 case Stmt::CastExprClass: {
814 CastExpr *C = cast<CastExpr>(E);
815 Expr *SubExpr = C->getSubExpr();
816
817 if (SubExpr->getType()->isPointerType())
818 return EvalAddr(SubExpr);
819 else
820 return NULL;
821 }
822
823 // C++ casts. For dynamic casts, static casts, and const casts, we
824 // are always converting from a pointer-to-pointer, so we just blow
825 // through the cast. In the case the dynamic cast doesn't fail
826 // (and return NULL), we take the conservative route and report cases
827 // where we return the address of a stack variable. For Reinterpre
828 case Stmt::CXXCastExprClass: {
829 CXXCastExpr *C = cast<CXXCastExpr>(E);
830
831 if (C->getOpcode() == CXXCastExpr::ReinterpretCast) {
832 Expr *S = C->getSubExpr();
833 if (S->getType()->isPointerType())
834 return EvalAddr(S);
835 else
836 return NULL;
837 }
838 else
839 return EvalAddr(C->getSubExpr());
840 }
841
842 // Everything else: we simply don't reason about them.
843 default:
844 return NULL;
845 }
Ted Kremenek06de2762007-08-17 16:46:58 +0000846}
847
848
849/// EvalVal - This function is complements EvalAddr in the mutual recursion.
850/// See the comments for EvalAddr for more details.
851static DeclRefExpr* EvalVal(Expr *E) {
852
Ted Kremeneke8c600f2007-08-28 17:02:55 +0000853 // We should only be called for evaluating non-pointer expressions, or
854 // expressions with a pointer type that are not used as references but instead
855 // are l-values (e.g., DeclRefExpr with a pointer type).
856
Ted Kremenek06de2762007-08-17 16:46:58 +0000857 // Our "symbolic interpreter" is just a dispatch off the currently
858 // viewed AST node. We then recursively traverse the AST by calling
859 // EvalAddr and EvalVal appropriately.
860 switch (E->getStmtClass()) {
Ted Kremenek06de2762007-08-17 16:46:58 +0000861 case Stmt::DeclRefExprClass: {
862 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
863 // at code that refers to a variable's name. We check if it has local
864 // storage within the function, and if so, return the expression.
865 DeclRefExpr *DR = cast<DeclRefExpr>(E);
866
867 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
868 if(V->hasLocalStorage()) return DR;
869
870 return NULL;
871 }
872
873 case Stmt::ParenExprClass:
874 // Ignore parentheses.
875 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
876
877 case Stmt::UnaryOperatorClass: {
878 // The only unary operator that make sense to handle here
879 // is Deref. All others don't resolve to a "name." This includes
880 // handling all sorts of rvalues passed to a unary operator.
881 UnaryOperator *U = cast<UnaryOperator>(E);
882
883 if (U->getOpcode() == UnaryOperator::Deref)
884 return EvalAddr(U->getSubExpr());
885
886 return NULL;
887 }
888
889 case Stmt::ArraySubscriptExprClass: {
890 // Array subscripts are potential references to data on the stack. We
891 // retrieve the DeclRefExpr* for the array variable if it indeed
892 // has local storage.
Ted Kremenek23245122007-08-20 16:18:38 +0000893 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek06de2762007-08-17 16:46:58 +0000894 }
895
896 case Stmt::ConditionalOperatorClass: {
897 // For conditional operators we need to see if either the LHS or RHS are
898 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
899 ConditionalOperator *C = cast<ConditionalOperator>(E);
900
Anders Carlsson39073232007-11-30 19:04:31 +0000901 // Handle the GNU extension for missing LHS.
902 if (Expr *lhsExpr = C->getLHS())
903 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
904 return LHS;
905
906 return EvalVal(C->getRHS());
Ted Kremenek06de2762007-08-17 16:46:58 +0000907 }
908
909 // Accesses to members are potential references to data on the stack.
910 case Stmt::MemberExprClass: {
911 MemberExpr *M = cast<MemberExpr>(E);
912
913 // Check for indirect access. We only want direct field accesses.
914 if (!M->isArrow())
915 return EvalVal(M->getBase());
916 else
917 return NULL;
918 }
919
920 // Everything else: we simply don't reason about them.
921 default:
922 return NULL;
923 }
924}
Ted Kremenek588e5eb2007-11-25 00:58:00 +0000925
926//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
927
928/// Check for comparisons of floating point operands using != and ==.
929/// Issue a warning if these are no self-comparisons, as they are not likely
930/// to do what the programmer intended.
931void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
932 bool EmitWarning = true;
933
Ted Kremenek4e99a5f2008-01-17 16:57:34 +0000934 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek32e97b62008-01-17 17:55:13 +0000935 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek588e5eb2007-11-25 00:58:00 +0000936
937 // Special case: check for x == x (which is OK).
938 // Do not emit warnings for such cases.
939 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
940 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
941 if (DRL->getDecl() == DRR->getDecl())
942 EmitWarning = false;
943
Ted Kremenek1b500bb2007-11-29 00:59:04 +0000944
945 // Special case: check for comparisons against literals that can be exactly
946 // represented by APFloat. In such cases, do not emit a warning. This
947 // is a heuristic: often comparison against such literals are used to
948 // detect if a value in a variable has not changed. This clearly can
949 // lead to false negatives.
950 if (EmitWarning) {
951 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
952 if (FLL->isExact())
953 EmitWarning = false;
954 }
955 else
956 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
957 if (FLR->isExact())
958 EmitWarning = false;
959 }
960 }
961
Ted Kremenek588e5eb2007-11-25 00:58:00 +0000962 // Check for comparisons with builtin types.
963 if (EmitWarning)
964 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
965 if (isCallBuiltin(CL))
966 EmitWarning = false;
967
968 if (EmitWarning)
969 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
970 if (isCallBuiltin(CR))
971 EmitWarning = false;
972
973 // Emit the diagnostic.
974 if (EmitWarning)
975 Diag(loc, diag::warn_floatingpoint_eq,
976 lex->getSourceRange(),rex->getSourceRange());
977}