blob: db622f66483e01c810376f424335bcfae5b9e0d3 [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");
Chris Lattner69039812009-02-18 06:01:06 +000040 if (CheckObjCString(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
Chris Lattner69039812009-02-18 06:01:06 +000094/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +000095/// CFString constructor is correct
Chris Lattner69039812009-02-18 06:01:06 +000096bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +000097 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +000098 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
99
100 if (!Literal || Literal->isWide()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000101 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
102 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000103 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000104 }
105
106 const char *Data = Literal->getStrData();
107 unsigned Length = Literal->getByteLength();
108
109 for (unsigned i = 0; i < Length; ++i) {
110 if (!isascii(Data[i])) {
111 Diag(PP.AdvanceToTokenCharacter(Arg->getLocStart(), i + 1),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000112 diag::warn_cfstring_literal_contains_non_ascii_character)
113 << Arg->getSourceRange();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000114 break;
115 }
116
117 if (!Data[i]) {
118 Diag(PP.AdvanceToTokenCharacter(Arg->getLocStart(), i + 1),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000119 diag::warn_cfstring_literal_contains_nul_character)
120 << Arg->getSourceRange();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000121 break;
122 }
123 }
124
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000125 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000126}
127
Chris Lattnerc27c6652007-12-20 00:05:45 +0000128/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
129/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000130bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
131 Expr *Fn = TheCall->getCallee();
132 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000133 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000134 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000135 << 0 /*function call*/ << Fn->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000136 << SourceRange(TheCall->getArg(2)->getLocStart(),
137 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000138 return true;
139 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000140
141 if (TheCall->getNumArgs() < 2) {
142 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
143 << 0 /*function call*/;
144 }
145
Chris Lattnerc27c6652007-12-20 00:05:45 +0000146 // Determine whether the current function is variadic or not.
147 bool isVariadic;
Eli Friedman56f20ae2008-12-15 22:05:35 +0000148 if (getCurFunctionDecl()) {
149 if (FunctionTypeProto* FTP =
150 dyn_cast<FunctionTypeProto>(getCurFunctionDecl()->getType()))
151 isVariadic = FTP->isVariadic();
152 else
153 isVariadic = false;
154 } else {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000155 isVariadic = getCurMethodDecl()->isVariadic();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000156 }
Chris Lattner30ce3442007-12-19 23:59:04 +0000157
Chris Lattnerc27c6652007-12-20 00:05:45 +0000158 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000159 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
160 return true;
161 }
162
163 // Verify that the second argument to the builtin is the last argument of the
164 // current function or method.
165 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000166 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Anders Carlsson88cf2262008-02-11 04:20:54 +0000167
168 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
169 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000170 // FIXME: This isn't correct for methods (results in bogus warning).
171 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000172 const ParmVarDecl *LastArg;
Chris Lattner371f2582008-12-04 23:50:19 +0000173 if (FunctionDecl *FD = getCurFunctionDecl())
174 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000175 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000176 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000177 SecondArgIsLastNamedArgument = PV == LastArg;
178 }
179 }
180
181 if (!SecondArgIsLastNamedArgument)
Chris Lattner925e60d2007-12-28 05:29:59 +0000182 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000183 diag::warn_second_parameter_of_va_start_not_last_named_argument);
184 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000185}
Chris Lattner30ce3442007-12-19 23:59:04 +0000186
Chris Lattner1b9a0792007-12-20 00:26:33 +0000187/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
188/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000189bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
190 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000191 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
192 << 0 /*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000193 if (TheCall->getNumArgs() > 2)
194 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000195 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000196 << 0 /*function call*/
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000197 << SourceRange(TheCall->getArg(2)->getLocStart(),
198 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner1b9a0792007-12-20 00:26:33 +0000199
Chris Lattner925e60d2007-12-28 05:29:59 +0000200 Expr *OrigArg0 = TheCall->getArg(0);
201 Expr *OrigArg1 = TheCall->getArg(1);
Chris Lattner1b9a0792007-12-20 00:26:33 +0000202
203 // Do standard promotions between the two arguments, returning their common
204 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000205 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Chris Lattner1b9a0792007-12-20 00:26:33 +0000206
207 // If the common type isn't a real floating type, then the arguments were
208 // invalid for this operation.
209 if (!Res->isRealFloatingType())
Chris Lattner925e60d2007-12-28 05:29:59 +0000210 return Diag(OrigArg0->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000211 diag::err_typecheck_call_invalid_ordered_compare)
Chris Lattnerd1625842008-11-24 06:25:27 +0000212 << OrigArg0->getType() << OrigArg1->getType()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000213 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
Chris Lattner1b9a0792007-12-20 00:26:33 +0000214
215 return false;
216}
217
Eli Friedman6cfda232008-05-20 08:23:37 +0000218bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) {
219 // The signature for these builtins is exact; the only thing we need
220 // to check is that the argument is a constant.
221 SourceLocation Loc;
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000222 if (!TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc))
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000223 return Diag(Loc, diag::err_stack_const_level) << TheCall->getSourceRange();
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000224
Eli Friedman6cfda232008-05-20 08:23:37 +0000225 return false;
226}
227
Eli Friedmand38617c2008-05-14 19:38:39 +0000228/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
229// This is declared to take (...), so we have to check everything.
Sebastian Redl0eb23302009-01-19 00:08:26 +0000230Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000231 if (TheCall->getNumArgs() < 3)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000232 return ExprError(Diag(TheCall->getLocEnd(),
233 diag::err_typecheck_call_too_few_args)
234 << 0 /*function call*/ << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000235
236 QualType FAType = TheCall->getArg(0)->getType();
237 QualType SAType = TheCall->getArg(1)->getType();
238
239 if (!FAType->isVectorType() || !SAType->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000240 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
241 << SourceRange(TheCall->getArg(0)->getLocStart(),
242 TheCall->getArg(1)->getLocEnd());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000243 return ExprError();
Eli Friedmand38617c2008-05-14 19:38:39 +0000244 }
245
Chris Lattnerb77792e2008-07-26 22:17:49 +0000246 if (Context.getCanonicalType(FAType).getUnqualifiedType() !=
247 Context.getCanonicalType(SAType).getUnqualifiedType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000248 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
249 << SourceRange(TheCall->getArg(0)->getLocStart(),
250 TheCall->getArg(1)->getLocEnd());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000251 return ExprError();
Eli Friedmand38617c2008-05-14 19:38:39 +0000252 }
253
254 unsigned numElements = FAType->getAsVectorType()->getNumElements();
255 if (TheCall->getNumArgs() != numElements+2) {
256 if (TheCall->getNumArgs() < numElements+2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000257 return ExprError(Diag(TheCall->getLocEnd(),
258 diag::err_typecheck_call_too_few_args)
259 << 0 /*function call*/ << TheCall->getSourceRange());
260 return ExprError(Diag(TheCall->getLocEnd(),
261 diag::err_typecheck_call_too_many_args)
262 << 0 /*function call*/ << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000263 }
264
265 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
266 llvm::APSInt Result(32);
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000267 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000268 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000269 diag::err_shufflevector_nonconstant_argument)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000270 << TheCall->getArg(i)->getSourceRange());
271
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000272 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000273 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000274 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000275 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000276 }
277
278 llvm::SmallVector<Expr*, 32> exprs;
279
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000280 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000281 exprs.push_back(TheCall->getArg(i));
282 TheCall->setArg(i, 0);
283 }
284
Ted Kremenek8189cde2009-02-07 01:47:29 +0000285 return Owned(new (Context) ShuffleVectorExpr(exprs.begin(), numElements+2,
286 FAType,
287 TheCall->getCallee()->getLocStart(),
288 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000289}
Chris Lattner30ce3442007-12-19 23:59:04 +0000290
Daniel Dunbar4493f792008-07-21 22:59:13 +0000291/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
292// This is declared to take (const void*, ...) and can take two
293// optional constant int args.
294bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000295 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000296
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000297 if (NumArgs > 3)
298 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000299 << 0 /*function call*/ << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000300
301 // Argument 0 is checked for us and the remaining arguments must be
302 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000303 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000304 Expr *Arg = TheCall->getArg(i);
305 QualType RWType = Arg->getType();
306
307 const BuiltinType *BT = RWType->getAsBuiltinType();
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000308 llvm::APSInt Result;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000309 if (!BT || BT->getKind() != BuiltinType::Int ||
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000310 !Arg->isIntegerConstantExpr(Result, Context))
311 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument)
312 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar4493f792008-07-21 22:59:13 +0000313
314 // FIXME: gcc issues a warning and rewrites these to 0. These
315 // seems especially odd for the third argument since the default
316 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000317 if (i == 1) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000318 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000319 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
320 << "0" << "1" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar4493f792008-07-21 22:59:13 +0000321 } else {
322 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000323 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
324 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar4493f792008-07-21 22:59:13 +0000325 }
326 }
327
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000328 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000329}
330
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000331/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
332/// int type). This simply type checks that type is one of the defined
333/// constants (0-3).
334bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
335 Expr *Arg = TheCall->getArg(1);
336 QualType ArgType = Arg->getType();
337 const BuiltinType *BT = ArgType->getAsBuiltinType();
338 llvm::APSInt Result(32);
339 if (!BT || BT->getKind() != BuiltinType::Int ||
340 !Arg->isIntegerConstantExpr(Result, Context)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000341 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
342 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000343 }
344
345 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000346 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
347 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000348 }
349
350 return false;
351}
352
Ted Kremenekd30ef872009-01-12 23:09:09 +0000353// Handle i > 1 ? "x" : "y", recursivelly
354bool Sema::SemaCheckStringLiteral(Expr *E, CallExpr *TheCall, bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000355 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenekd30ef872009-01-12 23:09:09 +0000356
357 switch (E->getStmtClass()) {
358 case Stmt::ConditionalOperatorClass: {
359 ConditionalOperator *C = cast<ConditionalOperator>(E);
360 return SemaCheckStringLiteral(C->getLHS(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000361 HasVAListArg, format_idx, firstDataArg)
Ted Kremenekd30ef872009-01-12 23:09:09 +0000362 && SemaCheckStringLiteral(C->getRHS(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000363 HasVAListArg, format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000364 }
365
366 case Stmt::ImplicitCastExprClass: {
367 ImplicitCastExpr *Expr = dyn_cast<ImplicitCastExpr>(E);
368 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000369 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000370 }
371
372 case Stmt::ParenExprClass: {
373 ParenExpr *Expr = dyn_cast<ParenExpr>(E);
374 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000375 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000376 }
377
378 default: {
379 ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E);
380 StringLiteral *StrE = NULL;
381
382 if (ObjCFExpr)
383 StrE = ObjCFExpr->getString();
384 else
385 StrE = dyn_cast<StringLiteral>(E);
386
387 if (StrE) {
Douglas Gregor3c385e52009-02-14 18:57:46 +0000388 CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx,
389 firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000390 return true;
391 }
392
393 return false;
394 }
395 }
396}
397
398
Chris Lattner59907c42007-08-10 20:18:51 +0000399/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Ted Kremenek71895b92007-08-14 17:39:48 +0000400/// correct use of format strings.
401///
402/// HasVAListArg - A predicate indicating whether the printf-like
403/// function is passed an explicit va_arg argument (e.g., vprintf)
404///
405/// format_idx - The index into Args for the format string.
406///
407/// Improper format strings to functions in the printf family can be
408/// the source of bizarre bugs and very serious security holes. A
409/// good source of information is available in the following paper
410/// (which includes additional references):
Chris Lattner59907c42007-08-10 20:18:51 +0000411///
412/// FormatGuard: Automatic Protection From printf Format String
413/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremenek71895b92007-08-14 17:39:48 +0000414///
415/// Functionality implemented:
416///
417/// We can statically check the following properties for string
418/// literal format strings for non v.*printf functions (where the
419/// arguments are passed directly):
420//
421/// (1) Are the number of format conversions equal to the number of
422/// data arguments?
423///
424/// (2) Does each format conversion correctly match the type of the
425/// corresponding data argument? (TODO)
426///
427/// Moreover, for all printf functions we can:
428///
429/// (3) Check for a missing format string (when not caught by type checking).
430///
431/// (4) Check for no-operation flags; e.g. using "#" with format
432/// conversion 'c' (TODO)
433///
434/// (5) Check the use of '%n', a major source of security holes.
435///
436/// (6) Check for malformed format conversions that don't specify anything.
437///
438/// (7) Check for empty format strings. e.g: printf("");
439///
440/// (8) Check that the format string is a wide literal.
441///
Ted Kremenek6d439592008-03-03 16:50:00 +0000442/// (9) Also check the arguments of functions with the __format__ attribute.
443/// (TODO).
444///
Ted Kremenek71895b92007-08-14 17:39:48 +0000445/// All of these checks can be done by parsing the format string.
446///
447/// For now, we ONLY do (1), (3), (5), (6), (7), and (8).
Chris Lattner59907c42007-08-10 20:18:51 +0000448void
Chris Lattner925e60d2007-12-28 05:29:59 +0000449Sema::CheckPrintfArguments(CallExpr *TheCall, bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000450 unsigned format_idx, unsigned firstDataArg) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000451 Expr *Fn = TheCall->getCallee();
452
Ted Kremenek71895b92007-08-14 17:39:48 +0000453 // CHECK: printf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +0000454 if (format_idx >= TheCall->getNumArgs()) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000455 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string)
456 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000457 return;
458 }
459
Chris Lattner56f34942008-02-13 01:02:39 +0000460 Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Chris Lattner459e8482007-08-25 05:36:18 +0000461
Chris Lattner59907c42007-08-10 20:18:51 +0000462 // CHECK: format string is not a string literal.
463 //
Ted Kremenek71895b92007-08-14 17:39:48 +0000464 // Dynamically generated format strings are difficult to
465 // automatically vet at compile time. Requiring that format strings
466 // are string literals: (1) permits the checking of format strings by
467 // the compiler and thereby (2) can practically remove the source of
468 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000469
470 // Format string can be either ObjC string (e.g. @"%d") or
471 // C string (e.g. "%d")
472 // ObjC string uses the same format specifiers as C string, so we can use
473 // the same format string checking logic for both ObjC and C strings.
Douglas Gregor3c385e52009-02-14 18:57:46 +0000474 bool isFExpr = SemaCheckStringLiteral(OrigFormatExpr, TheCall,
475 HasVAListArg, format_idx,
476 firstDataArg);
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000477
Ted Kremenekd30ef872009-01-12 23:09:09 +0000478 if (!isFExpr) {
Ted Kremenek4a336462007-12-17 19:03:13 +0000479 // For vprintf* functions (i.e., HasVAListArg==true), we add a
480 // special check to see if the format string is a function parameter
481 // of the function calling the printf function. If the function
482 // has an attribute indicating it is a printf-like function, then we
483 // should suppress warnings concerning non-literals being used in a call
484 // to a vprintf function. For example:
485 //
486 // void
487 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...) {
488 // va_list ap;
489 // va_start(ap, fmt);
490 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
491 // ...
492 //
493 //
494 // FIXME: We don't have full attribute support yet, so just check to see
495 // if the argument is a DeclRefExpr that references a parameter. We'll
496 // add proper support for checking the attribute later.
497 if (HasVAListArg)
Chris Lattner998568f2007-12-28 05:38:24 +0000498 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(OrigFormatExpr))
499 if (isa<ParmVarDecl>(DR->getDecl()))
Ted Kremenek4a336462007-12-17 19:03:13 +0000500 return;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000501
Chris Lattner925e60d2007-12-28 05:29:59 +0000502 Diag(TheCall->getArg(format_idx)->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000503 diag::warn_printf_not_string_constant)
504 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000505 return;
506 }
Ted Kremenekd30ef872009-01-12 23:09:09 +0000507}
Ted Kremenek71895b92007-08-14 17:39:48 +0000508
Ted Kremenekd30ef872009-01-12 23:09:09 +0000509void Sema::CheckPrintfString(StringLiteral *FExpr, Expr *OrigFormatExpr,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000510 CallExpr *TheCall, bool HasVAListArg, unsigned format_idx,
511 unsigned firstDataArg) {
Ted Kremenekd30ef872009-01-12 23:09:09 +0000512
513 ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(OrigFormatExpr);
Ted Kremenek71895b92007-08-14 17:39:48 +0000514 // CHECK: is the format string a wide literal?
515 if (FExpr->isWide()) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000516 Diag(FExpr->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000517 diag::warn_printf_format_string_is_wide_literal)
518 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000519 return;
520 }
521
522 // Str - The format string. NOTE: this is NOT null-terminated!
523 const char * const Str = FExpr->getStrData();
524
525 // CHECK: empty format string?
526 const unsigned StrLen = FExpr->getByteLength();
527
528 if (StrLen == 0) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000529 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string)
530 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000531 return;
532 }
533
534 // We process the format string using a binary state machine. The
535 // current state is stored in CurrentState.
536 enum {
537 state_OrdChr,
538 state_Conversion
539 } CurrentState = state_OrdChr;
540
541 // numConversions - The number of conversions seen so far. This is
542 // incremented as we traverse the format string.
543 unsigned numConversions = 0;
544
545 // numDataArgs - The number of data arguments after the format
546 // string. This can only be determined for non vprintf-like
547 // functions. For those functions, this value is 1 (the sole
548 // va_arg argument).
Douglas Gregor3c385e52009-02-14 18:57:46 +0000549 unsigned numDataArgs = TheCall->getNumArgs()-firstDataArg;
Ted Kremenek71895b92007-08-14 17:39:48 +0000550
551 // Inspect the format string.
552 unsigned StrIdx = 0;
553
554 // LastConversionIdx - Index within the format string where we last saw
555 // a '%' character that starts a new format conversion.
556 unsigned LastConversionIdx = 0;
557
Chris Lattner925e60d2007-12-28 05:29:59 +0000558 for (; StrIdx < StrLen; ++StrIdx) {
Chris Lattner998568f2007-12-28 05:38:24 +0000559
Ted Kremenek71895b92007-08-14 17:39:48 +0000560 // Is the number of detected conversion conversions greater than
561 // the number of matching data arguments? If so, stop.
562 if (!HasVAListArg && numConversions > numDataArgs) break;
563
564 // Handle "\0"
Chris Lattner925e60d2007-12-28 05:29:59 +0000565 if (Str[StrIdx] == '\0') {
Ted Kremenek71895b92007-08-14 17:39:48 +0000566 // The string returned by getStrData() is not null-terminated,
567 // so the presence of a null character is likely an error.
Chris Lattner998568f2007-12-28 05:38:24 +0000568 Diag(PP.AdvanceToTokenCharacter(FExpr->getLocStart(), StrIdx+1),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000569 diag::warn_printf_format_string_contains_null_char)
570 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000571 return;
572 }
573
574 // Ordinary characters (not processing a format conversion).
575 if (CurrentState == state_OrdChr) {
576 if (Str[StrIdx] == '%') {
577 CurrentState = state_Conversion;
578 LastConversionIdx = StrIdx;
579 }
580 continue;
581 }
582
583 // Seen '%'. Now processing a format conversion.
584 switch (Str[StrIdx]) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000585 // Handle dynamic precision or width specifier.
586 case '*': {
587 ++numConversions;
588
589 if (!HasVAListArg && numConversions > numDataArgs) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000590 SourceLocation Loc = FExpr->getLocStart();
591 Loc = PP.AdvanceToTokenCharacter(Loc, StrIdx+1);
Ted Kremenek580b6642007-10-12 20:51:52 +0000592
Ted Kremenek580b6642007-10-12 20:51:52 +0000593 if (Str[StrIdx-1] == '.')
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000594 Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg)
595 << OrigFormatExpr->getSourceRange();
Ted Kremenek580b6642007-10-12 20:51:52 +0000596 else
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000597 Diag(Loc, diag::warn_printf_asterisk_width_missing_arg)
598 << OrigFormatExpr->getSourceRange();
Ted Kremenek580b6642007-10-12 20:51:52 +0000599
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000600 // Don't do any more checking. We'll just emit spurious errors.
601 return;
Ted Kremenek580b6642007-10-12 20:51:52 +0000602 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000603
604 // Perform type checking on width/precision specifier.
605 Expr *E = TheCall->getArg(format_idx+numConversions);
606 if (const BuiltinType *BT = E->getType()->getAsBuiltinType())
607 if (BT->getKind() == BuiltinType::Int)
608 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000609
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000610 SourceLocation Loc =
611 PP.AdvanceToTokenCharacter(FExpr->getLocStart(), StrIdx+1);
612
613 if (Str[StrIdx-1] == '.')
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000614 Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000615 << E->getType() << E->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000616 else
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000617 Diag(Loc, diag::warn_printf_asterisk_width_wrong_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000618 << E->getType() << E->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000619
620 break;
621 }
622
623 // Characters which can terminate a format conversion
624 // (e.g. "%d"). Characters that specify length modifiers or
625 // other flags are handled by the default case below.
626 //
627 // FIXME: additional checks will go into the following cases.
628 case 'i':
629 case 'd':
630 case 'o':
631 case 'u':
632 case 'x':
633 case 'X':
634 case 'D':
635 case 'O':
636 case 'U':
637 case 'e':
638 case 'E':
639 case 'f':
640 case 'F':
641 case 'g':
642 case 'G':
643 case 'a':
644 case 'A':
645 case 'c':
646 case 'C':
647 case 'S':
648 case 's':
649 case 'p':
650 ++numConversions;
651 CurrentState = state_OrdChr;
652 break;
653
654 // CHECK: Are we using "%n"? Issue a warning.
655 case 'n': {
656 ++numConversions;
657 CurrentState = state_OrdChr;
658 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
659 LastConversionIdx+1);
660
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000661 Diag(Loc, diag::warn_printf_write_back)<<OrigFormatExpr->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000662 break;
663 }
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000664
665 // Handle "%@"
666 case '@':
667 // %@ is allowed in ObjC format strings only.
668 if(ObjCFExpr != NULL)
669 CurrentState = state_OrdChr;
670 else {
671 // Issue a warning: invalid format conversion.
672 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
673 LastConversionIdx+1);
674
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000675 Diag(Loc, diag::warn_printf_invalid_conversion)
676 << std::string(Str+LastConversionIdx,
677 Str+std::min(LastConversionIdx+2, StrLen))
678 << OrigFormatExpr->getSourceRange();
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000679 }
680 ++numConversions;
681 break;
682
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000683 // Handle "%%"
684 case '%':
685 // Sanity check: Was the first "%" character the previous one?
686 // If not, we will assume that we have a malformed format
687 // conversion, and that the current "%" character is the start
688 // of a new conversion.
689 if (StrIdx - LastConversionIdx == 1)
690 CurrentState = state_OrdChr;
691 else {
692 // Issue a warning: invalid format conversion.
Chris Lattner925e60d2007-12-28 05:29:59 +0000693 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
694 LastConversionIdx+1);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000695
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000696 Diag(Loc, diag::warn_printf_invalid_conversion)
697 << std::string(Str+LastConversionIdx, Str+StrIdx)
698 << OrigFormatExpr->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000699
700 // This conversion is broken. Advance to the next format
701 // conversion.
702 LastConversionIdx = StrIdx;
703 ++numConversions;
Ted Kremenek71895b92007-08-14 17:39:48 +0000704 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000705 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000706
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000707 default:
708 // This case catches all other characters: flags, widths, etc.
709 // We should eventually process those as well.
710 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000711 }
712 }
713
714 if (CurrentState == state_Conversion) {
715 // Issue a warning: invalid format conversion.
Chris Lattner925e60d2007-12-28 05:29:59 +0000716 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
717 LastConversionIdx+1);
Ted Kremenek71895b92007-08-14 17:39:48 +0000718
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000719 Diag(Loc, diag::warn_printf_invalid_conversion)
720 << std::string(Str+LastConversionIdx,
721 Str+std::min(LastConversionIdx+2, StrLen))
722 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000723 return;
724 }
725
726 if (!HasVAListArg) {
727 // CHECK: Does the number of format conversions exceed the number
728 // of data arguments?
729 if (numConversions > numDataArgs) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000730 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
731 LastConversionIdx);
Ted Kremenek71895b92007-08-14 17:39:48 +0000732
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000733 Diag(Loc, diag::warn_printf_insufficient_data_args)
734 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000735 }
736 // CHECK: Does the number of data arguments exceed the number of
737 // format conversions in the format string?
738 else if (numConversions < numDataArgs)
Chris Lattner925e60d2007-12-28 05:29:59 +0000739 Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000740 diag::warn_printf_too_many_data_args)
741 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000742 }
743}
Ted Kremenek06de2762007-08-17 16:46:58 +0000744
745//===--- CHECK: Return Address of Stack Variable --------------------------===//
746
747static DeclRefExpr* EvalVal(Expr *E);
748static DeclRefExpr* EvalAddr(Expr* E);
749
750/// CheckReturnStackAddr - Check if a return statement returns the address
751/// of a stack variable.
752void
753Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
754 SourceLocation ReturnLoc) {
Chris Lattner56f34942008-02-13 01:02:39 +0000755
Ted Kremenek06de2762007-08-17 16:46:58 +0000756 // Perform checking for returned stack addresses.
Steve Naroffdd972f22008-09-05 22:11:13 +0000757 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Ted Kremenek06de2762007-08-17 16:46:58 +0000758 if (DeclRefExpr *DR = EvalAddr(RetValExp))
Chris Lattner3c73c412008-11-19 08:23:25 +0000759 Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
Chris Lattner08631c52008-11-23 21:45:46 +0000760 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Steve Naroffc50a4a52008-09-16 22:25:10 +0000761
762 // Skip over implicit cast expressions when checking for block expressions.
763 if (ImplicitCastExpr *IcExpr =
764 dyn_cast_or_null<ImplicitCastExpr>(RetValExp))
765 RetValExp = IcExpr->getSubExpr();
766
Steve Naroff61f40a22008-09-10 19:17:48 +0000767 if (BlockExpr *C = dyn_cast_or_null<BlockExpr>(RetValExp))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000768 Diag(C->getLocStart(), diag::err_ret_local_block)
769 << C->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +0000770 }
771 // Perform checking for stack values returned by reference.
772 else if (lhsType->isReferenceType()) {
Douglas Gregor49badde2008-10-27 19:41:14 +0000773 // Check for a reference to the stack
774 if (DeclRefExpr *DR = EvalVal(RetValExp))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000775 Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
Chris Lattner08631c52008-11-23 21:45:46 +0000776 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +0000777 }
778}
779
780/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
781/// check if the expression in a return statement evaluates to an address
782/// to a location on the stack. The recursion is used to traverse the
783/// AST of the return expression, with recursion backtracking when we
784/// encounter a subexpression that (1) clearly does not lead to the address
785/// of a stack variable or (2) is something we cannot determine leads to
786/// the address of a stack variable based on such local checking.
787///
Ted Kremeneke8c600f2007-08-28 17:02:55 +0000788/// EvalAddr processes expressions that are pointers that are used as
789/// references (and not L-values). EvalVal handles all other values.
Ted Kremenek06de2762007-08-17 16:46:58 +0000790/// At the base case of the recursion is a check for a DeclRefExpr* in
791/// the refers to a stack variable.
792///
793/// This implementation handles:
794///
795/// * pointer-to-pointer casts
796/// * implicit conversions from array references to pointers
797/// * taking the address of fields
798/// * arbitrary interplay between "&" and "*" operators
799/// * pointer arithmetic from an address of a stack variable
800/// * taking the address of an array element where the array is on the stack
801static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek06de2762007-08-17 16:46:58 +0000802 // We should only be called for evaluating pointer expressions.
Steve Naroffdd972f22008-09-05 22:11:13 +0000803 assert((E->getType()->isPointerType() ||
804 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000805 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000806 "EvalAddr only works on pointers");
Ted Kremenek06de2762007-08-17 16:46:58 +0000807
808 // Our "symbolic interpreter" is just a dispatch off the currently
809 // viewed AST node. We then recursively traverse the AST by calling
810 // EvalAddr and EvalVal appropriately.
811 switch (E->getStmtClass()) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000812 case Stmt::ParenExprClass:
813 // Ignore parentheses.
814 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek06de2762007-08-17 16:46:58 +0000815
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000816 case Stmt::UnaryOperatorClass: {
817 // The only unary operator that make sense to handle here
818 // is AddrOf. All others don't make sense as pointers.
819 UnaryOperator *U = cast<UnaryOperator>(E);
Ted Kremenek06de2762007-08-17 16:46:58 +0000820
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000821 if (U->getOpcode() == UnaryOperator::AddrOf)
822 return EvalVal(U->getSubExpr());
823 else
Ted Kremenek06de2762007-08-17 16:46:58 +0000824 return NULL;
825 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000826
827 case Stmt::BinaryOperatorClass: {
828 // Handle pointer arithmetic. All other binary operators are not valid
829 // in this context.
830 BinaryOperator *B = cast<BinaryOperator>(E);
831 BinaryOperator::Opcode op = B->getOpcode();
832
833 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
834 return NULL;
835
836 Expr *Base = B->getLHS();
837
838 // Determine which argument is the real pointer base. It could be
839 // the RHS argument instead of the LHS.
840 if (!Base->getType()->isPointerType()) Base = B->getRHS();
841
842 assert (Base->getType()->isPointerType());
843 return EvalAddr(Base);
844 }
Steve Naroff61f40a22008-09-10 19:17:48 +0000845
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000846 // For conditional operators we need to see if either the LHS or RHS are
847 // valid DeclRefExpr*s. If one of them is valid, we return it.
848 case Stmt::ConditionalOperatorClass: {
849 ConditionalOperator *C = cast<ConditionalOperator>(E);
850
851 // Handle the GNU extension for missing LHS.
852 if (Expr *lhsExpr = C->getLHS())
853 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
854 return LHS;
855
856 return EvalAddr(C->getRHS());
857 }
858
Ted Kremenek54b52742008-08-07 00:49:01 +0000859 // For casts, we need to handle conversions from arrays to
860 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +0000861 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +0000862 case Stmt::CStyleCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +0000863 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +0000864 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +0000865 QualType T = SubExpr->getType();
866
Steve Naroffdd972f22008-09-05 22:11:13 +0000867 if (SubExpr->getType()->isPointerType() ||
868 SubExpr->getType()->isBlockPointerType() ||
869 SubExpr->getType()->isObjCQualifiedIdType())
Ted Kremenek54b52742008-08-07 00:49:01 +0000870 return EvalAddr(SubExpr);
871 else if (T->isArrayType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000872 return EvalVal(SubExpr);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000873 else
Ted Kremenek54b52742008-08-07 00:49:01 +0000874 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000875 }
876
877 // C++ casts. For dynamic casts, static casts, and const casts, we
878 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +0000879 // through the cast. In the case the dynamic cast doesn't fail (and
880 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000881 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +0000882 // FIXME: The comment about is wrong; we're not always converting
883 // from pointer to pointer. I'm guessing that this code should also
884 // handle references to objects.
885 case Stmt::CXXStaticCastExprClass:
886 case Stmt::CXXDynamicCastExprClass:
887 case Stmt::CXXConstCastExprClass:
888 case Stmt::CXXReinterpretCastExprClass: {
889 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +0000890 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000891 return EvalAddr(S);
892 else
893 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000894 }
895
896 // Everything else: we simply don't reason about them.
897 default:
898 return NULL;
899 }
Ted Kremenek06de2762007-08-17 16:46:58 +0000900}
901
902
903/// EvalVal - This function is complements EvalAddr in the mutual recursion.
904/// See the comments for EvalAddr for more details.
905static DeclRefExpr* EvalVal(Expr *E) {
906
Ted Kremeneke8c600f2007-08-28 17:02:55 +0000907 // We should only be called for evaluating non-pointer expressions, or
908 // expressions with a pointer type that are not used as references but instead
909 // are l-values (e.g., DeclRefExpr with a pointer type).
910
Ted Kremenek06de2762007-08-17 16:46:58 +0000911 // Our "symbolic interpreter" is just a dispatch off the currently
912 // viewed AST node. We then recursively traverse the AST by calling
913 // EvalAddr and EvalVal appropriately.
914 switch (E->getStmtClass()) {
Douglas Gregor1a49af92009-01-06 05:10:23 +0000915 case Stmt::DeclRefExprClass:
916 case Stmt::QualifiedDeclRefExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +0000917 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
918 // at code that refers to a variable's name. We check if it has local
919 // storage within the function, and if so, return the expression.
920 DeclRefExpr *DR = cast<DeclRefExpr>(E);
921
922 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000923 if(V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
Ted Kremenek06de2762007-08-17 16:46:58 +0000924
925 return NULL;
926 }
927
928 case Stmt::ParenExprClass:
929 // Ignore parentheses.
930 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
931
932 case Stmt::UnaryOperatorClass: {
933 // The only unary operator that make sense to handle here
934 // is Deref. All others don't resolve to a "name." This includes
935 // handling all sorts of rvalues passed to a unary operator.
936 UnaryOperator *U = cast<UnaryOperator>(E);
937
938 if (U->getOpcode() == UnaryOperator::Deref)
939 return EvalAddr(U->getSubExpr());
940
941 return NULL;
942 }
943
944 case Stmt::ArraySubscriptExprClass: {
945 // Array subscripts are potential references to data on the stack. We
946 // retrieve the DeclRefExpr* for the array variable if it indeed
947 // has local storage.
Ted Kremenek23245122007-08-20 16:18:38 +0000948 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek06de2762007-08-17 16:46:58 +0000949 }
950
951 case Stmt::ConditionalOperatorClass: {
952 // For conditional operators we need to see if either the LHS or RHS are
953 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
954 ConditionalOperator *C = cast<ConditionalOperator>(E);
955
Anders Carlsson39073232007-11-30 19:04:31 +0000956 // Handle the GNU extension for missing LHS.
957 if (Expr *lhsExpr = C->getLHS())
958 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
959 return LHS;
960
961 return EvalVal(C->getRHS());
Ted Kremenek06de2762007-08-17 16:46:58 +0000962 }
963
964 // Accesses to members are potential references to data on the stack.
965 case Stmt::MemberExprClass: {
966 MemberExpr *M = cast<MemberExpr>(E);
967
968 // Check for indirect access. We only want direct field accesses.
969 if (!M->isArrow())
970 return EvalVal(M->getBase());
971 else
972 return NULL;
973 }
974
975 // Everything else: we simply don't reason about them.
976 default:
977 return NULL;
978 }
979}
Ted Kremenek588e5eb2007-11-25 00:58:00 +0000980
981//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
982
983/// Check for comparisons of floating point operands using != and ==.
984/// Issue a warning if these are no self-comparisons, as they are not likely
985/// to do what the programmer intended.
986void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
987 bool EmitWarning = true;
988
Ted Kremenek4e99a5f2008-01-17 16:57:34 +0000989 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek32e97b62008-01-17 17:55:13 +0000990 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek588e5eb2007-11-25 00:58:00 +0000991
992 // Special case: check for x == x (which is OK).
993 // Do not emit warnings for such cases.
994 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
995 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
996 if (DRL->getDecl() == DRR->getDecl())
997 EmitWarning = false;
998
Ted Kremenek1b500bb2007-11-29 00:59:04 +0000999
1000 // Special case: check for comparisons against literals that can be exactly
1001 // represented by APFloat. In such cases, do not emit a warning. This
1002 // is a heuristic: often comparison against such literals are used to
1003 // detect if a value in a variable has not changed. This clearly can
1004 // lead to false negatives.
1005 if (EmitWarning) {
1006 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
1007 if (FLL->isExact())
1008 EmitWarning = false;
1009 }
1010 else
1011 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
1012 if (FLR->isExact())
1013 EmitWarning = false;
1014 }
1015 }
1016
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001017 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001018 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001019 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001020 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001021 EmitWarning = false;
1022
Sebastian Redl0eb23302009-01-19 00:08:26 +00001023 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001024 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001025 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001026 EmitWarning = false;
1027
1028 // Emit the diagnostic.
1029 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001030 Diag(loc, diag::warn_floatingpoint_eq)
1031 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001032}