blob: e52c73044232747742ecea6341a859424257c055 [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"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000017#include "clang/AST/DeclObjC.h"
Ted Kremenek23245122007-08-20 16:18:38 +000018#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000019#include "clang/AST/ExprObjC.h"
Chris Lattner59907c42007-08-10 20:18:51 +000020#include "clang/Lex/Preprocessor.h"
Ted Kremenek588e5eb2007-11-25 00:58:00 +000021#include "SemaUtil.h"
Chris Lattner59907c42007-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 Redl0eb23302009-01-19 00:08:26 +000026Action::OwningExprResult
27Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
28 OwningExprResult TheCallResult(Owned(TheCall));
Chris Lattner59907c42007-08-10 20:18:51 +000029 // Get the IdentifierInfo* for the called function.
30 IdentifierInfo *FnInfo = FDecl->getIdentifier();
Douglas Gregor2def4832008-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 Redl0eb23302009-01-19 00:08:26 +000035 return move(TheCallResult);
Douglas Gregor2def4832008-11-17 20:34:05 +000036
Chris Lattner30ce3442007-12-19 23:59:04 +000037 switch (FnInfo->getBuiltinID()) {
38 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +000039 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +000040 "Wrong # arguments to builtin CFStringMakeConstantString");
Eli Friedmane8018702008-05-16 17:51:27 +000041 if (CheckBuiltinCFStringArgument(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +000042 return ExprError();
43 return move(TheCallResult);
Ted Kremenek49ff7a12008-07-09 17:58:53 +000044 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +000045 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +000046 if (SemaBuiltinVAStart(TheCall))
47 return ExprError();
48 return move(TheCallResult);
Chris Lattner1b9a0792007-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 Redl0eb23302009-01-19 00:08:26 +000055 if (SemaBuiltinUnorderedCompare(TheCall))
56 return ExprError();
57 return move(TheCallResult);
Eli Friedman6cfda232008-05-20 08:23:37 +000058 case Builtin::BI__builtin_return_address:
59 case Builtin::BI__builtin_frame_address:
Sebastian Redl0eb23302009-01-19 00:08:26 +000060 if (SemaBuiltinStackAddress(TheCall))
61 return ExprError();
62 return move(TheCallResult);
Eli Friedmand38617c2008-05-14 19:38:39 +000063 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-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 Dunbar4493f792008-07-21 22:59:13 +000067 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +000068 if (SemaBuiltinPrefetch(TheCall))
69 return ExprError();
70 return move(TheCallResult);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +000071 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +000072 if (SemaBuiltinObjectSize(TheCall))
73 return ExprError();
Anders Carlsson71993dd2007-08-17 05:31:46 +000074 }
Daniel Dunbarde454282008-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 Lattner59907c42007-08-10 20:18:51 +000080 // Search the KnownFunctionIDs for the identifier.
81 unsigned i = 0, e = id_num_known_functions;
Ted Kremenek71895b92007-08-14 17:39:48 +000082 for (; i != e; ++i) { if (KnownFunctionIDs[i] == FnInfo) break; }
Sebastian Redl0eb23302009-01-19 00:08:26 +000083 if (i == e) return move(TheCallResult);
84
Chris Lattner59907c42007-08-10 20:18:51 +000085 // Printf checking.
86 if (i <= id_vprintf) {
Ted Kremenek71895b92007-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 Lattner59907c42007-08-10 20:18:51 +000089 unsigned format_idx = 0;
Ted Kremenek71895b92007-08-14 17:39:48 +000090 bool HasVAListArg = false;
Sebastian Redl0eb23302009-01-19 00:08:26 +000091
Chris Lattner59907c42007-08-10 20:18:51 +000092 switch (i) {
Chris Lattner30ce3442007-12-19 23:59:04 +000093 default: assert(false && "No format string argument index.");
Daniel Dunbarde454282008-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 Kremenek71895b92007-08-14 17:39:48 +0000109 }
Sebastian Redl0eb23302009-01-19 00:08:26 +0000110
111 CheckPrintfArguments(TheCall, HasVAListArg, format_idx);
Chris Lattner59907c42007-08-10 20:18:51 +0000112 }
Sebastian Redl0eb23302009-01-19 00:08:26 +0000113
114 return move(TheCallResult);
Anders Carlsson71993dd2007-08-17 05:31:46 +0000115}
116
117/// CheckBuiltinCFStringArgument - Checks that the argument to the builtin
118/// CFString constructor is correct
Chris Lattnercc6f65d2007-08-25 05:30:33 +0000119bool Sema::CheckBuiltinCFStringArgument(Expr* Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000120 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000121
122 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
123
124 if (!Literal || Literal->isWide()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000125 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
126 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000127 return true;
Anders Carlsson71993dd2007-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 Lattnerfa25bbb2008-11-19 05:08:23 +0000136 diag::warn_cfstring_literal_contains_non_ascii_character)
137 << Arg->getSourceRange();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000138 break;
139 }
140
141 if (!Data[i]) {
142 Diag(PP.AdvanceToTokenCharacter(Arg->getLocStart(), i + 1),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000143 diag::warn_cfstring_literal_contains_nul_character)
144 << Arg->getSourceRange();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000145 break;
146 }
147 }
148
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000149 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000150}
151
Chris Lattnerc27c6652007-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 Lattner925e60d2007-12-28 05:29:59 +0000154bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
155 Expr *Fn = TheCall->getCallee();
156 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000157 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000158 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000159 << 0 /*function call*/ << Fn->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000160 << SourceRange(TheCall->getArg(2)->getLocStart(),
161 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000162 return true;
163 }
Eli Friedman56f20ae2008-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 Lattnerc27c6652007-12-20 00:05:45 +0000170 // Determine whether the current function is variadic or not.
171 bool isVariadic;
Eli Friedman56f20ae2008-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 {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000179 isVariadic = getCurMethodDecl()->isVariadic();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000180 }
Chris Lattner30ce3442007-12-19 23:59:04 +0000181
Chris Lattnerc27c6652007-12-20 00:05:45 +0000182 if (!isVariadic) {
Chris Lattner30ce3442007-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 Carlssone2c14102008-02-13 01:22:59 +0000190 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Anders Carlsson88cf2262008-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 Lattner30ce3442007-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 Carlsson88cf2262008-02-11 04:20:54 +0000196 const ParmVarDecl *LastArg;
Chris Lattner371f2582008-12-04 23:50:19 +0000197 if (FunctionDecl *FD = getCurFunctionDecl())
198 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000199 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000200 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000201 SecondArgIsLastNamedArgument = PV == LastArg;
202 }
203 }
204
205 if (!SecondArgIsLastNamedArgument)
Chris Lattner925e60d2007-12-28 05:29:59 +0000206 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000207 diag::warn_second_parameter_of_va_start_not_last_named_argument);
208 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000209}
Chris Lattner30ce3442007-12-19 23:59:04 +0000210
Chris Lattner1b9a0792007-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 Lattner925e60d2007-12-28 05:29:59 +0000213bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
214 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000215 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
216 << 0 /*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000217 if (TheCall->getNumArgs() > 2)
218 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000219 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000220 << 0 /*function call*/
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000221 << SourceRange(TheCall->getArg(2)->getLocStart(),
222 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner1b9a0792007-12-20 00:26:33 +0000223
Chris Lattner925e60d2007-12-28 05:29:59 +0000224 Expr *OrigArg0 = TheCall->getArg(0);
225 Expr *OrigArg1 = TheCall->getArg(1);
Chris Lattner1b9a0792007-12-20 00:26:33 +0000226
227 // Do standard promotions between the two arguments, returning their common
228 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000229 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Chris Lattner1b9a0792007-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 Lattner925e60d2007-12-28 05:29:59 +0000234 return Diag(OrigArg0->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000235 diag::err_typecheck_call_invalid_ordered_compare)
Chris Lattnerd1625842008-11-24 06:25:27 +0000236 << OrigArg0->getType() << OrigArg1->getType()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000237 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
Chris Lattner1b9a0792007-12-20 00:26:33 +0000238
239 return false;
240}
241
Eli Friedman6cfda232008-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 Lattnerd1a0b6d2008-08-10 02:05:13 +0000246 if (!TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc))
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000247 return Diag(Loc, diag::err_stack_const_level) << TheCall->getSourceRange();
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000248
Eli Friedman6cfda232008-05-20 08:23:37 +0000249 return false;
250}
251
Eli Friedmand38617c2008-05-14 19:38:39 +0000252/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
253// This is declared to take (...), so we have to check everything.
Sebastian Redl0eb23302009-01-19 00:08:26 +0000254Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000255 if (TheCall->getNumArgs() < 3)
Sebastian Redl0eb23302009-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 Friedmand38617c2008-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 Lattnerfa25bbb2008-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 Redl0eb23302009-01-19 00:08:26 +0000267 return ExprError();
Eli Friedmand38617c2008-05-14 19:38:39 +0000268 }
269
Chris Lattnerb77792e2008-07-26 22:17:49 +0000270 if (Context.getCanonicalType(FAType).getUnqualifiedType() !=
271 Context.getCanonicalType(SAType).getUnqualifiedType()) {
Chris Lattnerfa25bbb2008-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 Redl0eb23302009-01-19 00:08:26 +0000275 return ExprError();
Eli Friedmand38617c2008-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 Redl0eb23302009-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 Friedmand38617c2008-05-14 19:38:39 +0000287 }
288
289 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
290 llvm::APSInt Result(32);
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000291 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000292 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000293 diag::err_shufflevector_nonconstant_argument)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000294 << TheCall->getArg(i)->getSourceRange());
295
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000296 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000297 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000298 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000299 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000300 }
301
302 llvm::SmallVector<Expr*, 32> exprs;
303
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000304 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000305 exprs.push_back(TheCall->getArg(i));
306 TheCall->setArg(i, 0);
307 }
308
Ted Kremenek8189cde2009-02-07 01:47:29 +0000309 return Owned(new (Context) ShuffleVectorExpr(exprs.begin(), numElements+2,
310 FAType,
311 TheCall->getCallee()->getLocStart(),
312 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000313}
Chris Lattner30ce3442007-12-19 23:59:04 +0000314
Daniel Dunbar4493f792008-07-21 22:59:13 +0000315/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
316// This is declared to take (const void*, ...) and can take two
317// optional constant int args.
318bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000319 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000320
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000321 if (NumArgs > 3)
322 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000323 << 0 /*function call*/ << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000324
325 // Argument 0 is checked for us and the remaining arguments must be
326 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000327 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000328 Expr *Arg = TheCall->getArg(i);
329 QualType RWType = Arg->getType();
330
331 const BuiltinType *BT = RWType->getAsBuiltinType();
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000332 llvm::APSInt Result;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000333 if (!BT || BT->getKind() != BuiltinType::Int ||
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000334 !Arg->isIntegerConstantExpr(Result, Context))
335 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument)
336 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar4493f792008-07-21 22:59:13 +0000337
338 // FIXME: gcc issues a warning and rewrites these to 0. These
339 // seems especially odd for the third argument since the default
340 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000341 if (i == 1) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000342 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000343 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
344 << "0" << "1" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar4493f792008-07-21 22:59:13 +0000345 } else {
346 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000347 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
348 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar4493f792008-07-21 22:59:13 +0000349 }
350 }
351
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000352 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000353}
354
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000355/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
356/// int type). This simply type checks that type is one of the defined
357/// constants (0-3).
358bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
359 Expr *Arg = TheCall->getArg(1);
360 QualType ArgType = Arg->getType();
361 const BuiltinType *BT = ArgType->getAsBuiltinType();
362 llvm::APSInt Result(32);
363 if (!BT || BT->getKind() != BuiltinType::Int ||
364 !Arg->isIntegerConstantExpr(Result, Context)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000365 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
366 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000367 }
368
369 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000370 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
371 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000372 }
373
374 return false;
375}
376
Ted Kremenekd30ef872009-01-12 23:09:09 +0000377// Handle i > 1 ? "x" : "y", recursivelly
378bool Sema::SemaCheckStringLiteral(Expr *E, CallExpr *TheCall, bool HasVAListArg,
379 unsigned format_idx) {
380
381 switch (E->getStmtClass()) {
382 case Stmt::ConditionalOperatorClass: {
383 ConditionalOperator *C = cast<ConditionalOperator>(E);
384 return SemaCheckStringLiteral(C->getLHS(), TheCall,
385 HasVAListArg, format_idx)
386 && SemaCheckStringLiteral(C->getRHS(), TheCall,
387 HasVAListArg, format_idx);
388 }
389
390 case Stmt::ImplicitCastExprClass: {
391 ImplicitCastExpr *Expr = dyn_cast<ImplicitCastExpr>(E);
392 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
393 format_idx);
394 }
395
396 case Stmt::ParenExprClass: {
397 ParenExpr *Expr = dyn_cast<ParenExpr>(E);
398 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
399 format_idx);
400 }
401
402 default: {
403 ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E);
404 StringLiteral *StrE = NULL;
405
406 if (ObjCFExpr)
407 StrE = ObjCFExpr->getString();
408 else
409 StrE = dyn_cast<StringLiteral>(E);
410
411 if (StrE) {
412 CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx);
413 return true;
414 }
415
416 return false;
417 }
418 }
419}
420
421
Chris Lattner59907c42007-08-10 20:18:51 +0000422/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Ted Kremenek71895b92007-08-14 17:39:48 +0000423/// correct use of format strings.
424///
425/// HasVAListArg - A predicate indicating whether the printf-like
426/// function is passed an explicit va_arg argument (e.g., vprintf)
427///
428/// format_idx - The index into Args for the format string.
429///
430/// Improper format strings to functions in the printf family can be
431/// the source of bizarre bugs and very serious security holes. A
432/// good source of information is available in the following paper
433/// (which includes additional references):
Chris Lattner59907c42007-08-10 20:18:51 +0000434///
435/// FormatGuard: Automatic Protection From printf Format String
436/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremenek71895b92007-08-14 17:39:48 +0000437///
438/// Functionality implemented:
439///
440/// We can statically check the following properties for string
441/// literal format strings for non v.*printf functions (where the
442/// arguments are passed directly):
443//
444/// (1) Are the number of format conversions equal to the number of
445/// data arguments?
446///
447/// (2) Does each format conversion correctly match the type of the
448/// corresponding data argument? (TODO)
449///
450/// Moreover, for all printf functions we can:
451///
452/// (3) Check for a missing format string (when not caught by type checking).
453///
454/// (4) Check for no-operation flags; e.g. using "#" with format
455/// conversion 'c' (TODO)
456///
457/// (5) Check the use of '%n', a major source of security holes.
458///
459/// (6) Check for malformed format conversions that don't specify anything.
460///
461/// (7) Check for empty format strings. e.g: printf("");
462///
463/// (8) Check that the format string is a wide literal.
464///
Ted Kremenek6d439592008-03-03 16:50:00 +0000465/// (9) Also check the arguments of functions with the __format__ attribute.
466/// (TODO).
467///
Ted Kremenek71895b92007-08-14 17:39:48 +0000468/// All of these checks can be done by parsing the format string.
469///
470/// For now, we ONLY do (1), (3), (5), (6), (7), and (8).
Chris Lattner59907c42007-08-10 20:18:51 +0000471void
Chris Lattner925e60d2007-12-28 05:29:59 +0000472Sema::CheckPrintfArguments(CallExpr *TheCall, bool HasVAListArg,
473 unsigned format_idx) {
474 Expr *Fn = TheCall->getCallee();
475
Ted Kremenek71895b92007-08-14 17:39:48 +0000476 // CHECK: printf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +0000477 if (format_idx >= TheCall->getNumArgs()) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000478 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string)
479 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000480 return;
481 }
482
Chris Lattner56f34942008-02-13 01:02:39 +0000483 Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Chris Lattner459e8482007-08-25 05:36:18 +0000484
Chris Lattner59907c42007-08-10 20:18:51 +0000485 // CHECK: format string is not a string literal.
486 //
Ted Kremenek71895b92007-08-14 17:39:48 +0000487 // Dynamically generated format strings are difficult to
488 // automatically vet at compile time. Requiring that format strings
489 // are string literals: (1) permits the checking of format strings by
490 // the compiler and thereby (2) can practically remove the source of
491 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000492
493 // Format string can be either ObjC string (e.g. @"%d") or
494 // C string (e.g. "%d")
495 // ObjC string uses the same format specifiers as C string, so we can use
496 // the same format string checking logic for both ObjC and C strings.
Ted Kremenekd30ef872009-01-12 23:09:09 +0000497 bool isFExpr = SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx);
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000498
Ted Kremenekd30ef872009-01-12 23:09:09 +0000499 if (!isFExpr) {
Ted Kremenek4a336462007-12-17 19:03:13 +0000500 // For vprintf* functions (i.e., HasVAListArg==true), we add a
501 // special check to see if the format string is a function parameter
502 // of the function calling the printf function. If the function
503 // has an attribute indicating it is a printf-like function, then we
504 // should suppress warnings concerning non-literals being used in a call
505 // to a vprintf function. For example:
506 //
507 // void
508 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...) {
509 // va_list ap;
510 // va_start(ap, fmt);
511 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
512 // ...
513 //
514 //
515 // FIXME: We don't have full attribute support yet, so just check to see
516 // if the argument is a DeclRefExpr that references a parameter. We'll
517 // add proper support for checking the attribute later.
518 if (HasVAListArg)
Chris Lattner998568f2007-12-28 05:38:24 +0000519 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(OrigFormatExpr))
520 if (isa<ParmVarDecl>(DR->getDecl()))
Ted Kremenek4a336462007-12-17 19:03:13 +0000521 return;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000522
Chris Lattner925e60d2007-12-28 05:29:59 +0000523 Diag(TheCall->getArg(format_idx)->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000524 diag::warn_printf_not_string_constant)
525 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000526 return;
527 }
Ted Kremenekd30ef872009-01-12 23:09:09 +0000528}
Ted Kremenek71895b92007-08-14 17:39:48 +0000529
Ted Kremenekd30ef872009-01-12 23:09:09 +0000530void Sema::CheckPrintfString(StringLiteral *FExpr, Expr *OrigFormatExpr,
531 CallExpr *TheCall, bool HasVAListArg, unsigned format_idx) {
532
533 ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(OrigFormatExpr);
Ted Kremenek71895b92007-08-14 17:39:48 +0000534 // CHECK: is the format string a wide literal?
535 if (FExpr->isWide()) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000536 Diag(FExpr->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000537 diag::warn_printf_format_string_is_wide_literal)
538 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000539 return;
540 }
541
542 // Str - The format string. NOTE: this is NOT null-terminated!
543 const char * const Str = FExpr->getStrData();
544
545 // CHECK: empty format string?
546 const unsigned StrLen = FExpr->getByteLength();
547
548 if (StrLen == 0) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000549 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string)
550 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000551 return;
552 }
553
554 // We process the format string using a binary state machine. The
555 // current state is stored in CurrentState.
556 enum {
557 state_OrdChr,
558 state_Conversion
559 } CurrentState = state_OrdChr;
560
561 // numConversions - The number of conversions seen so far. This is
562 // incremented as we traverse the format string.
563 unsigned numConversions = 0;
564
565 // numDataArgs - The number of data arguments after the format
566 // string. This can only be determined for non vprintf-like
567 // functions. For those functions, this value is 1 (the sole
568 // va_arg argument).
Chris Lattner925e60d2007-12-28 05:29:59 +0000569 unsigned numDataArgs = TheCall->getNumArgs()-(format_idx+1);
Ted Kremenek71895b92007-08-14 17:39:48 +0000570
571 // Inspect the format string.
572 unsigned StrIdx = 0;
573
574 // LastConversionIdx - Index within the format string where we last saw
575 // a '%' character that starts a new format conversion.
576 unsigned LastConversionIdx = 0;
577
Chris Lattner925e60d2007-12-28 05:29:59 +0000578 for (; StrIdx < StrLen; ++StrIdx) {
Chris Lattner998568f2007-12-28 05:38:24 +0000579
Ted Kremenek71895b92007-08-14 17:39:48 +0000580 // Is the number of detected conversion conversions greater than
581 // the number of matching data arguments? If so, stop.
582 if (!HasVAListArg && numConversions > numDataArgs) break;
583
584 // Handle "\0"
Chris Lattner925e60d2007-12-28 05:29:59 +0000585 if (Str[StrIdx] == '\0') {
Ted Kremenek71895b92007-08-14 17:39:48 +0000586 // The string returned by getStrData() is not null-terminated,
587 // so the presence of a null character is likely an error.
Chris Lattner998568f2007-12-28 05:38:24 +0000588 Diag(PP.AdvanceToTokenCharacter(FExpr->getLocStart(), StrIdx+1),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000589 diag::warn_printf_format_string_contains_null_char)
590 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000591 return;
592 }
593
594 // Ordinary characters (not processing a format conversion).
595 if (CurrentState == state_OrdChr) {
596 if (Str[StrIdx] == '%') {
597 CurrentState = state_Conversion;
598 LastConversionIdx = StrIdx;
599 }
600 continue;
601 }
602
603 // Seen '%'. Now processing a format conversion.
604 switch (Str[StrIdx]) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000605 // Handle dynamic precision or width specifier.
606 case '*': {
607 ++numConversions;
608
609 if (!HasVAListArg && numConversions > numDataArgs) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000610 SourceLocation Loc = FExpr->getLocStart();
611 Loc = PP.AdvanceToTokenCharacter(Loc, StrIdx+1);
Ted Kremenek580b6642007-10-12 20:51:52 +0000612
Ted Kremenek580b6642007-10-12 20:51:52 +0000613 if (Str[StrIdx-1] == '.')
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000614 Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg)
615 << OrigFormatExpr->getSourceRange();
Ted Kremenek580b6642007-10-12 20:51:52 +0000616 else
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000617 Diag(Loc, diag::warn_printf_asterisk_width_missing_arg)
618 << OrigFormatExpr->getSourceRange();
Ted Kremenek580b6642007-10-12 20:51:52 +0000619
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000620 // Don't do any more checking. We'll just emit spurious errors.
621 return;
Ted Kremenek580b6642007-10-12 20:51:52 +0000622 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000623
624 // Perform type checking on width/precision specifier.
625 Expr *E = TheCall->getArg(format_idx+numConversions);
626 if (const BuiltinType *BT = E->getType()->getAsBuiltinType())
627 if (BT->getKind() == BuiltinType::Int)
628 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000629
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000630 SourceLocation Loc =
631 PP.AdvanceToTokenCharacter(FExpr->getLocStart(), StrIdx+1);
632
633 if (Str[StrIdx-1] == '.')
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000634 Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000635 << E->getType() << E->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000636 else
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000637 Diag(Loc, diag::warn_printf_asterisk_width_wrong_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000638 << E->getType() << E->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000639
640 break;
641 }
642
643 // Characters which can terminate a format conversion
644 // (e.g. "%d"). Characters that specify length modifiers or
645 // other flags are handled by the default case below.
646 //
647 // FIXME: additional checks will go into the following cases.
648 case 'i':
649 case 'd':
650 case 'o':
651 case 'u':
652 case 'x':
653 case 'X':
654 case 'D':
655 case 'O':
656 case 'U':
657 case 'e':
658 case 'E':
659 case 'f':
660 case 'F':
661 case 'g':
662 case 'G':
663 case 'a':
664 case 'A':
665 case 'c':
666 case 'C':
667 case 'S':
668 case 's':
669 case 'p':
670 ++numConversions;
671 CurrentState = state_OrdChr;
672 break;
673
674 // CHECK: Are we using "%n"? Issue a warning.
675 case 'n': {
676 ++numConversions;
677 CurrentState = state_OrdChr;
678 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
679 LastConversionIdx+1);
680
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000681 Diag(Loc, diag::warn_printf_write_back)<<OrigFormatExpr->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000682 break;
683 }
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000684
685 // Handle "%@"
686 case '@':
687 // %@ is allowed in ObjC format strings only.
688 if(ObjCFExpr != NULL)
689 CurrentState = state_OrdChr;
690 else {
691 // Issue a warning: invalid format conversion.
692 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
693 LastConversionIdx+1);
694
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000695 Diag(Loc, diag::warn_printf_invalid_conversion)
696 << std::string(Str+LastConversionIdx,
697 Str+std::min(LastConversionIdx+2, StrLen))
698 << OrigFormatExpr->getSourceRange();
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000699 }
700 ++numConversions;
701 break;
702
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000703 // Handle "%%"
704 case '%':
705 // Sanity check: Was the first "%" character the previous one?
706 // If not, we will assume that we have a malformed format
707 // conversion, and that the current "%" character is the start
708 // of a new conversion.
709 if (StrIdx - LastConversionIdx == 1)
710 CurrentState = state_OrdChr;
711 else {
712 // Issue a warning: invalid format conversion.
Chris Lattner925e60d2007-12-28 05:29:59 +0000713 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
714 LastConversionIdx+1);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000715
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000716 Diag(Loc, diag::warn_printf_invalid_conversion)
717 << std::string(Str+LastConversionIdx, Str+StrIdx)
718 << OrigFormatExpr->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000719
720 // This conversion is broken. Advance to the next format
721 // conversion.
722 LastConversionIdx = StrIdx;
723 ++numConversions;
Ted Kremenek71895b92007-08-14 17:39:48 +0000724 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000725 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000726
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000727 default:
728 // This case catches all other characters: flags, widths, etc.
729 // We should eventually process those as well.
730 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000731 }
732 }
733
734 if (CurrentState == state_Conversion) {
735 // Issue a warning: invalid format conversion.
Chris Lattner925e60d2007-12-28 05:29:59 +0000736 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
737 LastConversionIdx+1);
Ted Kremenek71895b92007-08-14 17:39:48 +0000738
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000739 Diag(Loc, diag::warn_printf_invalid_conversion)
740 << std::string(Str+LastConversionIdx,
741 Str+std::min(LastConversionIdx+2, StrLen))
742 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000743 return;
744 }
745
746 if (!HasVAListArg) {
747 // CHECK: Does the number of format conversions exceed the number
748 // of data arguments?
749 if (numConversions > numDataArgs) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000750 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
751 LastConversionIdx);
Ted Kremenek71895b92007-08-14 17:39:48 +0000752
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000753 Diag(Loc, diag::warn_printf_insufficient_data_args)
754 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000755 }
756 // CHECK: Does the number of data arguments exceed the number of
757 // format conversions in the format string?
758 else if (numConversions < numDataArgs)
Chris Lattner925e60d2007-12-28 05:29:59 +0000759 Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000760 diag::warn_printf_too_many_data_args)
761 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000762 }
763}
Ted Kremenek06de2762007-08-17 16:46:58 +0000764
765//===--- CHECK: Return Address of Stack Variable --------------------------===//
766
767static DeclRefExpr* EvalVal(Expr *E);
768static DeclRefExpr* EvalAddr(Expr* E);
769
770/// CheckReturnStackAddr - Check if a return statement returns the address
771/// of a stack variable.
772void
773Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
774 SourceLocation ReturnLoc) {
Chris Lattner56f34942008-02-13 01:02:39 +0000775
Ted Kremenek06de2762007-08-17 16:46:58 +0000776 // Perform checking for returned stack addresses.
Steve Naroffdd972f22008-09-05 22:11:13 +0000777 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Ted Kremenek06de2762007-08-17 16:46:58 +0000778 if (DeclRefExpr *DR = EvalAddr(RetValExp))
Chris Lattner3c73c412008-11-19 08:23:25 +0000779 Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
Chris Lattner08631c52008-11-23 21:45:46 +0000780 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Steve Naroffc50a4a52008-09-16 22:25:10 +0000781
782 // Skip over implicit cast expressions when checking for block expressions.
783 if (ImplicitCastExpr *IcExpr =
784 dyn_cast_or_null<ImplicitCastExpr>(RetValExp))
785 RetValExp = IcExpr->getSubExpr();
786
Steve Naroff61f40a22008-09-10 19:17:48 +0000787 if (BlockExpr *C = dyn_cast_or_null<BlockExpr>(RetValExp))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000788 Diag(C->getLocStart(), diag::err_ret_local_block)
789 << C->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +0000790 }
791 // Perform checking for stack values returned by reference.
792 else if (lhsType->isReferenceType()) {
Douglas Gregor49badde2008-10-27 19:41:14 +0000793 // Check for a reference to the stack
794 if (DeclRefExpr *DR = EvalVal(RetValExp))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000795 Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
Chris Lattner08631c52008-11-23 21:45:46 +0000796 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +0000797 }
798}
799
800/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
801/// check if the expression in a return statement evaluates to an address
802/// to a location on the stack. The recursion is used to traverse the
803/// AST of the return expression, with recursion backtracking when we
804/// encounter a subexpression that (1) clearly does not lead to the address
805/// of a stack variable or (2) is something we cannot determine leads to
806/// the address of a stack variable based on such local checking.
807///
Ted Kremeneke8c600f2007-08-28 17:02:55 +0000808/// EvalAddr processes expressions that are pointers that are used as
809/// references (and not L-values). EvalVal handles all other values.
Ted Kremenek06de2762007-08-17 16:46:58 +0000810/// At the base case of the recursion is a check for a DeclRefExpr* in
811/// the refers to a stack variable.
812///
813/// This implementation handles:
814///
815/// * pointer-to-pointer casts
816/// * implicit conversions from array references to pointers
817/// * taking the address of fields
818/// * arbitrary interplay between "&" and "*" operators
819/// * pointer arithmetic from an address of a stack variable
820/// * taking the address of an array element where the array is on the stack
821static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek06de2762007-08-17 16:46:58 +0000822 // We should only be called for evaluating pointer expressions.
Steve Naroffdd972f22008-09-05 22:11:13 +0000823 assert((E->getType()->isPointerType() ||
824 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000825 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000826 "EvalAddr only works on pointers");
Ted Kremenek06de2762007-08-17 16:46:58 +0000827
828 // Our "symbolic interpreter" is just a dispatch off the currently
829 // viewed AST node. We then recursively traverse the AST by calling
830 // EvalAddr and EvalVal appropriately.
831 switch (E->getStmtClass()) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000832 case Stmt::ParenExprClass:
833 // Ignore parentheses.
834 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek06de2762007-08-17 16:46:58 +0000835
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000836 case Stmt::UnaryOperatorClass: {
837 // The only unary operator that make sense to handle here
838 // is AddrOf. All others don't make sense as pointers.
839 UnaryOperator *U = cast<UnaryOperator>(E);
Ted Kremenek06de2762007-08-17 16:46:58 +0000840
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000841 if (U->getOpcode() == UnaryOperator::AddrOf)
842 return EvalVal(U->getSubExpr());
843 else
Ted Kremenek06de2762007-08-17 16:46:58 +0000844 return NULL;
845 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000846
847 case Stmt::BinaryOperatorClass: {
848 // Handle pointer arithmetic. All other binary operators are not valid
849 // in this context.
850 BinaryOperator *B = cast<BinaryOperator>(E);
851 BinaryOperator::Opcode op = B->getOpcode();
852
853 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
854 return NULL;
855
856 Expr *Base = B->getLHS();
857
858 // Determine which argument is the real pointer base. It could be
859 // the RHS argument instead of the LHS.
860 if (!Base->getType()->isPointerType()) Base = B->getRHS();
861
862 assert (Base->getType()->isPointerType());
863 return EvalAddr(Base);
864 }
Steve Naroff61f40a22008-09-10 19:17:48 +0000865
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000866 // For conditional operators we need to see if either the LHS or RHS are
867 // valid DeclRefExpr*s. If one of them is valid, we return it.
868 case Stmt::ConditionalOperatorClass: {
869 ConditionalOperator *C = cast<ConditionalOperator>(E);
870
871 // Handle the GNU extension for missing LHS.
872 if (Expr *lhsExpr = C->getLHS())
873 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
874 return LHS;
875
876 return EvalAddr(C->getRHS());
877 }
878
Ted Kremenek54b52742008-08-07 00:49:01 +0000879 // For casts, we need to handle conversions from arrays to
880 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +0000881 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +0000882 case Stmt::CStyleCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +0000883 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +0000884 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +0000885 QualType T = SubExpr->getType();
886
Steve Naroffdd972f22008-09-05 22:11:13 +0000887 if (SubExpr->getType()->isPointerType() ||
888 SubExpr->getType()->isBlockPointerType() ||
889 SubExpr->getType()->isObjCQualifiedIdType())
Ted Kremenek54b52742008-08-07 00:49:01 +0000890 return EvalAddr(SubExpr);
891 else if (T->isArrayType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000892 return EvalVal(SubExpr);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000893 else
Ted Kremenek54b52742008-08-07 00:49:01 +0000894 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000895 }
896
897 // C++ casts. For dynamic casts, static casts, and const casts, we
898 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +0000899 // through the cast. In the case the dynamic cast doesn't fail (and
900 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000901 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +0000902 // FIXME: The comment about is wrong; we're not always converting
903 // from pointer to pointer. I'm guessing that this code should also
904 // handle references to objects.
905 case Stmt::CXXStaticCastExprClass:
906 case Stmt::CXXDynamicCastExprClass:
907 case Stmt::CXXConstCastExprClass:
908 case Stmt::CXXReinterpretCastExprClass: {
909 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +0000910 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000911 return EvalAddr(S);
912 else
913 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000914 }
915
916 // Everything else: we simply don't reason about them.
917 default:
918 return NULL;
919 }
Ted Kremenek06de2762007-08-17 16:46:58 +0000920}
921
922
923/// EvalVal - This function is complements EvalAddr in the mutual recursion.
924/// See the comments for EvalAddr for more details.
925static DeclRefExpr* EvalVal(Expr *E) {
926
Ted Kremeneke8c600f2007-08-28 17:02:55 +0000927 // We should only be called for evaluating non-pointer expressions, or
928 // expressions with a pointer type that are not used as references but instead
929 // are l-values (e.g., DeclRefExpr with a pointer type).
930
Ted Kremenek06de2762007-08-17 16:46:58 +0000931 // Our "symbolic interpreter" is just a dispatch off the currently
932 // viewed AST node. We then recursively traverse the AST by calling
933 // EvalAddr and EvalVal appropriately.
934 switch (E->getStmtClass()) {
Douglas Gregor1a49af92009-01-06 05:10:23 +0000935 case Stmt::DeclRefExprClass:
936 case Stmt::QualifiedDeclRefExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +0000937 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
938 // at code that refers to a variable's name. We check if it has local
939 // storage within the function, and if so, return the expression.
940 DeclRefExpr *DR = cast<DeclRefExpr>(E);
941
942 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000943 if(V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
Ted Kremenek06de2762007-08-17 16:46:58 +0000944
945 return NULL;
946 }
947
948 case Stmt::ParenExprClass:
949 // Ignore parentheses.
950 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
951
952 case Stmt::UnaryOperatorClass: {
953 // The only unary operator that make sense to handle here
954 // is Deref. All others don't resolve to a "name." This includes
955 // handling all sorts of rvalues passed to a unary operator.
956 UnaryOperator *U = cast<UnaryOperator>(E);
957
958 if (U->getOpcode() == UnaryOperator::Deref)
959 return EvalAddr(U->getSubExpr());
960
961 return NULL;
962 }
963
964 case Stmt::ArraySubscriptExprClass: {
965 // Array subscripts are potential references to data on the stack. We
966 // retrieve the DeclRefExpr* for the array variable if it indeed
967 // has local storage.
Ted Kremenek23245122007-08-20 16:18:38 +0000968 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek06de2762007-08-17 16:46:58 +0000969 }
970
971 case Stmt::ConditionalOperatorClass: {
972 // For conditional operators we need to see if either the LHS or RHS are
973 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
974 ConditionalOperator *C = cast<ConditionalOperator>(E);
975
Anders Carlsson39073232007-11-30 19:04:31 +0000976 // Handle the GNU extension for missing LHS.
977 if (Expr *lhsExpr = C->getLHS())
978 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
979 return LHS;
980
981 return EvalVal(C->getRHS());
Ted Kremenek06de2762007-08-17 16:46:58 +0000982 }
983
984 // Accesses to members are potential references to data on the stack.
985 case Stmt::MemberExprClass: {
986 MemberExpr *M = cast<MemberExpr>(E);
987
988 // Check for indirect access. We only want direct field accesses.
989 if (!M->isArrow())
990 return EvalVal(M->getBase());
991 else
992 return NULL;
993 }
994
995 // Everything else: we simply don't reason about them.
996 default:
997 return NULL;
998 }
999}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001000
1001//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
1002
1003/// Check for comparisons of floating point operands using != and ==.
1004/// Issue a warning if these are no self-comparisons, as they are not likely
1005/// to do what the programmer intended.
1006void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
1007 bool EmitWarning = true;
1008
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00001009 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek32e97b62008-01-17 17:55:13 +00001010 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001011
1012 // Special case: check for x == x (which is OK).
1013 // Do not emit warnings for such cases.
1014 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
1015 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
1016 if (DRL->getDecl() == DRR->getDecl())
1017 EmitWarning = false;
1018
Ted Kremenek1b500bb2007-11-29 00:59:04 +00001019
1020 // Special case: check for comparisons against literals that can be exactly
1021 // represented by APFloat. In such cases, do not emit a warning. This
1022 // is a heuristic: often comparison against such literals are used to
1023 // detect if a value in a variable has not changed. This clearly can
1024 // lead to false negatives.
1025 if (EmitWarning) {
1026 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
1027 if (FLL->isExact())
1028 EmitWarning = false;
1029 }
1030 else
1031 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
1032 if (FLR->isExact())
1033 EmitWarning = false;
1034 }
1035 }
1036
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001037 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001038 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001039 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
1040 if (isCallBuiltin(CL))
1041 EmitWarning = false;
1042
Sebastian Redl0eb23302009-01-19 00:08:26 +00001043 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001044 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
1045 if (isCallBuiltin(CR))
1046 EmitWarning = false;
1047
1048 // Emit the diagnostic.
1049 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001050 Diag(loc, diag::warn_floatingpoint_eq)
1051 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001052}