blob: e2ec2676c70ec137ef9cc2ca4a9e438c2f87f28c [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"
Chris Lattner59907c42007-08-10 20:18:51 +000021using namespace clang;
22
23/// CheckFunctionCall - Check a direct function call for various correctness
24/// and safety properties not strictly enforced by the C type system.
Sebastian Redl0eb23302009-01-19 00:08:26 +000025Action::OwningExprResult
26Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
27 OwningExprResult TheCallResult(Owned(TheCall));
Chris Lattner59907c42007-08-10 20:18:51 +000028 // Get the IdentifierInfo* for the called function.
29 IdentifierInfo *FnInfo = FDecl->getIdentifier();
Douglas Gregor2def4832008-11-17 20:34:05 +000030
31 // None of the checks below are needed for functions that don't have
32 // simple names (e.g., C++ conversion functions).
33 if (!FnInfo)
Sebastian Redl0eb23302009-01-19 00:08:26 +000034 return move(TheCallResult);
Douglas Gregor2def4832008-11-17 20:34:05 +000035
Douglas Gregor3c385e52009-02-14 18:57:46 +000036 switch (FDecl->getBuiltinID(Context)) {
Chris Lattner30ce3442007-12-19 23:59:04 +000037 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +000038 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +000039 "Wrong # arguments to builtin CFStringMakeConstantString");
Eli Friedmane8018702008-05-16 17:51:27 +000040 if (CheckBuiltinCFStringArgument(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +000041 return ExprError();
42 return move(TheCallResult);
Ted Kremenek49ff7a12008-07-09 17:58:53 +000043 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +000044 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +000045 if (SemaBuiltinVAStart(TheCall))
46 return ExprError();
47 return move(TheCallResult);
Chris Lattner1b9a0792007-12-20 00:26:33 +000048 case Builtin::BI__builtin_isgreater:
49 case Builtin::BI__builtin_isgreaterequal:
50 case Builtin::BI__builtin_isless:
51 case Builtin::BI__builtin_islessequal:
52 case Builtin::BI__builtin_islessgreater:
53 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +000054 if (SemaBuiltinUnorderedCompare(TheCall))
55 return ExprError();
56 return move(TheCallResult);
Eli Friedman6cfda232008-05-20 08:23:37 +000057 case Builtin::BI__builtin_return_address:
58 case Builtin::BI__builtin_frame_address:
Sebastian Redl0eb23302009-01-19 00:08:26 +000059 if (SemaBuiltinStackAddress(TheCall))
60 return ExprError();
61 return move(TheCallResult);
Eli Friedmand38617c2008-05-14 19:38:39 +000062 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +000063 return SemaBuiltinShuffleVector(TheCall);
64 // TheCall will be freed by the smart pointer here, but that's fine, since
65 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +000066 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +000067 if (SemaBuiltinPrefetch(TheCall))
68 return ExprError();
69 return move(TheCallResult);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +000070 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +000071 if (SemaBuiltinObjectSize(TheCall))
72 return ExprError();
Anders Carlsson71993dd2007-08-17 05:31:46 +000073 }
Daniel Dunbarde454282008-10-02 18:44:07 +000074
75 // FIXME: This mechanism should be abstracted to be less fragile and
76 // more efficient. For example, just map function ids to custom
77 // handlers.
78
Chris Lattner59907c42007-08-10 20:18:51 +000079 // Printf checking.
Douglas Gregor3c385e52009-02-14 18:57:46 +000080 if (const FormatAttr *Format = FDecl->getAttr<FormatAttr>()) {
81 if (Format->getType() == "printf") {
82 bool HasVAListArg = false;
83 if (const FunctionTypeProto *Proto
84 = FDecl->getType()->getAsFunctionTypeProto())
85 HasVAListArg = !Proto->isVariadic();
86 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
87 Format->getFirstArg() - 1);
88 }
Chris Lattner59907c42007-08-10 20:18:51 +000089 }
Sebastian Redl0eb23302009-01-19 00:08:26 +000090
91 return move(TheCallResult);
Anders Carlsson71993dd2007-08-17 05:31:46 +000092}
93
94/// CheckBuiltinCFStringArgument - Checks that the argument to the builtin
95/// CFString constructor is correct
Chris Lattnercc6f65d2007-08-25 05:30:33 +000096bool Sema::CheckBuiltinCFStringArgument(Expr* Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +000097 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +000098
99 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
100
101 if (!Literal || Literal->isWide()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000102 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
103 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000104 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000105 }
106
107 const char *Data = Literal->getStrData();
108 unsigned Length = Literal->getByteLength();
109
110 for (unsigned i = 0; i < Length; ++i) {
111 if (!isascii(Data[i])) {
112 Diag(PP.AdvanceToTokenCharacter(Arg->getLocStart(), i + 1),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000113 diag::warn_cfstring_literal_contains_non_ascii_character)
114 << Arg->getSourceRange();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000115 break;
116 }
117
118 if (!Data[i]) {
119 Diag(PP.AdvanceToTokenCharacter(Arg->getLocStart(), i + 1),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000120 diag::warn_cfstring_literal_contains_nul_character)
121 << Arg->getSourceRange();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000122 break;
123 }
124 }
125
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000126 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000127}
128
Chris Lattnerc27c6652007-12-20 00:05:45 +0000129/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
130/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000131bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
132 Expr *Fn = TheCall->getCallee();
133 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000134 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000135 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000136 << 0 /*function call*/ << Fn->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000137 << SourceRange(TheCall->getArg(2)->getLocStart(),
138 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000139 return true;
140 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000141
142 if (TheCall->getNumArgs() < 2) {
143 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
144 << 0 /*function call*/;
145 }
146
Chris Lattnerc27c6652007-12-20 00:05:45 +0000147 // Determine whether the current function is variadic or not.
148 bool isVariadic;
Eli Friedman56f20ae2008-12-15 22:05:35 +0000149 if (getCurFunctionDecl()) {
150 if (FunctionTypeProto* FTP =
151 dyn_cast<FunctionTypeProto>(getCurFunctionDecl()->getType()))
152 isVariadic = FTP->isVariadic();
153 else
154 isVariadic = false;
155 } else {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000156 isVariadic = getCurMethodDecl()->isVariadic();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000157 }
Chris Lattner30ce3442007-12-19 23:59:04 +0000158
Chris Lattnerc27c6652007-12-20 00:05:45 +0000159 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000160 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
161 return true;
162 }
163
164 // Verify that the second argument to the builtin is the last argument of the
165 // current function or method.
166 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000167 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Anders Carlsson88cf2262008-02-11 04:20:54 +0000168
169 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
170 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000171 // FIXME: This isn't correct for methods (results in bogus warning).
172 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000173 const ParmVarDecl *LastArg;
Chris Lattner371f2582008-12-04 23:50:19 +0000174 if (FunctionDecl *FD = getCurFunctionDecl())
175 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000176 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000177 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000178 SecondArgIsLastNamedArgument = PV == LastArg;
179 }
180 }
181
182 if (!SecondArgIsLastNamedArgument)
Chris Lattner925e60d2007-12-28 05:29:59 +0000183 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000184 diag::warn_second_parameter_of_va_start_not_last_named_argument);
185 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000186}
Chris Lattner30ce3442007-12-19 23:59:04 +0000187
Chris Lattner1b9a0792007-12-20 00:26:33 +0000188/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
189/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000190bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
191 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000192 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
193 << 0 /*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000194 if (TheCall->getNumArgs() > 2)
195 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000196 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000197 << 0 /*function call*/
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000198 << SourceRange(TheCall->getArg(2)->getLocStart(),
199 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner1b9a0792007-12-20 00:26:33 +0000200
Chris Lattner925e60d2007-12-28 05:29:59 +0000201 Expr *OrigArg0 = TheCall->getArg(0);
202 Expr *OrigArg1 = TheCall->getArg(1);
Chris Lattner1b9a0792007-12-20 00:26:33 +0000203
204 // Do standard promotions between the two arguments, returning their common
205 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000206 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Chris Lattner1b9a0792007-12-20 00:26:33 +0000207
208 // If the common type isn't a real floating type, then the arguments were
209 // invalid for this operation.
210 if (!Res->isRealFloatingType())
Chris Lattner925e60d2007-12-28 05:29:59 +0000211 return Diag(OrigArg0->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000212 diag::err_typecheck_call_invalid_ordered_compare)
Chris Lattnerd1625842008-11-24 06:25:27 +0000213 << OrigArg0->getType() << OrigArg1->getType()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000214 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
Chris Lattner1b9a0792007-12-20 00:26:33 +0000215
216 return false;
217}
218
Eli Friedman6cfda232008-05-20 08:23:37 +0000219bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) {
220 // The signature for these builtins is exact; the only thing we need
221 // to check is that the argument is a constant.
222 SourceLocation Loc;
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000223 if (!TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc))
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000224 return Diag(Loc, diag::err_stack_const_level) << TheCall->getSourceRange();
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000225
Eli Friedman6cfda232008-05-20 08:23:37 +0000226 return false;
227}
228
Eli Friedmand38617c2008-05-14 19:38:39 +0000229/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
230// This is declared to take (...), so we have to check everything.
Sebastian Redl0eb23302009-01-19 00:08:26 +0000231Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000232 if (TheCall->getNumArgs() < 3)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000233 return ExprError(Diag(TheCall->getLocEnd(),
234 diag::err_typecheck_call_too_few_args)
235 << 0 /*function call*/ << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000236
237 QualType FAType = TheCall->getArg(0)->getType();
238 QualType SAType = TheCall->getArg(1)->getType();
239
240 if (!FAType->isVectorType() || !SAType->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000241 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
242 << SourceRange(TheCall->getArg(0)->getLocStart(),
243 TheCall->getArg(1)->getLocEnd());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000244 return ExprError();
Eli Friedmand38617c2008-05-14 19:38:39 +0000245 }
246
Chris Lattnerb77792e2008-07-26 22:17:49 +0000247 if (Context.getCanonicalType(FAType).getUnqualifiedType() !=
248 Context.getCanonicalType(SAType).getUnqualifiedType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000249 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
250 << SourceRange(TheCall->getArg(0)->getLocStart(),
251 TheCall->getArg(1)->getLocEnd());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000252 return ExprError();
Eli Friedmand38617c2008-05-14 19:38:39 +0000253 }
254
255 unsigned numElements = FAType->getAsVectorType()->getNumElements();
256 if (TheCall->getNumArgs() != numElements+2) {
257 if (TheCall->getNumArgs() < numElements+2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000258 return ExprError(Diag(TheCall->getLocEnd(),
259 diag::err_typecheck_call_too_few_args)
260 << 0 /*function call*/ << TheCall->getSourceRange());
261 return ExprError(Diag(TheCall->getLocEnd(),
262 diag::err_typecheck_call_too_many_args)
263 << 0 /*function call*/ << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000264 }
265
266 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
267 llvm::APSInt Result(32);
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000268 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000269 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000270 diag::err_shufflevector_nonconstant_argument)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000271 << TheCall->getArg(i)->getSourceRange());
272
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000273 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000274 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000275 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000276 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000277 }
278
279 llvm::SmallVector<Expr*, 32> exprs;
280
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000281 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000282 exprs.push_back(TheCall->getArg(i));
283 TheCall->setArg(i, 0);
284 }
285
Ted Kremenek8189cde2009-02-07 01:47:29 +0000286 return Owned(new (Context) ShuffleVectorExpr(exprs.begin(), numElements+2,
287 FAType,
288 TheCall->getCallee()->getLocStart(),
289 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000290}
Chris Lattner30ce3442007-12-19 23:59:04 +0000291
Daniel Dunbar4493f792008-07-21 22:59:13 +0000292/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
293// This is declared to take (const void*, ...) and can take two
294// optional constant int args.
295bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000296 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000297
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000298 if (NumArgs > 3)
299 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000300 << 0 /*function call*/ << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000301
302 // Argument 0 is checked for us and the remaining arguments must be
303 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000304 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000305 Expr *Arg = TheCall->getArg(i);
306 QualType RWType = Arg->getType();
307
308 const BuiltinType *BT = RWType->getAsBuiltinType();
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000309 llvm::APSInt Result;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000310 if (!BT || BT->getKind() != BuiltinType::Int ||
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000311 !Arg->isIntegerConstantExpr(Result, Context))
312 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument)
313 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar4493f792008-07-21 22:59:13 +0000314
315 // FIXME: gcc issues a warning and rewrites these to 0. These
316 // seems especially odd for the third argument since the default
317 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000318 if (i == 1) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000319 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000320 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
321 << "0" << "1" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar4493f792008-07-21 22:59:13 +0000322 } else {
323 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000324 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
325 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar4493f792008-07-21 22:59:13 +0000326 }
327 }
328
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000329 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000330}
331
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000332/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
333/// int type). This simply type checks that type is one of the defined
334/// constants (0-3).
335bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
336 Expr *Arg = TheCall->getArg(1);
337 QualType ArgType = Arg->getType();
338 const BuiltinType *BT = ArgType->getAsBuiltinType();
339 llvm::APSInt Result(32);
340 if (!BT || BT->getKind() != BuiltinType::Int ||
341 !Arg->isIntegerConstantExpr(Result, Context)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000342 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
343 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000344 }
345
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 Dunbard5f8a4f2008-09-03 21:13:56 +0000349 }
350
351 return false;
352}
353
Ted Kremenekd30ef872009-01-12 23:09:09 +0000354// Handle i > 1 ? "x" : "y", recursivelly
355bool Sema::SemaCheckStringLiteral(Expr *E, CallExpr *TheCall, bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000356 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenekd30ef872009-01-12 23:09:09 +0000357
358 switch (E->getStmtClass()) {
359 case Stmt::ConditionalOperatorClass: {
360 ConditionalOperator *C = cast<ConditionalOperator>(E);
361 return SemaCheckStringLiteral(C->getLHS(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000362 HasVAListArg, format_idx, firstDataArg)
Ted Kremenekd30ef872009-01-12 23:09:09 +0000363 && SemaCheckStringLiteral(C->getRHS(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000364 HasVAListArg, format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000365 }
366
367 case Stmt::ImplicitCastExprClass: {
368 ImplicitCastExpr *Expr = dyn_cast<ImplicitCastExpr>(E);
369 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000370 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000371 }
372
373 case Stmt::ParenExprClass: {
374 ParenExpr *Expr = dyn_cast<ParenExpr>(E);
375 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000376 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000377 }
378
379 default: {
380 ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E);
381 StringLiteral *StrE = NULL;
382
383 if (ObjCFExpr)
384 StrE = ObjCFExpr->getString();
385 else
386 StrE = dyn_cast<StringLiteral>(E);
387
388 if (StrE) {
Douglas Gregor3c385e52009-02-14 18:57:46 +0000389 CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx,
390 firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000391 return true;
392 }
393
394 return false;
395 }
396 }
397}
398
399
Chris Lattner59907c42007-08-10 20:18:51 +0000400/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Ted Kremenek71895b92007-08-14 17:39:48 +0000401/// correct use of format strings.
402///
403/// HasVAListArg - A predicate indicating whether the printf-like
404/// function is passed an explicit va_arg argument (e.g., vprintf)
405///
406/// format_idx - The index into Args for the format string.
407///
408/// Improper format strings to functions in the printf family can be
409/// the source of bizarre bugs and very serious security holes. A
410/// good source of information is available in the following paper
411/// (which includes additional references):
Chris Lattner59907c42007-08-10 20:18:51 +0000412///
413/// FormatGuard: Automatic Protection From printf Format String
414/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremenek71895b92007-08-14 17:39:48 +0000415///
416/// Functionality implemented:
417///
418/// We can statically check the following properties for string
419/// literal format strings for non v.*printf functions (where the
420/// arguments are passed directly):
421//
422/// (1) Are the number of format conversions equal to the number of
423/// data arguments?
424///
425/// (2) Does each format conversion correctly match the type of the
426/// corresponding data argument? (TODO)
427///
428/// Moreover, for all printf functions we can:
429///
430/// (3) Check for a missing format string (when not caught by type checking).
431///
432/// (4) Check for no-operation flags; e.g. using "#" with format
433/// conversion 'c' (TODO)
434///
435/// (5) Check the use of '%n', a major source of security holes.
436///
437/// (6) Check for malformed format conversions that don't specify anything.
438///
439/// (7) Check for empty format strings. e.g: printf("");
440///
441/// (8) Check that the format string is a wide literal.
442///
Ted Kremenek6d439592008-03-03 16:50:00 +0000443/// (9) Also check the arguments of functions with the __format__ attribute.
444/// (TODO).
445///
Ted Kremenek71895b92007-08-14 17:39:48 +0000446/// All of these checks can be done by parsing the format string.
447///
448/// For now, we ONLY do (1), (3), (5), (6), (7), and (8).
Chris Lattner59907c42007-08-10 20:18:51 +0000449void
Chris Lattner925e60d2007-12-28 05:29:59 +0000450Sema::CheckPrintfArguments(CallExpr *TheCall, bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000451 unsigned format_idx, unsigned firstDataArg) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000452 Expr *Fn = TheCall->getCallee();
453
Ted Kremenek71895b92007-08-14 17:39:48 +0000454 // CHECK: printf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +0000455 if (format_idx >= TheCall->getNumArgs()) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000456 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string)
457 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000458 return;
459 }
460
Chris Lattner56f34942008-02-13 01:02:39 +0000461 Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Chris Lattner459e8482007-08-25 05:36:18 +0000462
Chris Lattner59907c42007-08-10 20:18:51 +0000463 // CHECK: format string is not a string literal.
464 //
Ted Kremenek71895b92007-08-14 17:39:48 +0000465 // Dynamically generated format strings are difficult to
466 // automatically vet at compile time. Requiring that format strings
467 // are string literals: (1) permits the checking of format strings by
468 // the compiler and thereby (2) can practically remove the source of
469 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000470
471 // Format string can be either ObjC string (e.g. @"%d") or
472 // C string (e.g. "%d")
473 // ObjC string uses the same format specifiers as C string, so we can use
474 // the same format string checking logic for both ObjC and C strings.
Douglas Gregor3c385e52009-02-14 18:57:46 +0000475 bool isFExpr = SemaCheckStringLiteral(OrigFormatExpr, TheCall,
476 HasVAListArg, format_idx,
477 firstDataArg);
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000478
Ted Kremenekd30ef872009-01-12 23:09:09 +0000479 if (!isFExpr) {
Ted Kremenek4a336462007-12-17 19:03:13 +0000480 // For vprintf* functions (i.e., HasVAListArg==true), we add a
481 // special check to see if the format string is a function parameter
482 // of the function calling the printf function. If the function
483 // has an attribute indicating it is a printf-like function, then we
484 // should suppress warnings concerning non-literals being used in a call
485 // to a vprintf function. For example:
486 //
487 // void
488 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...) {
489 // va_list ap;
490 // va_start(ap, fmt);
491 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
492 // ...
493 //
494 //
495 // FIXME: We don't have full attribute support yet, so just check to see
496 // if the argument is a DeclRefExpr that references a parameter. We'll
497 // add proper support for checking the attribute later.
498 if (HasVAListArg)
Chris Lattner998568f2007-12-28 05:38:24 +0000499 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(OrigFormatExpr))
500 if (isa<ParmVarDecl>(DR->getDecl()))
Ted Kremenek4a336462007-12-17 19:03:13 +0000501 return;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000502
Chris Lattner925e60d2007-12-28 05:29:59 +0000503 Diag(TheCall->getArg(format_idx)->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000504 diag::warn_printf_not_string_constant)
505 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000506 return;
507 }
Ted Kremenekd30ef872009-01-12 23:09:09 +0000508}
Ted Kremenek71895b92007-08-14 17:39:48 +0000509
Ted Kremenekd30ef872009-01-12 23:09:09 +0000510void Sema::CheckPrintfString(StringLiteral *FExpr, Expr *OrigFormatExpr,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000511 CallExpr *TheCall, bool HasVAListArg, unsigned format_idx,
512 unsigned firstDataArg) {
Ted Kremenekd30ef872009-01-12 23:09:09 +0000513
514 ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(OrigFormatExpr);
Ted Kremenek71895b92007-08-14 17:39:48 +0000515 // CHECK: is the format string a wide literal?
516 if (FExpr->isWide()) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000517 Diag(FExpr->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000518 diag::warn_printf_format_string_is_wide_literal)
519 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000520 return;
521 }
522
523 // Str - The format string. NOTE: this is NOT null-terminated!
524 const char * const Str = FExpr->getStrData();
525
526 // CHECK: empty format string?
527 const unsigned StrLen = FExpr->getByteLength();
528
529 if (StrLen == 0) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000530 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string)
531 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000532 return;
533 }
534
535 // We process the format string using a binary state machine. The
536 // current state is stored in CurrentState.
537 enum {
538 state_OrdChr,
539 state_Conversion
540 } CurrentState = state_OrdChr;
541
542 // numConversions - The number of conversions seen so far. This is
543 // incremented as we traverse the format string.
544 unsigned numConversions = 0;
545
546 // numDataArgs - The number of data arguments after the format
547 // string. This can only be determined for non vprintf-like
548 // functions. For those functions, this value is 1 (the sole
549 // va_arg argument).
Douglas Gregor3c385e52009-02-14 18:57:46 +0000550 unsigned numDataArgs = TheCall->getNumArgs()-firstDataArg;
Ted Kremenek71895b92007-08-14 17:39:48 +0000551
552 // Inspect the format string.
553 unsigned StrIdx = 0;
554
555 // LastConversionIdx - Index within the format string where we last saw
556 // a '%' character that starts a new format conversion.
557 unsigned LastConversionIdx = 0;
558
Chris Lattner925e60d2007-12-28 05:29:59 +0000559 for (; StrIdx < StrLen; ++StrIdx) {
Chris Lattner998568f2007-12-28 05:38:24 +0000560
Ted Kremenek71895b92007-08-14 17:39:48 +0000561 // Is the number of detected conversion conversions greater than
562 // the number of matching data arguments? If so, stop.
563 if (!HasVAListArg && numConversions > numDataArgs) break;
564
565 // Handle "\0"
Chris Lattner925e60d2007-12-28 05:29:59 +0000566 if (Str[StrIdx] == '\0') {
Ted Kremenek71895b92007-08-14 17:39:48 +0000567 // The string returned by getStrData() is not null-terminated,
568 // so the presence of a null character is likely an error.
Chris Lattner998568f2007-12-28 05:38:24 +0000569 Diag(PP.AdvanceToTokenCharacter(FExpr->getLocStart(), StrIdx+1),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000570 diag::warn_printf_format_string_contains_null_char)
571 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000572 return;
573 }
574
575 // Ordinary characters (not processing a format conversion).
576 if (CurrentState == state_OrdChr) {
577 if (Str[StrIdx] == '%') {
578 CurrentState = state_Conversion;
579 LastConversionIdx = StrIdx;
580 }
581 continue;
582 }
583
584 // Seen '%'. Now processing a format conversion.
585 switch (Str[StrIdx]) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000586 // Handle dynamic precision or width specifier.
587 case '*': {
588 ++numConversions;
589
590 if (!HasVAListArg && numConversions > numDataArgs) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000591 SourceLocation Loc = FExpr->getLocStart();
592 Loc = PP.AdvanceToTokenCharacter(Loc, StrIdx+1);
Ted Kremenek580b6642007-10-12 20:51:52 +0000593
Ted Kremenek580b6642007-10-12 20:51:52 +0000594 if (Str[StrIdx-1] == '.')
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000595 Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg)
596 << OrigFormatExpr->getSourceRange();
Ted Kremenek580b6642007-10-12 20:51:52 +0000597 else
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000598 Diag(Loc, diag::warn_printf_asterisk_width_missing_arg)
599 << OrigFormatExpr->getSourceRange();
Ted Kremenek580b6642007-10-12 20:51:52 +0000600
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000601 // Don't do any more checking. We'll just emit spurious errors.
602 return;
Ted Kremenek580b6642007-10-12 20:51:52 +0000603 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000604
605 // Perform type checking on width/precision specifier.
606 Expr *E = TheCall->getArg(format_idx+numConversions);
607 if (const BuiltinType *BT = E->getType()->getAsBuiltinType())
608 if (BT->getKind() == BuiltinType::Int)
609 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000610
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000611 SourceLocation Loc =
612 PP.AdvanceToTokenCharacter(FExpr->getLocStart(), StrIdx+1);
613
614 if (Str[StrIdx-1] == '.')
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000615 Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000616 << E->getType() << E->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000617 else
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000618 Diag(Loc, diag::warn_printf_asterisk_width_wrong_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000619 << E->getType() << E->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000620
621 break;
622 }
623
624 // Characters which can terminate a format conversion
625 // (e.g. "%d"). Characters that specify length modifiers or
626 // other flags are handled by the default case below.
627 //
628 // FIXME: additional checks will go into the following cases.
629 case 'i':
630 case 'd':
631 case 'o':
632 case 'u':
633 case 'x':
634 case 'X':
635 case 'D':
636 case 'O':
637 case 'U':
638 case 'e':
639 case 'E':
640 case 'f':
641 case 'F':
642 case 'g':
643 case 'G':
644 case 'a':
645 case 'A':
646 case 'c':
647 case 'C':
648 case 'S':
649 case 's':
650 case 'p':
651 ++numConversions;
652 CurrentState = state_OrdChr;
653 break;
654
655 // CHECK: Are we using "%n"? Issue a warning.
656 case 'n': {
657 ++numConversions;
658 CurrentState = state_OrdChr;
659 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
660 LastConversionIdx+1);
661
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000662 Diag(Loc, diag::warn_printf_write_back)<<OrigFormatExpr->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000663 break;
664 }
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000665
666 // Handle "%@"
667 case '@':
668 // %@ is allowed in ObjC format strings only.
669 if(ObjCFExpr != NULL)
670 CurrentState = state_OrdChr;
671 else {
672 // Issue a warning: invalid format conversion.
673 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
674 LastConversionIdx+1);
675
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000676 Diag(Loc, diag::warn_printf_invalid_conversion)
677 << std::string(Str+LastConversionIdx,
678 Str+std::min(LastConversionIdx+2, StrLen))
679 << OrigFormatExpr->getSourceRange();
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000680 }
681 ++numConversions;
682 break;
683
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000684 // Handle "%%"
685 case '%':
686 // Sanity check: Was the first "%" character the previous one?
687 // If not, we will assume that we have a malformed format
688 // conversion, and that the current "%" character is the start
689 // of a new conversion.
690 if (StrIdx - LastConversionIdx == 1)
691 CurrentState = state_OrdChr;
692 else {
693 // Issue a warning: invalid format conversion.
Chris Lattner925e60d2007-12-28 05:29:59 +0000694 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
695 LastConversionIdx+1);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000696
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000697 Diag(Loc, diag::warn_printf_invalid_conversion)
698 << std::string(Str+LastConversionIdx, Str+StrIdx)
699 << OrigFormatExpr->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000700
701 // This conversion is broken. Advance to the next format
702 // conversion.
703 LastConversionIdx = StrIdx;
704 ++numConversions;
Ted Kremenek71895b92007-08-14 17:39:48 +0000705 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000706 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000707
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000708 default:
709 // This case catches all other characters: flags, widths, etc.
710 // We should eventually process those as well.
711 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000712 }
713 }
714
715 if (CurrentState == state_Conversion) {
716 // Issue a warning: invalid format conversion.
Chris Lattner925e60d2007-12-28 05:29:59 +0000717 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
718 LastConversionIdx+1);
Ted Kremenek71895b92007-08-14 17:39:48 +0000719
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000720 Diag(Loc, diag::warn_printf_invalid_conversion)
721 << std::string(Str+LastConversionIdx,
722 Str+std::min(LastConversionIdx+2, StrLen))
723 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000724 return;
725 }
726
727 if (!HasVAListArg) {
728 // CHECK: Does the number of format conversions exceed the number
729 // of data arguments?
730 if (numConversions > numDataArgs) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000731 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
732 LastConversionIdx);
Ted Kremenek71895b92007-08-14 17:39:48 +0000733
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000734 Diag(Loc, diag::warn_printf_insufficient_data_args)
735 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000736 }
737 // CHECK: Does the number of data arguments exceed the number of
738 // format conversions in the format string?
739 else if (numConversions < numDataArgs)
Chris Lattner925e60d2007-12-28 05:29:59 +0000740 Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000741 diag::warn_printf_too_many_data_args)
742 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000743 }
744}
Ted Kremenek06de2762007-08-17 16:46:58 +0000745
746//===--- CHECK: Return Address of Stack Variable --------------------------===//
747
748static DeclRefExpr* EvalVal(Expr *E);
749static DeclRefExpr* EvalAddr(Expr* E);
750
751/// CheckReturnStackAddr - Check if a return statement returns the address
752/// of a stack variable.
753void
754Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
755 SourceLocation ReturnLoc) {
Chris Lattner56f34942008-02-13 01:02:39 +0000756
Ted Kremenek06de2762007-08-17 16:46:58 +0000757 // Perform checking for returned stack addresses.
Steve Naroffdd972f22008-09-05 22:11:13 +0000758 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Ted Kremenek06de2762007-08-17 16:46:58 +0000759 if (DeclRefExpr *DR = EvalAddr(RetValExp))
Chris Lattner3c73c412008-11-19 08:23:25 +0000760 Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
Chris Lattner08631c52008-11-23 21:45:46 +0000761 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Steve Naroffc50a4a52008-09-16 22:25:10 +0000762
763 // Skip over implicit cast expressions when checking for block expressions.
764 if (ImplicitCastExpr *IcExpr =
765 dyn_cast_or_null<ImplicitCastExpr>(RetValExp))
766 RetValExp = IcExpr->getSubExpr();
767
Steve Naroff61f40a22008-09-10 19:17:48 +0000768 if (BlockExpr *C = dyn_cast_or_null<BlockExpr>(RetValExp))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000769 Diag(C->getLocStart(), diag::err_ret_local_block)
770 << C->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +0000771 }
772 // Perform checking for stack values returned by reference.
773 else if (lhsType->isReferenceType()) {
Douglas Gregor49badde2008-10-27 19:41:14 +0000774 // Check for a reference to the stack
775 if (DeclRefExpr *DR = EvalVal(RetValExp))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000776 Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
Chris Lattner08631c52008-11-23 21:45:46 +0000777 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +0000778 }
779}
780
781/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
782/// check if the expression in a return statement evaluates to an address
783/// to a location on the stack. The recursion is used to traverse the
784/// AST of the return expression, with recursion backtracking when we
785/// encounter a subexpression that (1) clearly does not lead to the address
786/// of a stack variable or (2) is something we cannot determine leads to
787/// the address of a stack variable based on such local checking.
788///
Ted Kremeneke8c600f2007-08-28 17:02:55 +0000789/// EvalAddr processes expressions that are pointers that are used as
790/// references (and not L-values). EvalVal handles all other values.
Ted Kremenek06de2762007-08-17 16:46:58 +0000791/// At the base case of the recursion is a check for a DeclRefExpr* in
792/// the refers to a stack variable.
793///
794/// This implementation handles:
795///
796/// * pointer-to-pointer casts
797/// * implicit conversions from array references to pointers
798/// * taking the address of fields
799/// * arbitrary interplay between "&" and "*" operators
800/// * pointer arithmetic from an address of a stack variable
801/// * taking the address of an array element where the array is on the stack
802static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek06de2762007-08-17 16:46:58 +0000803 // We should only be called for evaluating pointer expressions.
Steve Naroffdd972f22008-09-05 22:11:13 +0000804 assert((E->getType()->isPointerType() ||
805 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000806 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000807 "EvalAddr only works on pointers");
Ted Kremenek06de2762007-08-17 16:46:58 +0000808
809 // Our "symbolic interpreter" is just a dispatch off the currently
810 // viewed AST node. We then recursively traverse the AST by calling
811 // EvalAddr and EvalVal appropriately.
812 switch (E->getStmtClass()) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000813 case Stmt::ParenExprClass:
814 // Ignore parentheses.
815 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek06de2762007-08-17 16:46:58 +0000816
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000817 case Stmt::UnaryOperatorClass: {
818 // The only unary operator that make sense to handle here
819 // is AddrOf. All others don't make sense as pointers.
820 UnaryOperator *U = cast<UnaryOperator>(E);
Ted Kremenek06de2762007-08-17 16:46:58 +0000821
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000822 if (U->getOpcode() == UnaryOperator::AddrOf)
823 return EvalVal(U->getSubExpr());
824 else
Ted Kremenek06de2762007-08-17 16:46:58 +0000825 return NULL;
826 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000827
828 case Stmt::BinaryOperatorClass: {
829 // Handle pointer arithmetic. All other binary operators are not valid
830 // in this context.
831 BinaryOperator *B = cast<BinaryOperator>(E);
832 BinaryOperator::Opcode op = B->getOpcode();
833
834 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
835 return NULL;
836
837 Expr *Base = B->getLHS();
838
839 // Determine which argument is the real pointer base. It could be
840 // the RHS argument instead of the LHS.
841 if (!Base->getType()->isPointerType()) Base = B->getRHS();
842
843 assert (Base->getType()->isPointerType());
844 return EvalAddr(Base);
845 }
Steve Naroff61f40a22008-09-10 19:17:48 +0000846
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000847 // For conditional operators we need to see if either the LHS or RHS are
848 // valid DeclRefExpr*s. If one of them is valid, we return it.
849 case Stmt::ConditionalOperatorClass: {
850 ConditionalOperator *C = cast<ConditionalOperator>(E);
851
852 // Handle the GNU extension for missing LHS.
853 if (Expr *lhsExpr = C->getLHS())
854 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
855 return LHS;
856
857 return EvalAddr(C->getRHS());
858 }
859
Ted Kremenek54b52742008-08-07 00:49:01 +0000860 // For casts, we need to handle conversions from arrays to
861 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +0000862 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +0000863 case Stmt::CStyleCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +0000864 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +0000865 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +0000866 QualType T = SubExpr->getType();
867
Steve Naroffdd972f22008-09-05 22:11:13 +0000868 if (SubExpr->getType()->isPointerType() ||
869 SubExpr->getType()->isBlockPointerType() ||
870 SubExpr->getType()->isObjCQualifiedIdType())
Ted Kremenek54b52742008-08-07 00:49:01 +0000871 return EvalAddr(SubExpr);
872 else if (T->isArrayType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000873 return EvalVal(SubExpr);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000874 else
Ted Kremenek54b52742008-08-07 00:49:01 +0000875 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000876 }
877
878 // C++ casts. For dynamic casts, static casts, and const casts, we
879 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +0000880 // through the cast. In the case the dynamic cast doesn't fail (and
881 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000882 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +0000883 // FIXME: The comment about is wrong; we're not always converting
884 // from pointer to pointer. I'm guessing that this code should also
885 // handle references to objects.
886 case Stmt::CXXStaticCastExprClass:
887 case Stmt::CXXDynamicCastExprClass:
888 case Stmt::CXXConstCastExprClass:
889 case Stmt::CXXReinterpretCastExprClass: {
890 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +0000891 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000892 return EvalAddr(S);
893 else
894 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000895 }
896
897 // Everything else: we simply don't reason about them.
898 default:
899 return NULL;
900 }
Ted Kremenek06de2762007-08-17 16:46:58 +0000901}
902
903
904/// EvalVal - This function is complements EvalAddr in the mutual recursion.
905/// See the comments for EvalAddr for more details.
906static DeclRefExpr* EvalVal(Expr *E) {
907
Ted Kremeneke8c600f2007-08-28 17:02:55 +0000908 // We should only be called for evaluating non-pointer expressions, or
909 // expressions with a pointer type that are not used as references but instead
910 // are l-values (e.g., DeclRefExpr with a pointer type).
911
Ted Kremenek06de2762007-08-17 16:46:58 +0000912 // Our "symbolic interpreter" is just a dispatch off the currently
913 // viewed AST node. We then recursively traverse the AST by calling
914 // EvalAddr and EvalVal appropriately.
915 switch (E->getStmtClass()) {
Douglas Gregor1a49af92009-01-06 05:10:23 +0000916 case Stmt::DeclRefExprClass:
917 case Stmt::QualifiedDeclRefExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +0000918 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
919 // at code that refers to a variable's name. We check if it has local
920 // storage within the function, and if so, return the expression.
921 DeclRefExpr *DR = cast<DeclRefExpr>(E);
922
923 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000924 if(V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
Ted Kremenek06de2762007-08-17 16:46:58 +0000925
926 return NULL;
927 }
928
929 case Stmt::ParenExprClass:
930 // Ignore parentheses.
931 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
932
933 case Stmt::UnaryOperatorClass: {
934 // The only unary operator that make sense to handle here
935 // is Deref. All others don't resolve to a "name." This includes
936 // handling all sorts of rvalues passed to a unary operator.
937 UnaryOperator *U = cast<UnaryOperator>(E);
938
939 if (U->getOpcode() == UnaryOperator::Deref)
940 return EvalAddr(U->getSubExpr());
941
942 return NULL;
943 }
944
945 case Stmt::ArraySubscriptExprClass: {
946 // Array subscripts are potential references to data on the stack. We
947 // retrieve the DeclRefExpr* for the array variable if it indeed
948 // has local storage.
Ted Kremenek23245122007-08-20 16:18:38 +0000949 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek06de2762007-08-17 16:46:58 +0000950 }
951
952 case Stmt::ConditionalOperatorClass: {
953 // For conditional operators we need to see if either the LHS or RHS are
954 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
955 ConditionalOperator *C = cast<ConditionalOperator>(E);
956
Anders Carlsson39073232007-11-30 19:04:31 +0000957 // Handle the GNU extension for missing LHS.
958 if (Expr *lhsExpr = C->getLHS())
959 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
960 return LHS;
961
962 return EvalVal(C->getRHS());
Ted Kremenek06de2762007-08-17 16:46:58 +0000963 }
964
965 // Accesses to members are potential references to data on the stack.
966 case Stmt::MemberExprClass: {
967 MemberExpr *M = cast<MemberExpr>(E);
968
969 // Check for indirect access. We only want direct field accesses.
970 if (!M->isArrow())
971 return EvalVal(M->getBase());
972 else
973 return NULL;
974 }
975
976 // Everything else: we simply don't reason about them.
977 default:
978 return NULL;
979 }
980}
Ted Kremenek588e5eb2007-11-25 00:58:00 +0000981
982//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
983
984/// Check for comparisons of floating point operands using != and ==.
985/// Issue a warning if these are no self-comparisons, as they are not likely
986/// to do what the programmer intended.
987void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
988 bool EmitWarning = true;
989
Ted Kremenek4e99a5f2008-01-17 16:57:34 +0000990 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek32e97b62008-01-17 17:55:13 +0000991 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek588e5eb2007-11-25 00:58:00 +0000992
993 // Special case: check for x == x (which is OK).
994 // Do not emit warnings for such cases.
995 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
996 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
997 if (DRL->getDecl() == DRR->getDecl())
998 EmitWarning = false;
999
Ted Kremenek1b500bb2007-11-29 00:59:04 +00001000
1001 // Special case: check for comparisons against literals that can be exactly
1002 // represented by APFloat. In such cases, do not emit a warning. This
1003 // is a heuristic: often comparison against such literals are used to
1004 // detect if a value in a variable has not changed. This clearly can
1005 // lead to false negatives.
1006 if (EmitWarning) {
1007 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
1008 if (FLL->isExact())
1009 EmitWarning = false;
1010 }
1011 else
1012 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
1013 if (FLR->isExact())
1014 EmitWarning = false;
1015 }
1016 }
1017
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001018 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001019 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001020 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001021 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001022 EmitWarning = false;
1023
Sebastian Redl0eb23302009-01-19 00:08:26 +00001024 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001025 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001026 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001027 EmitWarning = false;
1028
1029 // Emit the diagnostic.
1030 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001031 Diag(loc, diag::warn_floatingpoint_eq)
1032 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001033}