blob: ab7125549654095d82f9c30935ecd4445d3d221b [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
Douglas Gregor411889e2009-02-13 23:20:09 +000037 switch (FDecl->getBuiltinID()) {
Chris Lattnerf22a8502007-12-19 23:59:04 +000038 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 // Printf checking.
Douglas Gregor17429032009-02-14 00:32:47 +000081 unsigned format_idx = 0;
82 bool HasVAListArg = false;
83 if (FDecl->getBuiltinID() &&
84 Context.BuiltinInfo.isPrintfLike(FDecl->getBuiltinID(), format_idx,
85 HasVAListArg)) {
86 // Found a printf builtin.
87 } else if (FnInfo == KnownFunctionIDs[id_NSLog]) {
88 format_idx = 0;
89 HasVAListArg = false;
90 } else if (FnInfo == KnownFunctionIDs[id_asprintf] ||
91 FnInfo == KnownFunctionIDs[id_fprintf]) {
92 format_idx = 1;
93 HasVAListArg = false;
94 } else if (FnInfo == KnownFunctionIDs[id_vasprintf] ||
95 FnInfo == KnownFunctionIDs[id_vfprintf]) {
96 format_idx = 1;
97 HasVAListArg = true;
98 } else {
99 return move(TheCallResult);
Chris Lattner2e64c072007-08-10 20:18:51 +0000100 }
Sebastian Redl8b769972009-01-19 00:08:26 +0000101
Douglas Gregor17429032009-02-14 00:32:47 +0000102 CheckPrintfArguments(TheCall, HasVAListArg, format_idx);
103
Sebastian Redl8b769972009-01-19 00:08:26 +0000104 return move(TheCallResult);
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000105}
106
107/// CheckBuiltinCFStringArgument - Checks that the argument to the builtin
108/// CFString constructor is correct
Chris Lattnerda050402007-08-25 05:30:33 +0000109bool Sema::CheckBuiltinCFStringArgument(Expr* Arg) {
Chris Lattner7a48d9c2008-02-13 01:02:39 +0000110 Arg = Arg->IgnoreParenCasts();
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000111
112 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
113
114 if (!Literal || Literal->isWide()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000115 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
116 << Arg->getSourceRange();
Anders Carlsson3e9b43b2007-08-17 15:44:17 +0000117 return true;
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000118 }
119
120 const char *Data = Literal->getStrData();
121 unsigned Length = Literal->getByteLength();
122
123 for (unsigned i = 0; i < Length; ++i) {
124 if (!isascii(Data[i])) {
125 Diag(PP.AdvanceToTokenCharacter(Arg->getLocStart(), i + 1),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000126 diag::warn_cfstring_literal_contains_non_ascii_character)
127 << Arg->getSourceRange();
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000128 break;
129 }
130
131 if (!Data[i]) {
132 Diag(PP.AdvanceToTokenCharacter(Arg->getLocStart(), i + 1),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000133 diag::warn_cfstring_literal_contains_nul_character)
134 << Arg->getSourceRange();
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000135 break;
136 }
137 }
138
Anders Carlsson3e9b43b2007-08-17 15:44:17 +0000139 return false;
Chris Lattner2e64c072007-08-10 20:18:51 +0000140}
141
Chris Lattner3b933692007-12-20 00:05:45 +0000142/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
143/// Emit an error and return true on failure, return false on success.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000144bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
145 Expr *Fn = TheCall->getCallee();
146 if (TheCall->getNumArgs() > 2) {
Chris Lattner66beaba2008-11-21 18:44:24 +0000147 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000148 diag::err_typecheck_call_too_many_args)
Chris Lattner66beaba2008-11-21 18:44:24 +0000149 << 0 /*function call*/ << Fn->getSourceRange()
Chris Lattner8ba580c2008-11-19 05:08:23 +0000150 << SourceRange(TheCall->getArg(2)->getLocStart(),
151 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattnerf22a8502007-12-19 23:59:04 +0000152 return true;
153 }
Eli Friedman6422de62008-12-15 22:05:35 +0000154
155 if (TheCall->getNumArgs() < 2) {
156 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
157 << 0 /*function call*/;
158 }
159
Chris Lattner3b933692007-12-20 00:05:45 +0000160 // Determine whether the current function is variadic or not.
161 bool isVariadic;
Eli Friedman6422de62008-12-15 22:05:35 +0000162 if (getCurFunctionDecl()) {
163 if (FunctionTypeProto* FTP =
164 dyn_cast<FunctionTypeProto>(getCurFunctionDecl()->getType()))
165 isVariadic = FTP->isVariadic();
166 else
167 isVariadic = false;
168 } else {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000169 isVariadic = getCurMethodDecl()->isVariadic();
Eli Friedman6422de62008-12-15 22:05:35 +0000170 }
Chris Lattnerf22a8502007-12-19 23:59:04 +0000171
Chris Lattner3b933692007-12-20 00:05:45 +0000172 if (!isVariadic) {
Chris Lattnerf22a8502007-12-19 23:59:04 +0000173 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
174 return true;
175 }
176
177 // Verify that the second argument to the builtin is the last argument of the
178 // current function or method.
179 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson924556e2008-02-13 01:22:59 +0000180 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Anders Carlssonc27156b2008-02-11 04:20:54 +0000181
182 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
183 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattnerf22a8502007-12-19 23:59:04 +0000184 // FIXME: This isn't correct for methods (results in bogus warning).
185 // Get the last formal in the current function.
Anders Carlssonc27156b2008-02-11 04:20:54 +0000186 const ParmVarDecl *LastArg;
Chris Lattnere5cb5862008-12-04 23:50:19 +0000187 if (FunctionDecl *FD = getCurFunctionDecl())
188 LastArg = *(FD->param_end()-1);
Chris Lattnerf22a8502007-12-19 23:59:04 +0000189 else
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000190 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattnerf22a8502007-12-19 23:59:04 +0000191 SecondArgIsLastNamedArgument = PV == LastArg;
192 }
193 }
194
195 if (!SecondArgIsLastNamedArgument)
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000196 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattnerf22a8502007-12-19 23:59:04 +0000197 diag::warn_second_parameter_of_va_start_not_last_named_argument);
198 return false;
Eli Friedman8c50c622008-05-20 08:23:37 +0000199}
Chris Lattnerf22a8502007-12-19 23:59:04 +0000200
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000201/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
202/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000203bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
204 if (TheCall->getNumArgs() < 2)
Chris Lattner66beaba2008-11-21 18:44:24 +0000205 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
206 << 0 /*function call*/;
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000207 if (TheCall->getNumArgs() > 2)
208 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000209 diag::err_typecheck_call_too_many_args)
Chris Lattner66beaba2008-11-21 18:44:24 +0000210 << 0 /*function call*/
Chris Lattner8ba580c2008-11-19 05:08:23 +0000211 << SourceRange(TheCall->getArg(2)->getLocStart(),
212 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000213
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000214 Expr *OrigArg0 = TheCall->getArg(0);
215 Expr *OrigArg1 = TheCall->getArg(1);
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000216
217 // Do standard promotions between the two arguments, returning their common
218 // type.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000219 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000220
221 // If the common type isn't a real floating type, then the arguments were
222 // invalid for this operation.
223 if (!Res->isRealFloatingType())
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000224 return Diag(OrigArg0->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000225 diag::err_typecheck_call_invalid_ordered_compare)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000226 << OrigArg0->getType() << OrigArg1->getType()
Chris Lattner8ba580c2008-11-19 05:08:23 +0000227 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000228
229 return false;
230}
231
Eli Friedman8c50c622008-05-20 08:23:37 +0000232bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) {
233 // The signature for these builtins is exact; the only thing we need
234 // to check is that the argument is a constant.
235 SourceLocation Loc;
Chris Lattner941c0102008-08-10 02:05:13 +0000236 if (!TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc))
Chris Lattner8ba580c2008-11-19 05:08:23 +0000237 return Diag(Loc, diag::err_stack_const_level) << TheCall->getSourceRange();
Chris Lattner941c0102008-08-10 02:05:13 +0000238
Eli Friedman8c50c622008-05-20 08:23:37 +0000239 return false;
240}
241
Eli Friedmand0e9d092008-05-14 19:38:39 +0000242/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
243// This is declared to take (...), so we have to check everything.
Sebastian Redl8b769972009-01-19 00:08:26 +0000244Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Eli Friedmand0e9d092008-05-14 19:38:39 +0000245 if (TheCall->getNumArgs() < 3)
Sebastian Redl8b769972009-01-19 00:08:26 +0000246 return ExprError(Diag(TheCall->getLocEnd(),
247 diag::err_typecheck_call_too_few_args)
248 << 0 /*function call*/ << TheCall->getSourceRange());
Eli Friedmand0e9d092008-05-14 19:38:39 +0000249
250 QualType FAType = TheCall->getArg(0)->getType();
251 QualType SAType = TheCall->getArg(1)->getType();
252
253 if (!FAType->isVectorType() || !SAType->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000254 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
255 << SourceRange(TheCall->getArg(0)->getLocStart(),
256 TheCall->getArg(1)->getLocEnd());
Sebastian Redl8b769972009-01-19 00:08:26 +0000257 return ExprError();
Eli Friedmand0e9d092008-05-14 19:38:39 +0000258 }
259
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000260 if (Context.getCanonicalType(FAType).getUnqualifiedType() !=
261 Context.getCanonicalType(SAType).getUnqualifiedType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000262 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
263 << SourceRange(TheCall->getArg(0)->getLocStart(),
264 TheCall->getArg(1)->getLocEnd());
Sebastian Redl8b769972009-01-19 00:08:26 +0000265 return ExprError();
Eli Friedmand0e9d092008-05-14 19:38:39 +0000266 }
267
268 unsigned numElements = FAType->getAsVectorType()->getNumElements();
269 if (TheCall->getNumArgs() != numElements+2) {
270 if (TheCall->getNumArgs() < numElements+2)
Sebastian Redl8b769972009-01-19 00:08:26 +0000271 return ExprError(Diag(TheCall->getLocEnd(),
272 diag::err_typecheck_call_too_few_args)
273 << 0 /*function call*/ << TheCall->getSourceRange());
274 return ExprError(Diag(TheCall->getLocEnd(),
275 diag::err_typecheck_call_too_many_args)
276 << 0 /*function call*/ << TheCall->getSourceRange());
Eli Friedmand0e9d092008-05-14 19:38:39 +0000277 }
278
279 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
280 llvm::APSInt Result(32);
Chris Lattner941c0102008-08-10 02:05:13 +0000281 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
Sebastian Redl8b769972009-01-19 00:08:26 +0000282 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000283 diag::err_shufflevector_nonconstant_argument)
Sebastian Redl8b769972009-01-19 00:08:26 +0000284 << TheCall->getArg(i)->getSourceRange());
285
Chris Lattner941c0102008-08-10 02:05:13 +0000286 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl8b769972009-01-19 00:08:26 +0000287 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000288 diag::err_shufflevector_argument_too_large)
Sebastian Redl8b769972009-01-19 00:08:26 +0000289 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand0e9d092008-05-14 19:38:39 +0000290 }
291
292 llvm::SmallVector<Expr*, 32> exprs;
293
Chris Lattner941c0102008-08-10 02:05:13 +0000294 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand0e9d092008-05-14 19:38:39 +0000295 exprs.push_back(TheCall->getArg(i));
296 TheCall->setArg(i, 0);
297 }
298
Ted Kremenek0c97e042009-02-07 01:47:29 +0000299 return Owned(new (Context) ShuffleVectorExpr(exprs.begin(), numElements+2,
300 FAType,
301 TheCall->getCallee()->getLocStart(),
302 TheCall->getRParenLoc()));
Eli Friedmand0e9d092008-05-14 19:38:39 +0000303}
Chris Lattnerf22a8502007-12-19 23:59:04 +0000304
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000305/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
306// This is declared to take (const void*, ...) and can take two
307// optional constant int args.
308bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000309 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000310
Chris Lattner8ba580c2008-11-19 05:08:23 +0000311 if (NumArgs > 3)
312 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args)
Chris Lattner66beaba2008-11-21 18:44:24 +0000313 << 0 /*function call*/ << TheCall->getSourceRange();
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000314
315 // Argument 0 is checked for us and the remaining arguments must be
316 // constant integers.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000317 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000318 Expr *Arg = TheCall->getArg(i);
319 QualType RWType = Arg->getType();
320
321 const BuiltinType *BT = RWType->getAsBuiltinType();
Daniel Dunbar30ad42d2008-09-03 21:13:56 +0000322 llvm::APSInt Result;
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000323 if (!BT || BT->getKind() != BuiltinType::Int ||
Chris Lattner8ba580c2008-11-19 05:08:23 +0000324 !Arg->isIntegerConstantExpr(Result, Context))
325 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument)
326 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000327
328 // FIXME: gcc issues a warning and rewrites these to 0. These
329 // seems especially odd for the third argument since the default
330 // is 3.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000331 if (i == 1) {
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000332 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 1)
Chris Lattner8ba580c2008-11-19 05:08:23 +0000333 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
334 << "0" << "1" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000335 } else {
336 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3)
Chris Lattner8ba580c2008-11-19 05:08:23 +0000337 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
338 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000339 }
340 }
341
Chris Lattner8ba580c2008-11-19 05:08:23 +0000342 return false;
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000343}
344
Daniel Dunbar30ad42d2008-09-03 21:13:56 +0000345/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
346/// int type). This simply type checks that type is one of the defined
347/// constants (0-3).
348bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
349 Expr *Arg = TheCall->getArg(1);
350 QualType ArgType = Arg->getType();
351 const BuiltinType *BT = ArgType->getAsBuiltinType();
352 llvm::APSInt Result(32);
353 if (!BT || BT->getKind() != BuiltinType::Int ||
354 !Arg->isIntegerConstantExpr(Result, Context)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000355 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
356 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar30ad42d2008-09-03 21:13:56 +0000357 }
358
359 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000360 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
361 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar30ad42d2008-09-03 21:13:56 +0000362 }
363
364 return false;
365}
366
Ted Kremenek8c797c02009-01-12 23:09:09 +0000367// Handle i > 1 ? "x" : "y", recursivelly
368bool Sema::SemaCheckStringLiteral(Expr *E, CallExpr *TheCall, bool HasVAListArg,
369 unsigned format_idx) {
370
371 switch (E->getStmtClass()) {
372 case Stmt::ConditionalOperatorClass: {
373 ConditionalOperator *C = cast<ConditionalOperator>(E);
374 return SemaCheckStringLiteral(C->getLHS(), TheCall,
375 HasVAListArg, format_idx)
376 && SemaCheckStringLiteral(C->getRHS(), TheCall,
377 HasVAListArg, format_idx);
378 }
379
380 case Stmt::ImplicitCastExprClass: {
381 ImplicitCastExpr *Expr = dyn_cast<ImplicitCastExpr>(E);
382 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
383 format_idx);
384 }
385
386 case Stmt::ParenExprClass: {
387 ParenExpr *Expr = dyn_cast<ParenExpr>(E);
388 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
389 format_idx);
390 }
391
392 default: {
393 ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E);
394 StringLiteral *StrE = NULL;
395
396 if (ObjCFExpr)
397 StrE = ObjCFExpr->getString();
398 else
399 StrE = dyn_cast<StringLiteral>(E);
400
401 if (StrE) {
402 CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx);
403 return true;
404 }
405
406 return false;
407 }
408 }
409}
410
411
Chris Lattner2e64c072007-08-10 20:18:51 +0000412/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Ted Kremenek081ed872007-08-14 17:39:48 +0000413/// correct use of format strings.
414///
415/// HasVAListArg - A predicate indicating whether the printf-like
416/// function is passed an explicit va_arg argument (e.g., vprintf)
417///
418/// format_idx - The index into Args for the format string.
419///
420/// Improper format strings to functions in the printf family can be
421/// the source of bizarre bugs and very serious security holes. A
422/// good source of information is available in the following paper
423/// (which includes additional references):
Chris Lattner2e64c072007-08-10 20:18:51 +0000424///
425/// FormatGuard: Automatic Protection From printf Format String
426/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremenek081ed872007-08-14 17:39:48 +0000427///
428/// Functionality implemented:
429///
430/// We can statically check the following properties for string
431/// literal format strings for non v.*printf functions (where the
432/// arguments are passed directly):
433//
434/// (1) Are the number of format conversions equal to the number of
435/// data arguments?
436///
437/// (2) Does each format conversion correctly match the type of the
438/// corresponding data argument? (TODO)
439///
440/// Moreover, for all printf functions we can:
441///
442/// (3) Check for a missing format string (when not caught by type checking).
443///
444/// (4) Check for no-operation flags; e.g. using "#" with format
445/// conversion 'c' (TODO)
446///
447/// (5) Check the use of '%n', a major source of security holes.
448///
449/// (6) Check for malformed format conversions that don't specify anything.
450///
451/// (7) Check for empty format strings. e.g: printf("");
452///
453/// (8) Check that the format string is a wide literal.
454///
Ted Kremenekc2804c22008-03-03 16:50:00 +0000455/// (9) Also check the arguments of functions with the __format__ attribute.
456/// (TODO).
457///
Ted Kremenek081ed872007-08-14 17:39:48 +0000458/// All of these checks can be done by parsing the format string.
459///
460/// For now, we ONLY do (1), (3), (5), (6), (7), and (8).
Chris Lattner2e64c072007-08-10 20:18:51 +0000461void
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000462Sema::CheckPrintfArguments(CallExpr *TheCall, bool HasVAListArg,
463 unsigned format_idx) {
464 Expr *Fn = TheCall->getCallee();
465
Ted Kremenek081ed872007-08-14 17:39:48 +0000466 // CHECK: printf-like function is called with no format string.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000467 if (format_idx >= TheCall->getNumArgs()) {
Chris Lattner9d2cf082008-11-19 05:27:50 +0000468 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string)
469 << Fn->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +0000470 return;
471 }
472
Chris Lattner7a48d9c2008-02-13 01:02:39 +0000473 Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Chris Lattnere65acc12007-08-25 05:36:18 +0000474
Chris Lattner2e64c072007-08-10 20:18:51 +0000475 // CHECK: format string is not a string literal.
476 //
Ted Kremenek081ed872007-08-14 17:39:48 +0000477 // Dynamically generated format strings are difficult to
478 // automatically vet at compile time. Requiring that format strings
479 // are string literals: (1) permits the checking of format strings by
480 // the compiler and thereby (2) can practically remove the source of
481 // many format string exploits.
Ted Kremenek225a14c2008-06-16 18:00:42 +0000482
483 // Format string can be either ObjC string (e.g. @"%d") or
484 // C string (e.g. "%d")
485 // ObjC string uses the same format specifiers as C string, so we can use
486 // the same format string checking logic for both ObjC and C strings.
Ted Kremenek8c797c02009-01-12 23:09:09 +0000487 bool isFExpr = SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx);
Ted Kremenek225a14c2008-06-16 18:00:42 +0000488
Ted Kremenek8c797c02009-01-12 23:09:09 +0000489 if (!isFExpr) {
Ted Kremenek19398b62007-12-17 19:03:13 +0000490 // For vprintf* functions (i.e., HasVAListArg==true), we add a
491 // special check to see if the format string is a function parameter
492 // of the function calling the printf function. If the function
493 // has an attribute indicating it is a printf-like function, then we
494 // should suppress warnings concerning non-literals being used in a call
495 // to a vprintf function. For example:
496 //
497 // void
498 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...) {
499 // va_list ap;
500 // va_start(ap, fmt);
501 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
502 // ...
503 //
504 //
505 // FIXME: We don't have full attribute support yet, so just check to see
506 // if the argument is a DeclRefExpr that references a parameter. We'll
507 // add proper support for checking the attribute later.
508 if (HasVAListArg)
Chris Lattner3d5a8f32007-12-28 05:38:24 +0000509 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(OrigFormatExpr))
510 if (isa<ParmVarDecl>(DR->getDecl()))
Ted Kremenek19398b62007-12-17 19:03:13 +0000511 return;
Ted Kremenek8c797c02009-01-12 23:09:09 +0000512
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000513 Diag(TheCall->getArg(format_idx)->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000514 diag::warn_printf_not_string_constant)
515 << OrigFormatExpr->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +0000516 return;
517 }
Ted Kremenek8c797c02009-01-12 23:09:09 +0000518}
Ted Kremenek081ed872007-08-14 17:39:48 +0000519
Ted Kremenek8c797c02009-01-12 23:09:09 +0000520void Sema::CheckPrintfString(StringLiteral *FExpr, Expr *OrigFormatExpr,
521 CallExpr *TheCall, bool HasVAListArg, unsigned format_idx) {
522
523 ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(OrigFormatExpr);
Ted Kremenek081ed872007-08-14 17:39:48 +0000524 // CHECK: is the format string a wide literal?
525 if (FExpr->isWide()) {
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000526 Diag(FExpr->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000527 diag::warn_printf_format_string_is_wide_literal)
528 << OrigFormatExpr->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +0000529 return;
530 }
531
532 // Str - The format string. NOTE: this is NOT null-terminated!
533 const char * const Str = FExpr->getStrData();
534
535 // CHECK: empty format string?
536 const unsigned StrLen = FExpr->getByteLength();
537
538 if (StrLen == 0) {
Chris Lattner9d2cf082008-11-19 05:27:50 +0000539 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string)
540 << OrigFormatExpr->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +0000541 return;
542 }
543
544 // We process the format string using a binary state machine. The
545 // current state is stored in CurrentState.
546 enum {
547 state_OrdChr,
548 state_Conversion
549 } CurrentState = state_OrdChr;
550
551 // numConversions - The number of conversions seen so far. This is
552 // incremented as we traverse the format string.
553 unsigned numConversions = 0;
554
555 // numDataArgs - The number of data arguments after the format
556 // string. This can only be determined for non vprintf-like
557 // functions. For those functions, this value is 1 (the sole
558 // va_arg argument).
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000559 unsigned numDataArgs = TheCall->getNumArgs()-(format_idx+1);
Ted Kremenek081ed872007-08-14 17:39:48 +0000560
561 // Inspect the format string.
562 unsigned StrIdx = 0;
563
564 // LastConversionIdx - Index within the format string where we last saw
565 // a '%' character that starts a new format conversion.
566 unsigned LastConversionIdx = 0;
567
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000568 for (; StrIdx < StrLen; ++StrIdx) {
Chris Lattner3d5a8f32007-12-28 05:38:24 +0000569
Ted Kremenek081ed872007-08-14 17:39:48 +0000570 // Is the number of detected conversion conversions greater than
571 // the number of matching data arguments? If so, stop.
572 if (!HasVAListArg && numConversions > numDataArgs) break;
573
574 // Handle "\0"
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000575 if (Str[StrIdx] == '\0') {
Ted Kremenek081ed872007-08-14 17:39:48 +0000576 // The string returned by getStrData() is not null-terminated,
577 // so the presence of a null character is likely an error.
Chris Lattner3d5a8f32007-12-28 05:38:24 +0000578 Diag(PP.AdvanceToTokenCharacter(FExpr->getLocStart(), StrIdx+1),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000579 diag::warn_printf_format_string_contains_null_char)
580 << OrigFormatExpr->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +0000581 return;
582 }
583
584 // Ordinary characters (not processing a format conversion).
585 if (CurrentState == state_OrdChr) {
586 if (Str[StrIdx] == '%') {
587 CurrentState = state_Conversion;
588 LastConversionIdx = StrIdx;
589 }
590 continue;
591 }
592
593 // Seen '%'. Now processing a format conversion.
594 switch (Str[StrIdx]) {
Chris Lattner68d88f02007-12-28 05:31:15 +0000595 // Handle dynamic precision or width specifier.
596 case '*': {
597 ++numConversions;
598
599 if (!HasVAListArg && numConversions > numDataArgs) {
Chris Lattner68d88f02007-12-28 05:31:15 +0000600 SourceLocation Loc = FExpr->getLocStart();
601 Loc = PP.AdvanceToTokenCharacter(Loc, StrIdx+1);
Ted Kremenek035d8792007-10-12 20:51:52 +0000602
Ted Kremenek035d8792007-10-12 20:51:52 +0000603 if (Str[StrIdx-1] == '.')
Chris Lattner9d2cf082008-11-19 05:27:50 +0000604 Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg)
605 << OrigFormatExpr->getSourceRange();
Ted Kremenek035d8792007-10-12 20:51:52 +0000606 else
Chris Lattner9d2cf082008-11-19 05:27:50 +0000607 Diag(Loc, diag::warn_printf_asterisk_width_missing_arg)
608 << OrigFormatExpr->getSourceRange();
Ted Kremenek035d8792007-10-12 20:51:52 +0000609
Chris Lattner68d88f02007-12-28 05:31:15 +0000610 // Don't do any more checking. We'll just emit spurious errors.
611 return;
Ted Kremenek035d8792007-10-12 20:51:52 +0000612 }
Chris Lattner68d88f02007-12-28 05:31:15 +0000613
614 // Perform type checking on width/precision specifier.
615 Expr *E = TheCall->getArg(format_idx+numConversions);
616 if (const BuiltinType *BT = E->getType()->getAsBuiltinType())
617 if (BT->getKind() == BuiltinType::Int)
618 break;
Ted Kremenek081ed872007-08-14 17:39:48 +0000619
Chris Lattner68d88f02007-12-28 05:31:15 +0000620 SourceLocation Loc =
621 PP.AdvanceToTokenCharacter(FExpr->getLocStart(), StrIdx+1);
622
623 if (Str[StrIdx-1] == '.')
Chris Lattner9d2cf082008-11-19 05:27:50 +0000624 Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000625 << E->getType() << E->getSourceRange();
Chris Lattner68d88f02007-12-28 05:31:15 +0000626 else
Chris Lattner9d2cf082008-11-19 05:27:50 +0000627 Diag(Loc, diag::warn_printf_asterisk_width_wrong_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000628 << E->getType() << E->getSourceRange();
Chris Lattner68d88f02007-12-28 05:31:15 +0000629
630 break;
631 }
632
633 // Characters which can terminate a format conversion
634 // (e.g. "%d"). Characters that specify length modifiers or
635 // other flags are handled by the default case below.
636 //
637 // FIXME: additional checks will go into the following cases.
638 case 'i':
639 case 'd':
640 case 'o':
641 case 'u':
642 case 'x':
643 case 'X':
644 case 'D':
645 case 'O':
646 case 'U':
647 case 'e':
648 case 'E':
649 case 'f':
650 case 'F':
651 case 'g':
652 case 'G':
653 case 'a':
654 case 'A':
655 case 'c':
656 case 'C':
657 case 'S':
658 case 's':
659 case 'p':
660 ++numConversions;
661 CurrentState = state_OrdChr;
662 break;
663
664 // CHECK: Are we using "%n"? Issue a warning.
665 case 'n': {
666 ++numConversions;
667 CurrentState = state_OrdChr;
668 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
669 LastConversionIdx+1);
670
Chris Lattner9d2cf082008-11-19 05:27:50 +0000671 Diag(Loc, diag::warn_printf_write_back)<<OrigFormatExpr->getSourceRange();
Chris Lattner68d88f02007-12-28 05:31:15 +0000672 break;
673 }
Ted Kremenek225a14c2008-06-16 18:00:42 +0000674
675 // Handle "%@"
676 case '@':
677 // %@ is allowed in ObjC format strings only.
678 if(ObjCFExpr != NULL)
679 CurrentState = state_OrdChr;
680 else {
681 // Issue a warning: invalid format conversion.
682 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
683 LastConversionIdx+1);
684
Chris Lattner77d52da2008-11-20 06:06:08 +0000685 Diag(Loc, diag::warn_printf_invalid_conversion)
686 << std::string(Str+LastConversionIdx,
687 Str+std::min(LastConversionIdx+2, StrLen))
688 << OrigFormatExpr->getSourceRange();
Ted Kremenek225a14c2008-06-16 18:00:42 +0000689 }
690 ++numConversions;
691 break;
692
Chris Lattner68d88f02007-12-28 05:31:15 +0000693 // Handle "%%"
694 case '%':
695 // Sanity check: Was the first "%" character the previous one?
696 // If not, we will assume that we have a malformed format
697 // conversion, and that the current "%" character is the start
698 // of a new conversion.
699 if (StrIdx - LastConversionIdx == 1)
700 CurrentState = state_OrdChr;
701 else {
702 // Issue a warning: invalid format conversion.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000703 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
704 LastConversionIdx+1);
Chris Lattner68d88f02007-12-28 05:31:15 +0000705
Chris Lattner77d52da2008-11-20 06:06:08 +0000706 Diag(Loc, diag::warn_printf_invalid_conversion)
707 << std::string(Str+LastConversionIdx, Str+StrIdx)
708 << OrigFormatExpr->getSourceRange();
Chris Lattner68d88f02007-12-28 05:31:15 +0000709
710 // This conversion is broken. Advance to the next format
711 // conversion.
712 LastConversionIdx = StrIdx;
713 ++numConversions;
Ted Kremenek081ed872007-08-14 17:39:48 +0000714 }
Chris Lattner68d88f02007-12-28 05:31:15 +0000715 break;
Ted Kremenek081ed872007-08-14 17:39:48 +0000716
Chris Lattner68d88f02007-12-28 05:31:15 +0000717 default:
718 // This case catches all other characters: flags, widths, etc.
719 // We should eventually process those as well.
720 break;
Ted Kremenek081ed872007-08-14 17:39:48 +0000721 }
722 }
723
724 if (CurrentState == state_Conversion) {
725 // Issue a warning: invalid format conversion.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000726 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
727 LastConversionIdx+1);
Ted Kremenek081ed872007-08-14 17:39:48 +0000728
Chris Lattner77d52da2008-11-20 06:06:08 +0000729 Diag(Loc, diag::warn_printf_invalid_conversion)
730 << std::string(Str+LastConversionIdx,
731 Str+std::min(LastConversionIdx+2, StrLen))
732 << OrigFormatExpr->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +0000733 return;
734 }
735
736 if (!HasVAListArg) {
737 // CHECK: Does the number of format conversions exceed the number
738 // of data arguments?
739 if (numConversions > numDataArgs) {
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000740 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
741 LastConversionIdx);
Ted Kremenek081ed872007-08-14 17:39:48 +0000742
Chris Lattner9d2cf082008-11-19 05:27:50 +0000743 Diag(Loc, diag::warn_printf_insufficient_data_args)
744 << OrigFormatExpr->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +0000745 }
746 // CHECK: Does the number of data arguments exceed the number of
747 // format conversions in the format string?
748 else if (numConversions < numDataArgs)
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000749 Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000750 diag::warn_printf_too_many_data_args)
751 << OrigFormatExpr->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +0000752 }
753}
Ted Kremenek45925ab2007-08-17 16:46:58 +0000754
755//===--- CHECK: Return Address of Stack Variable --------------------------===//
756
757static DeclRefExpr* EvalVal(Expr *E);
758static DeclRefExpr* EvalAddr(Expr* E);
759
760/// CheckReturnStackAddr - Check if a return statement returns the address
761/// of a stack variable.
762void
763Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
764 SourceLocation ReturnLoc) {
Chris Lattner7a48d9c2008-02-13 01:02:39 +0000765
Ted Kremenek45925ab2007-08-17 16:46:58 +0000766 // Perform checking for returned stack addresses.
Steve Naroffd6163f32008-09-05 22:11:13 +0000767 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Ted Kremenek45925ab2007-08-17 16:46:58 +0000768 if (DeclRefExpr *DR = EvalAddr(RetValExp))
Chris Lattner65cae292008-11-19 08:23:25 +0000769 Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
Chris Lattnerb1753422008-11-23 21:45:46 +0000770 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Steve Naroff503996b2008-09-16 22:25:10 +0000771
772 // Skip over implicit cast expressions when checking for block expressions.
773 if (ImplicitCastExpr *IcExpr =
774 dyn_cast_or_null<ImplicitCastExpr>(RetValExp))
775 RetValExp = IcExpr->getSubExpr();
776
Steve Naroff3eac7692008-09-10 19:17:48 +0000777 if (BlockExpr *C = dyn_cast_or_null<BlockExpr>(RetValExp))
Chris Lattner9d2cf082008-11-19 05:27:50 +0000778 Diag(C->getLocStart(), diag::err_ret_local_block)
779 << C->getSourceRange();
Ted Kremenek45925ab2007-08-17 16:46:58 +0000780 }
781 // Perform checking for stack values returned by reference.
782 else if (lhsType->isReferenceType()) {
Douglas Gregor21a04f32008-10-27 19:41:14 +0000783 // Check for a reference to the stack
784 if (DeclRefExpr *DR = EvalVal(RetValExp))
Chris Lattner9d2cf082008-11-19 05:27:50 +0000785 Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
Chris Lattnerb1753422008-11-23 21:45:46 +0000786 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Ted Kremenek45925ab2007-08-17 16:46:58 +0000787 }
788}
789
790/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
791/// check if the expression in a return statement evaluates to an address
792/// to a location on the stack. The recursion is used to traverse the
793/// AST of the return expression, with recursion backtracking when we
794/// encounter a subexpression that (1) clearly does not lead to the address
795/// of a stack variable or (2) is something we cannot determine leads to
796/// the address of a stack variable based on such local checking.
797///
Ted Kremenekda1300a2007-08-28 17:02:55 +0000798/// EvalAddr processes expressions that are pointers that are used as
799/// references (and not L-values). EvalVal handles all other values.
Ted Kremenek45925ab2007-08-17 16:46:58 +0000800/// At the base case of the recursion is a check for a DeclRefExpr* in
801/// the refers to a stack variable.
802///
803/// This implementation handles:
804///
805/// * pointer-to-pointer casts
806/// * implicit conversions from array references to pointers
807/// * taking the address of fields
808/// * arbitrary interplay between "&" and "*" operators
809/// * pointer arithmetic from an address of a stack variable
810/// * taking the address of an array element where the array is on the stack
811static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek45925ab2007-08-17 16:46:58 +0000812 // We should only be called for evaluating pointer expressions.
Steve Naroffd6163f32008-09-05 22:11:13 +0000813 assert((E->getType()->isPointerType() ||
814 E->getType()->isBlockPointerType() ||
Ted Kremenek42730c52008-01-07 19:49:32 +0000815 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner68d88f02007-12-28 05:31:15 +0000816 "EvalAddr only works on pointers");
Ted Kremenek45925ab2007-08-17 16:46:58 +0000817
818 // Our "symbolic interpreter" is just a dispatch off the currently
819 // viewed AST node. We then recursively traverse the AST by calling
820 // EvalAddr and EvalVal appropriately.
821 switch (E->getStmtClass()) {
Chris Lattner68d88f02007-12-28 05:31:15 +0000822 case Stmt::ParenExprClass:
823 // Ignore parentheses.
824 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek45925ab2007-08-17 16:46:58 +0000825
Chris Lattner68d88f02007-12-28 05:31:15 +0000826 case Stmt::UnaryOperatorClass: {
827 // The only unary operator that make sense to handle here
828 // is AddrOf. All others don't make sense as pointers.
829 UnaryOperator *U = cast<UnaryOperator>(E);
Ted Kremenek45925ab2007-08-17 16:46:58 +0000830
Chris Lattner68d88f02007-12-28 05:31:15 +0000831 if (U->getOpcode() == UnaryOperator::AddrOf)
832 return EvalVal(U->getSubExpr());
833 else
Ted Kremenek45925ab2007-08-17 16:46:58 +0000834 return NULL;
835 }
Chris Lattner68d88f02007-12-28 05:31:15 +0000836
837 case Stmt::BinaryOperatorClass: {
838 // Handle pointer arithmetic. All other binary operators are not valid
839 // in this context.
840 BinaryOperator *B = cast<BinaryOperator>(E);
841 BinaryOperator::Opcode op = B->getOpcode();
842
843 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
844 return NULL;
845
846 Expr *Base = B->getLHS();
847
848 // Determine which argument is the real pointer base. It could be
849 // the RHS argument instead of the LHS.
850 if (!Base->getType()->isPointerType()) Base = B->getRHS();
851
852 assert (Base->getType()->isPointerType());
853 return EvalAddr(Base);
854 }
Steve Naroff3eac7692008-09-10 19:17:48 +0000855
Chris Lattner68d88f02007-12-28 05:31:15 +0000856 // For conditional operators we need to see if either the LHS or RHS are
857 // valid DeclRefExpr*s. If one of them is valid, we return it.
858 case Stmt::ConditionalOperatorClass: {
859 ConditionalOperator *C = cast<ConditionalOperator>(E);
860
861 // Handle the GNU extension for missing LHS.
862 if (Expr *lhsExpr = C->getLHS())
863 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
864 return LHS;
865
866 return EvalAddr(C->getRHS());
867 }
868
Ted Kremenekea19edd2008-08-07 00:49:01 +0000869 // For casts, we need to handle conversions from arrays to
870 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor21a04f32008-10-27 19:41:14 +0000871 case Stmt::ImplicitCastExprClass:
Douglas Gregor035d0882008-10-28 15:36:24 +0000872 case Stmt::CStyleCastExprClass:
Douglas Gregor21a04f32008-10-27 19:41:14 +0000873 case Stmt::CXXFunctionalCastExprClass: {
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +0000874 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenekea19edd2008-08-07 00:49:01 +0000875 QualType T = SubExpr->getType();
876
Steve Naroffd6163f32008-09-05 22:11:13 +0000877 if (SubExpr->getType()->isPointerType() ||
878 SubExpr->getType()->isBlockPointerType() ||
879 SubExpr->getType()->isObjCQualifiedIdType())
Ted Kremenekea19edd2008-08-07 00:49:01 +0000880 return EvalAddr(SubExpr);
881 else if (T->isArrayType())
Chris Lattner68d88f02007-12-28 05:31:15 +0000882 return EvalVal(SubExpr);
Chris Lattner68d88f02007-12-28 05:31:15 +0000883 else
Ted Kremenekea19edd2008-08-07 00:49:01 +0000884 return 0;
Chris Lattner68d88f02007-12-28 05:31:15 +0000885 }
886
887 // C++ casts. For dynamic casts, static casts, and const casts, we
888 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor21a04f32008-10-27 19:41:14 +0000889 // through the cast. In the case the dynamic cast doesn't fail (and
890 // return NULL), we take the conservative route and report cases
Chris Lattner68d88f02007-12-28 05:31:15 +0000891 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor21a04f32008-10-27 19:41:14 +0000892 // FIXME: The comment about is wrong; we're not always converting
893 // from pointer to pointer. I'm guessing that this code should also
894 // handle references to objects.
895 case Stmt::CXXStaticCastExprClass:
896 case Stmt::CXXDynamicCastExprClass:
897 case Stmt::CXXConstCastExprClass:
898 case Stmt::CXXReinterpretCastExprClass: {
899 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffd6163f32008-09-05 22:11:13 +0000900 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Chris Lattner68d88f02007-12-28 05:31:15 +0000901 return EvalAddr(S);
902 else
903 return NULL;
Chris Lattner68d88f02007-12-28 05:31:15 +0000904 }
905
906 // Everything else: we simply don't reason about them.
907 default:
908 return NULL;
909 }
Ted Kremenek45925ab2007-08-17 16:46:58 +0000910}
911
912
913/// EvalVal - This function is complements EvalAddr in the mutual recursion.
914/// See the comments for EvalAddr for more details.
915static DeclRefExpr* EvalVal(Expr *E) {
916
Ted Kremenekda1300a2007-08-28 17:02:55 +0000917 // We should only be called for evaluating non-pointer expressions, or
918 // expressions with a pointer type that are not used as references but instead
919 // are l-values (e.g., DeclRefExpr with a pointer type).
920
Ted Kremenek45925ab2007-08-17 16:46:58 +0000921 // Our "symbolic interpreter" is just a dispatch off the currently
922 // viewed AST node. We then recursively traverse the AST by calling
923 // EvalAddr and EvalVal appropriately.
924 switch (E->getStmtClass()) {
Douglas Gregor566782a2009-01-06 05:10:23 +0000925 case Stmt::DeclRefExprClass:
926 case Stmt::QualifiedDeclRefExprClass: {
Ted Kremenek45925ab2007-08-17 16:46:58 +0000927 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
928 // at code that refers to a variable's name. We check if it has local
929 // storage within the function, and if so, return the expression.
930 DeclRefExpr *DR = cast<DeclRefExpr>(E);
931
932 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Douglas Gregor81c29152008-10-29 00:13:59 +0000933 if(V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
Ted Kremenek45925ab2007-08-17 16:46:58 +0000934
935 return NULL;
936 }
937
938 case Stmt::ParenExprClass:
939 // Ignore parentheses.
940 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
941
942 case Stmt::UnaryOperatorClass: {
943 // The only unary operator that make sense to handle here
944 // is Deref. All others don't resolve to a "name." This includes
945 // handling all sorts of rvalues passed to a unary operator.
946 UnaryOperator *U = cast<UnaryOperator>(E);
947
948 if (U->getOpcode() == UnaryOperator::Deref)
949 return EvalAddr(U->getSubExpr());
950
951 return NULL;
952 }
953
954 case Stmt::ArraySubscriptExprClass: {
955 // Array subscripts are potential references to data on the stack. We
956 // retrieve the DeclRefExpr* for the array variable if it indeed
957 // has local storage.
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000958 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek45925ab2007-08-17 16:46:58 +0000959 }
960
961 case Stmt::ConditionalOperatorClass: {
962 // For conditional operators we need to see if either the LHS or RHS are
963 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
964 ConditionalOperator *C = cast<ConditionalOperator>(E);
965
Anders Carlsson37365fc2007-11-30 19:04:31 +0000966 // Handle the GNU extension for missing LHS.
967 if (Expr *lhsExpr = C->getLHS())
968 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
969 return LHS;
970
971 return EvalVal(C->getRHS());
Ted Kremenek45925ab2007-08-17 16:46:58 +0000972 }
973
974 // Accesses to members are potential references to data on the stack.
975 case Stmt::MemberExprClass: {
976 MemberExpr *M = cast<MemberExpr>(E);
977
978 // Check for indirect access. We only want direct field accesses.
979 if (!M->isArrow())
980 return EvalVal(M->getBase());
981 else
982 return NULL;
983 }
984
985 // Everything else: we simply don't reason about them.
986 default:
987 return NULL;
988 }
989}
Ted Kremenek30c66752007-11-25 00:58:00 +0000990
991//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
992
993/// Check for comparisons of floating point operands using != and ==.
994/// Issue a warning if these are no self-comparisons, as they are not likely
995/// to do what the programmer intended.
996void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
997 bool EmitWarning = true;
998
Ted Kremenek87e30c52008-01-17 16:57:34 +0000999 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek24c61682008-01-17 17:55:13 +00001000 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek30c66752007-11-25 00:58:00 +00001001
1002 // Special case: check for x == x (which is OK).
1003 // Do not emit warnings for such cases.
1004 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
1005 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
1006 if (DRL->getDecl() == DRR->getDecl())
1007 EmitWarning = false;
1008
Ted Kremenek33159832007-11-29 00:59:04 +00001009
1010 // Special case: check for comparisons against literals that can be exactly
1011 // represented by APFloat. In such cases, do not emit a warning. This
1012 // is a heuristic: often comparison against such literals are used to
1013 // detect if a value in a variable has not changed. This clearly can
1014 // lead to false negatives.
1015 if (EmitWarning) {
1016 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
1017 if (FLL->isExact())
1018 EmitWarning = false;
1019 }
1020 else
1021 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
1022 if (FLR->isExact())
1023 EmitWarning = false;
1024 }
1025 }
1026
Ted Kremenek30c66752007-11-25 00:58:00 +00001027 // Check for comparisons with builtin types.
Sebastian Redl8b769972009-01-19 00:08:26 +00001028 if (EmitWarning)
Ted Kremenek30c66752007-11-25 00:58:00 +00001029 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
1030 if (isCallBuiltin(CL))
1031 EmitWarning = false;
1032
Sebastian Redl8b769972009-01-19 00:08:26 +00001033 if (EmitWarning)
Ted Kremenek30c66752007-11-25 00:58:00 +00001034 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
1035 if (isCallBuiltin(CR))
1036 EmitWarning = false;
1037
1038 // Emit the diagnostic.
1039 if (EmitWarning)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001040 Diag(loc, diag::warn_floatingpoint_eq)
1041 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek30c66752007-11-25 00:58:00 +00001042}