blob: 92cad1029b765ff02c41d900b098e66e85c44c62 [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"
Daniel Dunbar64789f82008-08-11 05:35:13 +000017#include "clang/AST/DeclObjC.h"
Ted Kremenek1c1700f2007-08-20 16:18:38 +000018#include "clang/AST/ExprCXX.h"
Ted Kremenek225a14c2008-06-16 18:00:42 +000019#include "clang/AST/ExprObjC.h"
Chris Lattner2e64c072007-08-10 20:18:51 +000020#include "clang/Lex/Preprocessor.h"
Ted Kremenek30c66752007-11-25 00:58:00 +000021#include "SemaUtil.h"
Chris Lattner2e64c072007-08-10 20:18:51 +000022using namespace clang;
23
24/// CheckFunctionCall - Check a direct function call for various correctness
25/// and safety properties not strictly enforced by the C type system.
Sebastian Redl8b769972009-01-19 00:08:26 +000026Action::OwningExprResult
27Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
28 OwningExprResult TheCallResult(Owned(TheCall));
Chris Lattner2e64c072007-08-10 20:18:51 +000029 // Get the IdentifierInfo* for the called function.
30 IdentifierInfo *FnInfo = FDecl->getIdentifier();
Douglas Gregorb0212bd2008-11-17 20:34:05 +000031
32 // None of the checks below are needed for functions that don't have
33 // simple names (e.g., C++ conversion functions).
34 if (!FnInfo)
Sebastian Redl8b769972009-01-19 00:08:26 +000035 return move(TheCallResult);
Douglas Gregorb0212bd2008-11-17 20:34:05 +000036
Chris Lattnerf22a8502007-12-19 23:59:04 +000037 switch (FnInfo->getBuiltinID()) {
38 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner83bd5eb2007-12-28 05:29:59 +000039 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner7c8d1af2007-12-20 00:26:33 +000040 "Wrong # arguments to builtin CFStringMakeConstantString");
Eli Friedman798e4d52008-05-16 17:51:27 +000041 if (CheckBuiltinCFStringArgument(TheCall->getArg(0)))
Sebastian Redl8b769972009-01-19 00:08:26 +000042 return ExprError();
43 return move(TheCallResult);
Ted Kremenek7a0654c2008-07-09 17:58:53 +000044 case Builtin::BI__builtin_stdarg_start:
Chris Lattnerf22a8502007-12-19 23:59:04 +000045 case Builtin::BI__builtin_va_start:
Sebastian Redl8b769972009-01-19 00:08:26 +000046 if (SemaBuiltinVAStart(TheCall))
47 return ExprError();
48 return move(TheCallResult);
Chris Lattner7c8d1af2007-12-20 00:26:33 +000049 case Builtin::BI__builtin_isgreater:
50 case Builtin::BI__builtin_isgreaterequal:
51 case Builtin::BI__builtin_isless:
52 case Builtin::BI__builtin_islessequal:
53 case Builtin::BI__builtin_islessgreater:
54 case Builtin::BI__builtin_isunordered:
Sebastian Redl8b769972009-01-19 00:08:26 +000055 if (SemaBuiltinUnorderedCompare(TheCall))
56 return ExprError();
57 return move(TheCallResult);
Eli Friedman8c50c622008-05-20 08:23:37 +000058 case Builtin::BI__builtin_return_address:
59 case Builtin::BI__builtin_frame_address:
Sebastian Redl8b769972009-01-19 00:08:26 +000060 if (SemaBuiltinStackAddress(TheCall))
61 return ExprError();
62 return move(TheCallResult);
Eli Friedmand0e9d092008-05-14 19:38:39 +000063 case Builtin::BI__builtin_shufflevector:
Sebastian Redl8b769972009-01-19 00:08:26 +000064 return SemaBuiltinShuffleVector(TheCall);
65 // TheCall will be freed by the smart pointer here, but that's fine, since
66 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar5b0de852008-07-21 22:59:13 +000067 case Builtin::BI__builtin_prefetch:
Sebastian Redl8b769972009-01-19 00:08:26 +000068 if (SemaBuiltinPrefetch(TheCall))
69 return ExprError();
70 return move(TheCallResult);
Daniel Dunbar30ad42d2008-09-03 21:13:56 +000071 case Builtin::BI__builtin_object_size:
Sebastian Redl8b769972009-01-19 00:08:26 +000072 if (SemaBuiltinObjectSize(TheCall))
73 return ExprError();
Anders Carlssone7e7aa22007-08-17 05:31:46 +000074 }
Daniel Dunbar0ab03e62008-10-02 18:44:07 +000075
76 // FIXME: This mechanism should be abstracted to be less fragile and
77 // more efficient. For example, just map function ids to custom
78 // handlers.
79
Chris Lattner2e64c072007-08-10 20:18:51 +000080 // Search the KnownFunctionIDs for the identifier.
81 unsigned i = 0, e = id_num_known_functions;
Ted Kremenek081ed872007-08-14 17:39:48 +000082 for (; i != e; ++i) { if (KnownFunctionIDs[i] == FnInfo) break; }
Sebastian Redl8b769972009-01-19 00:08:26 +000083 if (i == e) return move(TheCallResult);
84
Chris Lattner2e64c072007-08-10 20:18:51 +000085 // Printf checking.
86 if (i <= id_vprintf) {
Ted Kremenek081ed872007-08-14 17:39:48 +000087 // Retrieve the index of the format string parameter and determine
88 // if the function is passed a va_arg argument.
Chris Lattner2e64c072007-08-10 20:18:51 +000089 unsigned format_idx = 0;
Ted Kremenek081ed872007-08-14 17:39:48 +000090 bool HasVAListArg = false;
Sebastian Redl8b769972009-01-19 00:08:26 +000091
Chris Lattner2e64c072007-08-10 20:18:51 +000092 switch (i) {
Chris Lattnerf22a8502007-12-19 23:59:04 +000093 default: assert(false && "No format string argument index.");
Daniel Dunbar0ab03e62008-10-02 18:44:07 +000094 case id_NSLog: format_idx = 0; break;
95 case id_asprintf: format_idx = 1; break;
96 case id_fprintf: format_idx = 1; break;
97 case id_printf: format_idx = 0; break;
98 case id_snprintf: format_idx = 2; break;
99 case id_snprintf_chk: format_idx = 4; break;
100 case id_sprintf: format_idx = 1; break;
101 case id_sprintf_chk: format_idx = 3; break;
102 case id_vasprintf: format_idx = 1; HasVAListArg = true; break;
103 case id_vfprintf: format_idx = 1; HasVAListArg = true; break;
104 case id_vsnprintf: format_idx = 2; HasVAListArg = true; break;
105 case id_vsnprintf_chk: format_idx = 4; HasVAListArg = true; break;
106 case id_vsprintf: format_idx = 1; HasVAListArg = true; break;
107 case id_vsprintf_chk: format_idx = 3; HasVAListArg = true; break;
108 case id_vprintf: format_idx = 0; HasVAListArg = true; break;
Ted Kremenek081ed872007-08-14 17:39:48 +0000109 }
Sebastian Redl8b769972009-01-19 00:08:26 +0000110
111 CheckPrintfArguments(TheCall, HasVAListArg, format_idx);
Chris Lattner2e64c072007-08-10 20:18:51 +0000112 }
Sebastian Redl8b769972009-01-19 00:08:26 +0000113
114 return move(TheCallResult);
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000115}
116
117/// CheckBuiltinCFStringArgument - Checks that the argument to the builtin
118/// CFString constructor is correct
Chris Lattnerda050402007-08-25 05:30:33 +0000119bool Sema::CheckBuiltinCFStringArgument(Expr* Arg) {
Chris Lattner7a48d9c2008-02-13 01:02:39 +0000120 Arg = Arg->IgnoreParenCasts();
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000121
122 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
123
124 if (!Literal || Literal->isWide()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000125 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
126 << Arg->getSourceRange();
Anders Carlsson3e9b43b2007-08-17 15:44:17 +0000127 return true;
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000128 }
129
130 const char *Data = Literal->getStrData();
131 unsigned Length = Literal->getByteLength();
132
133 for (unsigned i = 0; i < Length; ++i) {
134 if (!isascii(Data[i])) {
135 Diag(PP.AdvanceToTokenCharacter(Arg->getLocStart(), i + 1),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000136 diag::warn_cfstring_literal_contains_non_ascii_character)
137 << Arg->getSourceRange();
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000138 break;
139 }
140
141 if (!Data[i]) {
142 Diag(PP.AdvanceToTokenCharacter(Arg->getLocStart(), i + 1),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000143 diag::warn_cfstring_literal_contains_nul_character)
144 << Arg->getSourceRange();
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000145 break;
146 }
147 }
148
Anders Carlsson3e9b43b2007-08-17 15:44:17 +0000149 return false;
Chris Lattner2e64c072007-08-10 20:18:51 +0000150}
151
Chris Lattner3b933692007-12-20 00:05:45 +0000152/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
153/// Emit an error and return true on failure, return false on success.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000154bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
155 Expr *Fn = TheCall->getCallee();
156 if (TheCall->getNumArgs() > 2) {
Chris Lattner66beaba2008-11-21 18:44:24 +0000157 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000158 diag::err_typecheck_call_too_many_args)
Chris Lattner66beaba2008-11-21 18:44:24 +0000159 << 0 /*function call*/ << Fn->getSourceRange()
Chris Lattner8ba580c2008-11-19 05:08:23 +0000160 << SourceRange(TheCall->getArg(2)->getLocStart(),
161 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattnerf22a8502007-12-19 23:59:04 +0000162 return true;
163 }
Eli Friedman6422de62008-12-15 22:05:35 +0000164
165 if (TheCall->getNumArgs() < 2) {
166 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
167 << 0 /*function call*/;
168 }
169
Chris Lattner3b933692007-12-20 00:05:45 +0000170 // Determine whether the current function is variadic or not.
171 bool isVariadic;
Eli Friedman6422de62008-12-15 22:05:35 +0000172 if (getCurFunctionDecl()) {
173 if (FunctionTypeProto* FTP =
174 dyn_cast<FunctionTypeProto>(getCurFunctionDecl()->getType()))
175 isVariadic = FTP->isVariadic();
176 else
177 isVariadic = false;
178 } else {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000179 isVariadic = getCurMethodDecl()->isVariadic();
Eli Friedman6422de62008-12-15 22:05:35 +0000180 }
Chris Lattnerf22a8502007-12-19 23:59:04 +0000181
Chris Lattner3b933692007-12-20 00:05:45 +0000182 if (!isVariadic) {
Chris Lattnerf22a8502007-12-19 23:59:04 +0000183 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
184 return true;
185 }
186
187 // Verify that the second argument to the builtin is the last argument of the
188 // current function or method.
189 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson924556e2008-02-13 01:22:59 +0000190 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Anders Carlssonc27156b2008-02-11 04:20:54 +0000191
192 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
193 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattnerf22a8502007-12-19 23:59:04 +0000194 // FIXME: This isn't correct for methods (results in bogus warning).
195 // Get the last formal in the current function.
Anders Carlssonc27156b2008-02-11 04:20:54 +0000196 const ParmVarDecl *LastArg;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000197 if (FunctionDecl *FD = getCurFunctionDecl())
198 LastArg = *(FD->param_end()-1);
Chris Lattnerf22a8502007-12-19 23:59:04 +0000199 else
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000200 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattnerf22a8502007-12-19 23:59:04 +0000201 SecondArgIsLastNamedArgument = PV == LastArg;
202 }
203 }
204
205 if (!SecondArgIsLastNamedArgument)
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000206 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattnerf22a8502007-12-19 23:59:04 +0000207 diag::warn_second_parameter_of_va_start_not_last_named_argument);
208 return false;
Eli Friedman8c50c622008-05-20 08:23:37 +0000209}
Chris Lattnerf22a8502007-12-19 23:59:04 +0000210
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000211/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
212/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000213bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
214 if (TheCall->getNumArgs() < 2)
Chris Lattner66beaba2008-11-21 18:44:24 +0000215 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
216 << 0 /*function call*/;
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000217 if (TheCall->getNumArgs() > 2)
218 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000219 diag::err_typecheck_call_too_many_args)
Chris Lattner66beaba2008-11-21 18:44:24 +0000220 << 0 /*function call*/
Chris Lattner8ba580c2008-11-19 05:08:23 +0000221 << SourceRange(TheCall->getArg(2)->getLocStart(),
222 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000223
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000224 Expr *OrigArg0 = TheCall->getArg(0);
225 Expr *OrigArg1 = TheCall->getArg(1);
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000226
227 // Do standard promotions between the two arguments, returning their common
228 // type.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000229 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000230
231 // If the common type isn't a real floating type, then the arguments were
232 // invalid for this operation.
233 if (!Res->isRealFloatingType())
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000234 return Diag(OrigArg0->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000235 diag::err_typecheck_call_invalid_ordered_compare)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000236 << OrigArg0->getType() << OrigArg1->getType()
Chris Lattner8ba580c2008-11-19 05:08:23 +0000237 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000238
239 return false;
240}
241
Eli Friedman8c50c622008-05-20 08:23:37 +0000242bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) {
243 // The signature for these builtins is exact; the only thing we need
244 // to check is that the argument is a constant.
245 SourceLocation Loc;
Chris Lattner941c0102008-08-10 02:05:13 +0000246 if (!TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc))
Chris Lattner8ba580c2008-11-19 05:08:23 +0000247 return Diag(Loc, diag::err_stack_const_level) << TheCall->getSourceRange();
Chris Lattner941c0102008-08-10 02:05:13 +0000248
Eli Friedman8c50c622008-05-20 08:23:37 +0000249 return false;
250}
251
Eli Friedmand0e9d092008-05-14 19:38:39 +0000252/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
253// This is declared to take (...), so we have to check everything.
Sebastian Redl8b769972009-01-19 00:08:26 +0000254Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Eli Friedmand0e9d092008-05-14 19:38:39 +0000255 if (TheCall->getNumArgs() < 3)
Sebastian Redl8b769972009-01-19 00:08:26 +0000256 return ExprError(Diag(TheCall->getLocEnd(),
257 diag::err_typecheck_call_too_few_args)
258 << 0 /*function call*/ << TheCall->getSourceRange());
Eli Friedmand0e9d092008-05-14 19:38:39 +0000259
260 QualType FAType = TheCall->getArg(0)->getType();
261 QualType SAType = TheCall->getArg(1)->getType();
262
263 if (!FAType->isVectorType() || !SAType->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000264 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
265 << SourceRange(TheCall->getArg(0)->getLocStart(),
266 TheCall->getArg(1)->getLocEnd());
Sebastian Redl8b769972009-01-19 00:08:26 +0000267 return ExprError();
Eli Friedmand0e9d092008-05-14 19:38:39 +0000268 }
269
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000270 if (Context.getCanonicalType(FAType).getUnqualifiedType() !=
271 Context.getCanonicalType(SAType).getUnqualifiedType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000272 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
273 << SourceRange(TheCall->getArg(0)->getLocStart(),
274 TheCall->getArg(1)->getLocEnd());
Sebastian Redl8b769972009-01-19 00:08:26 +0000275 return ExprError();
Eli Friedmand0e9d092008-05-14 19:38:39 +0000276 }
277
278 unsigned numElements = FAType->getAsVectorType()->getNumElements();
279 if (TheCall->getNumArgs() != numElements+2) {
280 if (TheCall->getNumArgs() < numElements+2)
Sebastian Redl8b769972009-01-19 00:08:26 +0000281 return ExprError(Diag(TheCall->getLocEnd(),
282 diag::err_typecheck_call_too_few_args)
283 << 0 /*function call*/ << TheCall->getSourceRange());
284 return ExprError(Diag(TheCall->getLocEnd(),
285 diag::err_typecheck_call_too_many_args)
286 << 0 /*function call*/ << TheCall->getSourceRange());
Eli Friedmand0e9d092008-05-14 19:38:39 +0000287 }
288
289 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
290 llvm::APSInt Result(32);
Chris Lattner941c0102008-08-10 02:05:13 +0000291 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
Sebastian Redl8b769972009-01-19 00:08:26 +0000292 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000293 diag::err_shufflevector_nonconstant_argument)
Sebastian Redl8b769972009-01-19 00:08:26 +0000294 << TheCall->getArg(i)->getSourceRange());
295
Chris Lattner941c0102008-08-10 02:05:13 +0000296 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl8b769972009-01-19 00:08:26 +0000297 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000298 diag::err_shufflevector_argument_too_large)
Sebastian Redl8b769972009-01-19 00:08:26 +0000299 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand0e9d092008-05-14 19:38:39 +0000300 }
301
302 llvm::SmallVector<Expr*, 32> exprs;
303
Chris Lattner941c0102008-08-10 02:05:13 +0000304 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand0e9d092008-05-14 19:38:39 +0000305 exprs.push_back(TheCall->getArg(i));
306 TheCall->setArg(i, 0);
307 }
308
Sebastian Redl8b769972009-01-19 00:08:26 +0000309 return Owned(new ShuffleVectorExpr(exprs.begin(), numElements+2, FAType,
310 TheCall->getCallee()->getLocStart(),
311 TheCall->getRParenLoc()));
Eli Friedmand0e9d092008-05-14 19:38:39 +0000312}
Chris Lattnerf22a8502007-12-19 23:59:04 +0000313
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000314/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
315// This is declared to take (const void*, ...) and can take two
316// optional constant int args.
317bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000318 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000319
Chris Lattner8ba580c2008-11-19 05:08:23 +0000320 if (NumArgs > 3)
321 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args)
Chris Lattner66beaba2008-11-21 18:44:24 +0000322 << 0 /*function call*/ << TheCall->getSourceRange();
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000323
324 // Argument 0 is checked for us and the remaining arguments must be
325 // constant integers.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000326 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000327 Expr *Arg = TheCall->getArg(i);
328 QualType RWType = Arg->getType();
329
330 const BuiltinType *BT = RWType->getAsBuiltinType();
Daniel Dunbar30ad42d2008-09-03 21:13:56 +0000331 llvm::APSInt Result;
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000332 if (!BT || BT->getKind() != BuiltinType::Int ||
Chris Lattner8ba580c2008-11-19 05:08:23 +0000333 !Arg->isIntegerConstantExpr(Result, Context))
334 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument)
335 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000336
337 // FIXME: gcc issues a warning and rewrites these to 0. These
338 // seems especially odd for the third argument since the default
339 // is 3.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000340 if (i == 1) {
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000341 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 1)
Chris Lattner8ba580c2008-11-19 05:08:23 +0000342 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
343 << "0" << "1" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000344 } else {
345 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3)
Chris Lattner8ba580c2008-11-19 05:08:23 +0000346 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
347 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000348 }
349 }
350
Chris Lattner8ba580c2008-11-19 05:08:23 +0000351 return false;
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000352}
353
Daniel Dunbar30ad42d2008-09-03 21:13:56 +0000354/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
355/// int type). This simply type checks that type is one of the defined
356/// constants (0-3).
357bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
358 Expr *Arg = TheCall->getArg(1);
359 QualType ArgType = Arg->getType();
360 const BuiltinType *BT = ArgType->getAsBuiltinType();
361 llvm::APSInt Result(32);
362 if (!BT || BT->getKind() != BuiltinType::Int ||
363 !Arg->isIntegerConstantExpr(Result, Context)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000364 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
365 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar30ad42d2008-09-03 21:13:56 +0000366 }
367
368 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000369 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
370 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar30ad42d2008-09-03 21:13:56 +0000371 }
372
373 return false;
374}
375
Ted Kremenek8c797c02009-01-12 23:09:09 +0000376// Handle i > 1 ? "x" : "y", recursivelly
377bool Sema::SemaCheckStringLiteral(Expr *E, CallExpr *TheCall, bool HasVAListArg,
378 unsigned format_idx) {
379
380 switch (E->getStmtClass()) {
381 case Stmt::ConditionalOperatorClass: {
382 ConditionalOperator *C = cast<ConditionalOperator>(E);
383 return SemaCheckStringLiteral(C->getLHS(), TheCall,
384 HasVAListArg, format_idx)
385 && SemaCheckStringLiteral(C->getRHS(), TheCall,
386 HasVAListArg, format_idx);
387 }
388
389 case Stmt::ImplicitCastExprClass: {
390 ImplicitCastExpr *Expr = dyn_cast<ImplicitCastExpr>(E);
391 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
392 format_idx);
393 }
394
395 case Stmt::ParenExprClass: {
396 ParenExpr *Expr = dyn_cast<ParenExpr>(E);
397 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
398 format_idx);
399 }
400
401 default: {
402 ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E);
403 StringLiteral *StrE = NULL;
404
405 if (ObjCFExpr)
406 StrE = ObjCFExpr->getString();
407 else
408 StrE = dyn_cast<StringLiteral>(E);
409
410 if (StrE) {
411 CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx);
412 return true;
413 }
414
415 return false;
416 }
417 }
418}
419
420
Chris Lattner2e64c072007-08-10 20:18:51 +0000421/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Ted Kremenek081ed872007-08-14 17:39:48 +0000422/// correct use of format strings.
423///
424/// HasVAListArg - A predicate indicating whether the printf-like
425/// function is passed an explicit va_arg argument (e.g., vprintf)
426///
427/// format_idx - The index into Args for the format string.
428///
429/// Improper format strings to functions in the printf family can be
430/// the source of bizarre bugs and very serious security holes. A
431/// good source of information is available in the following paper
432/// (which includes additional references):
Chris Lattner2e64c072007-08-10 20:18:51 +0000433///
434/// FormatGuard: Automatic Protection From printf Format String
435/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremenek081ed872007-08-14 17:39:48 +0000436///
437/// Functionality implemented:
438///
439/// We can statically check the following properties for string
440/// literal format strings for non v.*printf functions (where the
441/// arguments are passed directly):
442//
443/// (1) Are the number of format conversions equal to the number of
444/// data arguments?
445///
446/// (2) Does each format conversion correctly match the type of the
447/// corresponding data argument? (TODO)
448///
449/// Moreover, for all printf functions we can:
450///
451/// (3) Check for a missing format string (when not caught by type checking).
452///
453/// (4) Check for no-operation flags; e.g. using "#" with format
454/// conversion 'c' (TODO)
455///
456/// (5) Check the use of '%n', a major source of security holes.
457///
458/// (6) Check for malformed format conversions that don't specify anything.
459///
460/// (7) Check for empty format strings. e.g: printf("");
461///
462/// (8) Check that the format string is a wide literal.
463///
Ted Kremenekc2804c22008-03-03 16:50:00 +0000464/// (9) Also check the arguments of functions with the __format__ attribute.
465/// (TODO).
466///
Ted Kremenek081ed872007-08-14 17:39:48 +0000467/// All of these checks can be done by parsing the format string.
468///
469/// For now, we ONLY do (1), (3), (5), (6), (7), and (8).
Chris Lattner2e64c072007-08-10 20:18:51 +0000470void
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000471Sema::CheckPrintfArguments(CallExpr *TheCall, bool HasVAListArg,
472 unsigned format_idx) {
473 Expr *Fn = TheCall->getCallee();
474
Ted Kremenek081ed872007-08-14 17:39:48 +0000475 // CHECK: printf-like function is called with no format string.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000476 if (format_idx >= TheCall->getNumArgs()) {
Chris Lattner9d2cf082008-11-19 05:27:50 +0000477 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string)
478 << Fn->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +0000479 return;
480 }
481
Chris Lattner7a48d9c2008-02-13 01:02:39 +0000482 Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Chris Lattnere65acc12007-08-25 05:36:18 +0000483
Chris Lattner2e64c072007-08-10 20:18:51 +0000484 // CHECK: format string is not a string literal.
485 //
Ted Kremenek081ed872007-08-14 17:39:48 +0000486 // Dynamically generated format strings are difficult to
487 // automatically vet at compile time. Requiring that format strings
488 // are string literals: (1) permits the checking of format strings by
489 // the compiler and thereby (2) can practically remove the source of
490 // many format string exploits.
Ted Kremenek225a14c2008-06-16 18:00:42 +0000491
492 // Format string can be either ObjC string (e.g. @"%d") or
493 // C string (e.g. "%d")
494 // ObjC string uses the same format specifiers as C string, so we can use
495 // the same format string checking logic for both ObjC and C strings.
Ted Kremenek8c797c02009-01-12 23:09:09 +0000496 bool isFExpr = SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx);
Ted Kremenek225a14c2008-06-16 18:00:42 +0000497
Ted Kremenek8c797c02009-01-12 23:09:09 +0000498 if (!isFExpr) {
Ted Kremenek19398b62007-12-17 19:03:13 +0000499 // For vprintf* functions (i.e., HasVAListArg==true), we add a
500 // special check to see if the format string is a function parameter
501 // of the function calling the printf function. If the function
502 // has an attribute indicating it is a printf-like function, then we
503 // should suppress warnings concerning non-literals being used in a call
504 // to a vprintf function. For example:
505 //
506 // void
507 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...) {
508 // va_list ap;
509 // va_start(ap, fmt);
510 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
511 // ...
512 //
513 //
514 // FIXME: We don't have full attribute support yet, so just check to see
515 // if the argument is a DeclRefExpr that references a parameter. We'll
516 // add proper support for checking the attribute later.
517 if (HasVAListArg)
Chris Lattner3d5a8f32007-12-28 05:38:24 +0000518 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(OrigFormatExpr))
519 if (isa<ParmVarDecl>(DR->getDecl()))
Ted Kremenek19398b62007-12-17 19:03:13 +0000520 return;
Ted Kremenek8c797c02009-01-12 23:09:09 +0000521
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000522 Diag(TheCall->getArg(format_idx)->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000523 diag::warn_printf_not_string_constant)
524 << OrigFormatExpr->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +0000525 return;
526 }
Ted Kremenek8c797c02009-01-12 23:09:09 +0000527}
Ted Kremenek081ed872007-08-14 17:39:48 +0000528
Ted Kremenek8c797c02009-01-12 23:09:09 +0000529void Sema::CheckPrintfString(StringLiteral *FExpr, Expr *OrigFormatExpr,
530 CallExpr *TheCall, bool HasVAListArg, unsigned format_idx) {
531
532 ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(OrigFormatExpr);
Ted Kremenek081ed872007-08-14 17:39:48 +0000533 // CHECK: is the format string a wide literal?
534 if (FExpr->isWide()) {
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000535 Diag(FExpr->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000536 diag::warn_printf_format_string_is_wide_literal)
537 << OrigFormatExpr->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +0000538 return;
539 }
540
541 // Str - The format string. NOTE: this is NOT null-terminated!
542 const char * const Str = FExpr->getStrData();
543
544 // CHECK: empty format string?
545 const unsigned StrLen = FExpr->getByteLength();
546
547 if (StrLen == 0) {
Chris Lattner9d2cf082008-11-19 05:27:50 +0000548 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string)
549 << OrigFormatExpr->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +0000550 return;
551 }
552
553 // We process the format string using a binary state machine. The
554 // current state is stored in CurrentState.
555 enum {
556 state_OrdChr,
557 state_Conversion
558 } CurrentState = state_OrdChr;
559
560 // numConversions - The number of conversions seen so far. This is
561 // incremented as we traverse the format string.
562 unsigned numConversions = 0;
563
564 // numDataArgs - The number of data arguments after the format
565 // string. This can only be determined for non vprintf-like
566 // functions. For those functions, this value is 1 (the sole
567 // va_arg argument).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000568 unsigned numDataArgs = TheCall->getNumArgs()-(format_idx+1);
Ted Kremenek081ed872007-08-14 17:39:48 +0000569
570 // Inspect the format string.
571 unsigned StrIdx = 0;
572
573 // LastConversionIdx - Index within the format string where we last saw
574 // a '%' character that starts a new format conversion.
575 unsigned LastConversionIdx = 0;
576
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000577 for (; StrIdx < StrLen; ++StrIdx) {
Chris Lattner3d5a8f32007-12-28 05:38:24 +0000578
Ted Kremenek081ed872007-08-14 17:39:48 +0000579 // Is the number of detected conversion conversions greater than
580 // the number of matching data arguments? If so, stop.
581 if (!HasVAListArg && numConversions > numDataArgs) break;
582
583 // Handle "\0"
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000584 if (Str[StrIdx] == '\0') {
Ted Kremenek081ed872007-08-14 17:39:48 +0000585 // The string returned by getStrData() is not null-terminated,
586 // so the presence of a null character is likely an error.
Chris Lattner3d5a8f32007-12-28 05:38:24 +0000587 Diag(PP.AdvanceToTokenCharacter(FExpr->getLocStart(), StrIdx+1),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000588 diag::warn_printf_format_string_contains_null_char)
589 << OrigFormatExpr->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +0000590 return;
591 }
592
593 // Ordinary characters (not processing a format conversion).
594 if (CurrentState == state_OrdChr) {
595 if (Str[StrIdx] == '%') {
596 CurrentState = state_Conversion;
597 LastConversionIdx = StrIdx;
598 }
599 continue;
600 }
601
602 // Seen '%'. Now processing a format conversion.
603 switch (Str[StrIdx]) {
Chris Lattner68d88f02007-12-28 05:31:15 +0000604 // Handle dynamic precision or width specifier.
605 case '*': {
606 ++numConversions;
607
608 if (!HasVAListArg && numConversions > numDataArgs) {
Chris Lattner68d88f02007-12-28 05:31:15 +0000609 SourceLocation Loc = FExpr->getLocStart();
610 Loc = PP.AdvanceToTokenCharacter(Loc, StrIdx+1);
Ted Kremenek035d8792007-10-12 20:51:52 +0000611
Ted Kremenek035d8792007-10-12 20:51:52 +0000612 if (Str[StrIdx-1] == '.')
Chris Lattner9d2cf082008-11-19 05:27:50 +0000613 Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg)
614 << OrigFormatExpr->getSourceRange();
Ted Kremenek035d8792007-10-12 20:51:52 +0000615 else
Chris Lattner9d2cf082008-11-19 05:27:50 +0000616 Diag(Loc, diag::warn_printf_asterisk_width_missing_arg)
617 << OrigFormatExpr->getSourceRange();
Ted Kremenek035d8792007-10-12 20:51:52 +0000618
Chris Lattner68d88f02007-12-28 05:31:15 +0000619 // Don't do any more checking. We'll just emit spurious errors.
620 return;
Ted Kremenek035d8792007-10-12 20:51:52 +0000621 }
Chris Lattner68d88f02007-12-28 05:31:15 +0000622
623 // Perform type checking on width/precision specifier.
624 Expr *E = TheCall->getArg(format_idx+numConversions);
625 if (const BuiltinType *BT = E->getType()->getAsBuiltinType())
626 if (BT->getKind() == BuiltinType::Int)
627 break;
Ted Kremenek081ed872007-08-14 17:39:48 +0000628
Chris Lattner68d88f02007-12-28 05:31:15 +0000629 SourceLocation Loc =
630 PP.AdvanceToTokenCharacter(FExpr->getLocStart(), StrIdx+1);
631
632 if (Str[StrIdx-1] == '.')
Chris Lattner9d2cf082008-11-19 05:27:50 +0000633 Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000634 << E->getType() << E->getSourceRange();
Chris Lattner68d88f02007-12-28 05:31:15 +0000635 else
Chris Lattner9d2cf082008-11-19 05:27:50 +0000636 Diag(Loc, diag::warn_printf_asterisk_width_wrong_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000637 << E->getType() << E->getSourceRange();
Chris Lattner68d88f02007-12-28 05:31:15 +0000638
639 break;
640 }
641
642 // Characters which can terminate a format conversion
643 // (e.g. "%d"). Characters that specify length modifiers or
644 // other flags are handled by the default case below.
645 //
646 // FIXME: additional checks will go into the following cases.
647 case 'i':
648 case 'd':
649 case 'o':
650 case 'u':
651 case 'x':
652 case 'X':
653 case 'D':
654 case 'O':
655 case 'U':
656 case 'e':
657 case 'E':
658 case 'f':
659 case 'F':
660 case 'g':
661 case 'G':
662 case 'a':
663 case 'A':
664 case 'c':
665 case 'C':
666 case 'S':
667 case 's':
668 case 'p':
669 ++numConversions;
670 CurrentState = state_OrdChr;
671 break;
672
673 // CHECK: Are we using "%n"? Issue a warning.
674 case 'n': {
675 ++numConversions;
676 CurrentState = state_OrdChr;
677 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
678 LastConversionIdx+1);
679
Chris Lattner9d2cf082008-11-19 05:27:50 +0000680 Diag(Loc, diag::warn_printf_write_back)<<OrigFormatExpr->getSourceRange();
Chris Lattner68d88f02007-12-28 05:31:15 +0000681 break;
682 }
Ted Kremenek225a14c2008-06-16 18:00:42 +0000683
684 // Handle "%@"
685 case '@':
686 // %@ is allowed in ObjC format strings only.
687 if(ObjCFExpr != NULL)
688 CurrentState = state_OrdChr;
689 else {
690 // Issue a warning: invalid format conversion.
691 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
692 LastConversionIdx+1);
693
Chris Lattner77d52da2008-11-20 06:06:08 +0000694 Diag(Loc, diag::warn_printf_invalid_conversion)
695 << std::string(Str+LastConversionIdx,
696 Str+std::min(LastConversionIdx+2, StrLen))
697 << OrigFormatExpr->getSourceRange();
Ted Kremenek225a14c2008-06-16 18:00:42 +0000698 }
699 ++numConversions;
700 break;
701
Chris Lattner68d88f02007-12-28 05:31:15 +0000702 // Handle "%%"
703 case '%':
704 // Sanity check: Was the first "%" character the previous one?
705 // If not, we will assume that we have a malformed format
706 // conversion, and that the current "%" character is the start
707 // of a new conversion.
708 if (StrIdx - LastConversionIdx == 1)
709 CurrentState = state_OrdChr;
710 else {
711 // Issue a warning: invalid format conversion.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000712 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
713 LastConversionIdx+1);
Chris Lattner68d88f02007-12-28 05:31:15 +0000714
Chris Lattner77d52da2008-11-20 06:06:08 +0000715 Diag(Loc, diag::warn_printf_invalid_conversion)
716 << std::string(Str+LastConversionIdx, Str+StrIdx)
717 << OrigFormatExpr->getSourceRange();
Chris Lattner68d88f02007-12-28 05:31:15 +0000718
719 // This conversion is broken. Advance to the next format
720 // conversion.
721 LastConversionIdx = StrIdx;
722 ++numConversions;
Ted Kremenek081ed872007-08-14 17:39:48 +0000723 }
Chris Lattner68d88f02007-12-28 05:31:15 +0000724 break;
Ted Kremenek081ed872007-08-14 17:39:48 +0000725
Chris Lattner68d88f02007-12-28 05:31:15 +0000726 default:
727 // This case catches all other characters: flags, widths, etc.
728 // We should eventually process those as well.
729 break;
Ted Kremenek081ed872007-08-14 17:39:48 +0000730 }
731 }
732
733 if (CurrentState == state_Conversion) {
734 // Issue a warning: invalid format conversion.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000735 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
736 LastConversionIdx+1);
Ted Kremenek081ed872007-08-14 17:39:48 +0000737
Chris Lattner77d52da2008-11-20 06:06:08 +0000738 Diag(Loc, diag::warn_printf_invalid_conversion)
739 << std::string(Str+LastConversionIdx,
740 Str+std::min(LastConversionIdx+2, StrLen))
741 << OrigFormatExpr->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +0000742 return;
743 }
744
745 if (!HasVAListArg) {
746 // CHECK: Does the number of format conversions exceed the number
747 // of data arguments?
748 if (numConversions > numDataArgs) {
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000749 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
750 LastConversionIdx);
Ted Kremenek081ed872007-08-14 17:39:48 +0000751
Chris Lattner9d2cf082008-11-19 05:27:50 +0000752 Diag(Loc, diag::warn_printf_insufficient_data_args)
753 << OrigFormatExpr->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +0000754 }
755 // CHECK: Does the number of data arguments exceed the number of
756 // format conversions in the format string?
757 else if (numConversions < numDataArgs)
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000758 Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000759 diag::warn_printf_too_many_data_args)
760 << OrigFormatExpr->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +0000761 }
762}
Ted Kremenek45925ab2007-08-17 16:46:58 +0000763
764//===--- CHECK: Return Address of Stack Variable --------------------------===//
765
766static DeclRefExpr* EvalVal(Expr *E);
767static DeclRefExpr* EvalAddr(Expr* E);
768
769/// CheckReturnStackAddr - Check if a return statement returns the address
770/// of a stack variable.
771void
772Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
773 SourceLocation ReturnLoc) {
Chris Lattner7a48d9c2008-02-13 01:02:39 +0000774
Ted Kremenek45925ab2007-08-17 16:46:58 +0000775 // Perform checking for returned stack addresses.
Steve Naroffd6163f32008-09-05 22:11:13 +0000776 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Ted Kremenek45925ab2007-08-17 16:46:58 +0000777 if (DeclRefExpr *DR = EvalAddr(RetValExp))
Chris Lattner65cae292008-11-19 08:23:25 +0000778 Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
Chris Lattnerb1753422008-11-23 21:45:46 +0000779 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Steve Naroff503996b2008-09-16 22:25:10 +0000780
781 // Skip over implicit cast expressions when checking for block expressions.
782 if (ImplicitCastExpr *IcExpr =
783 dyn_cast_or_null<ImplicitCastExpr>(RetValExp))
784 RetValExp = IcExpr->getSubExpr();
785
Steve Naroff3eac7692008-09-10 19:17:48 +0000786 if (BlockExpr *C = dyn_cast_or_null<BlockExpr>(RetValExp))
Chris Lattner9d2cf082008-11-19 05:27:50 +0000787 Diag(C->getLocStart(), diag::err_ret_local_block)
788 << C->getSourceRange();
Ted Kremenek45925ab2007-08-17 16:46:58 +0000789 }
790 // Perform checking for stack values returned by reference.
791 else if (lhsType->isReferenceType()) {
Douglas Gregor21a04f32008-10-27 19:41:14 +0000792 // Check for a reference to the stack
793 if (DeclRefExpr *DR = EvalVal(RetValExp))
Chris Lattner9d2cf082008-11-19 05:27:50 +0000794 Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
Chris Lattnerb1753422008-11-23 21:45:46 +0000795 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Ted Kremenek45925ab2007-08-17 16:46:58 +0000796 }
797}
798
799/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
800/// check if the expression in a return statement evaluates to an address
801/// to a location on the stack. The recursion is used to traverse the
802/// AST of the return expression, with recursion backtracking when we
803/// encounter a subexpression that (1) clearly does not lead to the address
804/// of a stack variable or (2) is something we cannot determine leads to
805/// the address of a stack variable based on such local checking.
806///
Ted Kremenekda1300a2007-08-28 17:02:55 +0000807/// EvalAddr processes expressions that are pointers that are used as
808/// references (and not L-values). EvalVal handles all other values.
Ted Kremenek45925ab2007-08-17 16:46:58 +0000809/// At the base case of the recursion is a check for a DeclRefExpr* in
810/// the refers to a stack variable.
811///
812/// This implementation handles:
813///
814/// * pointer-to-pointer casts
815/// * implicit conversions from array references to pointers
816/// * taking the address of fields
817/// * arbitrary interplay between "&" and "*" operators
818/// * pointer arithmetic from an address of a stack variable
819/// * taking the address of an array element where the array is on the stack
820static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek45925ab2007-08-17 16:46:58 +0000821 // We should only be called for evaluating pointer expressions.
Steve Naroffd6163f32008-09-05 22:11:13 +0000822 assert((E->getType()->isPointerType() ||
823 E->getType()->isBlockPointerType() ||
Ted Kremenek42730c52008-01-07 19:49:32 +0000824 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner68d88f02007-12-28 05:31:15 +0000825 "EvalAddr only works on pointers");
Ted Kremenek45925ab2007-08-17 16:46:58 +0000826
827 // Our "symbolic interpreter" is just a dispatch off the currently
828 // viewed AST node. We then recursively traverse the AST by calling
829 // EvalAddr and EvalVal appropriately.
830 switch (E->getStmtClass()) {
Chris Lattner68d88f02007-12-28 05:31:15 +0000831 case Stmt::ParenExprClass:
832 // Ignore parentheses.
833 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek45925ab2007-08-17 16:46:58 +0000834
Chris Lattner68d88f02007-12-28 05:31:15 +0000835 case Stmt::UnaryOperatorClass: {
836 // The only unary operator that make sense to handle here
837 // is AddrOf. All others don't make sense as pointers.
838 UnaryOperator *U = cast<UnaryOperator>(E);
Ted Kremenek45925ab2007-08-17 16:46:58 +0000839
Chris Lattner68d88f02007-12-28 05:31:15 +0000840 if (U->getOpcode() == UnaryOperator::AddrOf)
841 return EvalVal(U->getSubExpr());
842 else
Ted Kremenek45925ab2007-08-17 16:46:58 +0000843 return NULL;
844 }
Chris Lattner68d88f02007-12-28 05:31:15 +0000845
846 case Stmt::BinaryOperatorClass: {
847 // Handle pointer arithmetic. All other binary operators are not valid
848 // in this context.
849 BinaryOperator *B = cast<BinaryOperator>(E);
850 BinaryOperator::Opcode op = B->getOpcode();
851
852 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
853 return NULL;
854
855 Expr *Base = B->getLHS();
856
857 // Determine which argument is the real pointer base. It could be
858 // the RHS argument instead of the LHS.
859 if (!Base->getType()->isPointerType()) Base = B->getRHS();
860
861 assert (Base->getType()->isPointerType());
862 return EvalAddr(Base);
863 }
Steve Naroff3eac7692008-09-10 19:17:48 +0000864
Chris Lattner68d88f02007-12-28 05:31:15 +0000865 // For conditional operators we need to see if either the LHS or RHS are
866 // valid DeclRefExpr*s. If one of them is valid, we return it.
867 case Stmt::ConditionalOperatorClass: {
868 ConditionalOperator *C = cast<ConditionalOperator>(E);
869
870 // Handle the GNU extension for missing LHS.
871 if (Expr *lhsExpr = C->getLHS())
872 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
873 return LHS;
874
875 return EvalAddr(C->getRHS());
876 }
877
Ted Kremenekea19edd2008-08-07 00:49:01 +0000878 // For casts, we need to handle conversions from arrays to
879 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor21a04f32008-10-27 19:41:14 +0000880 case Stmt::ImplicitCastExprClass:
Douglas Gregor035d0882008-10-28 15:36:24 +0000881 case Stmt::CStyleCastExprClass:
Douglas Gregor21a04f32008-10-27 19:41:14 +0000882 case Stmt::CXXFunctionalCastExprClass: {
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +0000883 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenekea19edd2008-08-07 00:49:01 +0000884 QualType T = SubExpr->getType();
885
Steve Naroffd6163f32008-09-05 22:11:13 +0000886 if (SubExpr->getType()->isPointerType() ||
887 SubExpr->getType()->isBlockPointerType() ||
888 SubExpr->getType()->isObjCQualifiedIdType())
Ted Kremenekea19edd2008-08-07 00:49:01 +0000889 return EvalAddr(SubExpr);
890 else if (T->isArrayType())
Chris Lattner68d88f02007-12-28 05:31:15 +0000891 return EvalVal(SubExpr);
Chris Lattner68d88f02007-12-28 05:31:15 +0000892 else
Ted Kremenekea19edd2008-08-07 00:49:01 +0000893 return 0;
Chris Lattner68d88f02007-12-28 05:31:15 +0000894 }
895
896 // C++ casts. For dynamic casts, static casts, and const casts, we
897 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor21a04f32008-10-27 19:41:14 +0000898 // through the cast. In the case the dynamic cast doesn't fail (and
899 // return NULL), we take the conservative route and report cases
Chris Lattner68d88f02007-12-28 05:31:15 +0000900 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor21a04f32008-10-27 19:41:14 +0000901 // FIXME: The comment about is wrong; we're not always converting
902 // from pointer to pointer. I'm guessing that this code should also
903 // handle references to objects.
904 case Stmt::CXXStaticCastExprClass:
905 case Stmt::CXXDynamicCastExprClass:
906 case Stmt::CXXConstCastExprClass:
907 case Stmt::CXXReinterpretCastExprClass: {
908 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffd6163f32008-09-05 22:11:13 +0000909 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Chris Lattner68d88f02007-12-28 05:31:15 +0000910 return EvalAddr(S);
911 else
912 return NULL;
Chris Lattner68d88f02007-12-28 05:31:15 +0000913 }
914
915 // Everything else: we simply don't reason about them.
916 default:
917 return NULL;
918 }
Ted Kremenek45925ab2007-08-17 16:46:58 +0000919}
920
921
922/// EvalVal - This function is complements EvalAddr in the mutual recursion.
923/// See the comments for EvalAddr for more details.
924static DeclRefExpr* EvalVal(Expr *E) {
925
Ted Kremenekda1300a2007-08-28 17:02:55 +0000926 // We should only be called for evaluating non-pointer expressions, or
927 // expressions with a pointer type that are not used as references but instead
928 // are l-values (e.g., DeclRefExpr with a pointer type).
929
Ted Kremenek45925ab2007-08-17 16:46:58 +0000930 // Our "symbolic interpreter" is just a dispatch off the currently
931 // viewed AST node. We then recursively traverse the AST by calling
932 // EvalAddr and EvalVal appropriately.
933 switch (E->getStmtClass()) {
Douglas Gregor566782a2009-01-06 05:10:23 +0000934 case Stmt::DeclRefExprClass:
935 case Stmt::QualifiedDeclRefExprClass: {
Ted Kremenek45925ab2007-08-17 16:46:58 +0000936 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
937 // at code that refers to a variable's name. We check if it has local
938 // storage within the function, and if so, return the expression.
939 DeclRefExpr *DR = cast<DeclRefExpr>(E);
940
941 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Douglas Gregor81c29152008-10-29 00:13:59 +0000942 if(V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
Ted Kremenek45925ab2007-08-17 16:46:58 +0000943
944 return NULL;
945 }
946
947 case Stmt::ParenExprClass:
948 // Ignore parentheses.
949 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
950
951 case Stmt::UnaryOperatorClass: {
952 // The only unary operator that make sense to handle here
953 // is Deref. All others don't resolve to a "name." This includes
954 // handling all sorts of rvalues passed to a unary operator.
955 UnaryOperator *U = cast<UnaryOperator>(E);
956
957 if (U->getOpcode() == UnaryOperator::Deref)
958 return EvalAddr(U->getSubExpr());
959
960 return NULL;
961 }
962
963 case Stmt::ArraySubscriptExprClass: {
964 // Array subscripts are potential references to data on the stack. We
965 // retrieve the DeclRefExpr* for the array variable if it indeed
966 // has local storage.
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000967 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek45925ab2007-08-17 16:46:58 +0000968 }
969
970 case Stmt::ConditionalOperatorClass: {
971 // For conditional operators we need to see if either the LHS or RHS are
972 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
973 ConditionalOperator *C = cast<ConditionalOperator>(E);
974
Anders Carlsson37365fc2007-11-30 19:04:31 +0000975 // Handle the GNU extension for missing LHS.
976 if (Expr *lhsExpr = C->getLHS())
977 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
978 return LHS;
979
980 return EvalVal(C->getRHS());
Ted Kremenek45925ab2007-08-17 16:46:58 +0000981 }
982
983 // Accesses to members are potential references to data on the stack.
984 case Stmt::MemberExprClass: {
985 MemberExpr *M = cast<MemberExpr>(E);
986
987 // Check for indirect access. We only want direct field accesses.
988 if (!M->isArrow())
989 return EvalVal(M->getBase());
990 else
991 return NULL;
992 }
993
994 // Everything else: we simply don't reason about them.
995 default:
996 return NULL;
997 }
998}
Ted Kremenek30c66752007-11-25 00:58:00 +0000999
1000//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
1001
1002/// Check for comparisons of floating point operands using != and ==.
1003/// Issue a warning if these are no self-comparisons, as they are not likely
1004/// to do what the programmer intended.
1005void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
1006 bool EmitWarning = true;
1007
Ted Kremenek87e30c52008-01-17 16:57:34 +00001008 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek24c61682008-01-17 17:55:13 +00001009 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek30c66752007-11-25 00:58:00 +00001010
1011 // Special case: check for x == x (which is OK).
1012 // Do not emit warnings for such cases.
1013 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
1014 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
1015 if (DRL->getDecl() == DRR->getDecl())
1016 EmitWarning = false;
1017
Ted Kremenek33159832007-11-29 00:59:04 +00001018
1019 // Special case: check for comparisons against literals that can be exactly
1020 // represented by APFloat. In such cases, do not emit a warning. This
1021 // is a heuristic: often comparison against such literals are used to
1022 // detect if a value in a variable has not changed. This clearly can
1023 // lead to false negatives.
1024 if (EmitWarning) {
1025 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
1026 if (FLL->isExact())
1027 EmitWarning = false;
1028 }
1029 else
1030 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
1031 if (FLR->isExact())
1032 EmitWarning = false;
1033 }
1034 }
1035
Ted Kremenek30c66752007-11-25 00:58:00 +00001036 // Check for comparisons with builtin types.
Sebastian Redl8b769972009-01-19 00:08:26 +00001037 if (EmitWarning)
Ted Kremenek30c66752007-11-25 00:58:00 +00001038 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
1039 if (isCallBuiltin(CL))
1040 EmitWarning = false;
1041
Sebastian Redl8b769972009-01-19 00:08:26 +00001042 if (EmitWarning)
Ted Kremenek30c66752007-11-25 00:58:00 +00001043 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
1044 if (isCallBuiltin(CR))
1045 EmitWarning = false;
1046
1047 // Emit the diagnostic.
1048 if (EmitWarning)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001049 Diag(loc, diag::warn_floatingpoint_eq)
1050 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek30c66752007-11-25 00:58:00 +00001051}