blob: ff9d75302f7821917055eb31484468ca6988363f [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 +000021#include "clang/Basic/Diagnostic.h"
Ted Kremenek588e5eb2007-11-25 00:58:00 +000022#include "SemaUtil.h"
Chris Lattner59907c42007-08-10 20:18:51 +000023using namespace clang;
24
25/// CheckFunctionCall - Check a direct function call for various correctness
26/// and safety properties not strictly enforced by the C type system.
Eli Friedmand38617c2008-05-14 19:38:39 +000027Action::ExprResult
Eli Friedmane8018702008-05-16 17:51:27 +000028Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCallRaw) {
29 llvm::OwningPtr<CallExpr> TheCall(TheCallRaw);
Chris Lattner59907c42007-08-10 20:18:51 +000030 // Get the IdentifierInfo* for the called function.
31 IdentifierInfo *FnInfo = FDecl->getIdentifier();
Douglas Gregor2def4832008-11-17 20:34:05 +000032
33 // None of the checks below are needed for functions that don't have
34 // simple names (e.g., C++ conversion functions).
35 if (!FnInfo)
36 return TheCall.take();
37
Chris Lattner30ce3442007-12-19 23:59:04 +000038 switch (FnInfo->getBuiltinID()) {
39 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +000040 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +000041 "Wrong # arguments to builtin CFStringMakeConstantString");
Eli Friedmane8018702008-05-16 17:51:27 +000042 if (CheckBuiltinCFStringArgument(TheCall->getArg(0)))
Eli Friedmand38617c2008-05-14 19:38:39 +000043 return true;
Eli Friedmane8018702008-05-16 17:51:27 +000044 return TheCall.take();
Ted Kremenek49ff7a12008-07-09 17:58:53 +000045 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +000046 case Builtin::BI__builtin_va_start:
Chris Lattnerb7cfe882008-06-30 18:32:54 +000047 if (SemaBuiltinVAStart(TheCall.get()))
Eli Friedmand38617c2008-05-14 19:38:39 +000048 return true;
Eli Friedmane8018702008-05-16 17:51:27 +000049 return TheCall.take();
Chris Lattner1b9a0792007-12-20 00:26:33 +000050 case Builtin::BI__builtin_isgreater:
51 case Builtin::BI__builtin_isgreaterequal:
52 case Builtin::BI__builtin_isless:
53 case Builtin::BI__builtin_islessequal:
54 case Builtin::BI__builtin_islessgreater:
55 case Builtin::BI__builtin_isunordered:
Eli Friedmane8018702008-05-16 17:51:27 +000056 if (SemaBuiltinUnorderedCompare(TheCall.get()))
Eli Friedmand38617c2008-05-14 19:38:39 +000057 return true;
Eli Friedmane8018702008-05-16 17:51:27 +000058 return TheCall.take();
Eli Friedman6cfda232008-05-20 08:23:37 +000059 case Builtin::BI__builtin_return_address:
60 case Builtin::BI__builtin_frame_address:
61 if (SemaBuiltinStackAddress(TheCall.get()))
62 return true;
63 return TheCall.take();
Eli Friedmand38617c2008-05-14 19:38:39 +000064 case Builtin::BI__builtin_shufflevector:
Eli Friedmane8018702008-05-16 17:51:27 +000065 return SemaBuiltinShuffleVector(TheCall.get());
Daniel Dunbar4493f792008-07-21 22:59:13 +000066 case Builtin::BI__builtin_prefetch:
67 if (SemaBuiltinPrefetch(TheCall.get()))
68 return true;
69 return TheCall.take();
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +000070 case Builtin::BI__builtin_object_size:
71 if (SemaBuiltinObjectSize(TheCall.get()))
72 return true;
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 // Search the KnownFunctionIDs for the identifier.
80 unsigned i = 0, e = id_num_known_functions;
Ted Kremenek71895b92007-08-14 17:39:48 +000081 for (; i != e; ++i) { if (KnownFunctionIDs[i] == FnInfo) break; }
Eli Friedmane8018702008-05-16 17:51:27 +000082 if (i == e) return TheCall.take();
Chris Lattner59907c42007-08-10 20:18:51 +000083
84 // Printf checking.
85 if (i <= id_vprintf) {
Ted Kremenek71895b92007-08-14 17:39:48 +000086 // Retrieve the index of the format string parameter and determine
87 // if the function is passed a va_arg argument.
Chris Lattner59907c42007-08-10 20:18:51 +000088 unsigned format_idx = 0;
Ted Kremenek71895b92007-08-14 17:39:48 +000089 bool HasVAListArg = false;
90
Chris Lattner59907c42007-08-10 20:18:51 +000091 switch (i) {
Chris Lattner30ce3442007-12-19 23:59:04 +000092 default: assert(false && "No format string argument index.");
Daniel Dunbarde454282008-10-02 18:44:07 +000093 case id_NSLog: format_idx = 0; break;
94 case id_asprintf: format_idx = 1; break;
95 case id_fprintf: format_idx = 1; break;
96 case id_printf: format_idx = 0; break;
97 case id_snprintf: format_idx = 2; break;
98 case id_snprintf_chk: format_idx = 4; break;
99 case id_sprintf: format_idx = 1; break;
100 case id_sprintf_chk: format_idx = 3; break;
101 case id_vasprintf: format_idx = 1; HasVAListArg = true; break;
102 case id_vfprintf: format_idx = 1; HasVAListArg = true; break;
103 case id_vsnprintf: format_idx = 2; HasVAListArg = true; break;
104 case id_vsnprintf_chk: format_idx = 4; HasVAListArg = true; break;
105 case id_vsprintf: format_idx = 1; HasVAListArg = true; break;
106 case id_vsprintf_chk: format_idx = 3; HasVAListArg = true; break;
107 case id_vprintf: format_idx = 0; HasVAListArg = true; break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000108 }
109
Eli Friedmane8018702008-05-16 17:51:27 +0000110 CheckPrintfArguments(TheCall.get(), HasVAListArg, format_idx);
Chris Lattner59907c42007-08-10 20:18:51 +0000111 }
Anders Carlsson71993dd2007-08-17 05:31:46 +0000112
Eli Friedmane8018702008-05-16 17:51:27 +0000113 return TheCall.take();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000114}
115
116/// CheckBuiltinCFStringArgument - Checks that the argument to the builtin
117/// CFString constructor is correct
Chris Lattnercc6f65d2007-08-25 05:30:33 +0000118bool Sema::CheckBuiltinCFStringArgument(Expr* Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000119 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000120
121 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
122
123 if (!Literal || Literal->isWide()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000124 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
125 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000126 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000127 }
128
129 const char *Data = Literal->getStrData();
130 unsigned Length = Literal->getByteLength();
131
132 for (unsigned i = 0; i < Length; ++i) {
133 if (!isascii(Data[i])) {
134 Diag(PP.AdvanceToTokenCharacter(Arg->getLocStart(), i + 1),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000135 diag::warn_cfstring_literal_contains_non_ascii_character)
136 << Arg->getSourceRange();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000137 break;
138 }
139
140 if (!Data[i]) {
141 Diag(PP.AdvanceToTokenCharacter(Arg->getLocStart(), i + 1),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000142 diag::warn_cfstring_literal_contains_nul_character)
143 << Arg->getSourceRange();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000144 break;
145 }
146 }
147
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000148 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000149}
150
Chris Lattnerc27c6652007-12-20 00:05:45 +0000151/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
152/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000153bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
154 Expr *Fn = TheCall->getCallee();
155 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000156 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000157 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000158 << 0 /*function call*/ << Fn->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000159 << SourceRange(TheCall->getArg(2)->getLocStart(),
160 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000161 return true;
162 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000163
164 if (TheCall->getNumArgs() < 2) {
165 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
166 << 0 /*function call*/;
167 }
168
Chris Lattnerc27c6652007-12-20 00:05:45 +0000169 // Determine whether the current function is variadic or not.
170 bool isVariadic;
Eli Friedman56f20ae2008-12-15 22:05:35 +0000171 if (getCurFunctionDecl()) {
172 if (FunctionTypeProto* FTP =
173 dyn_cast<FunctionTypeProto>(getCurFunctionDecl()->getType()))
174 isVariadic = FTP->isVariadic();
175 else
176 isVariadic = false;
177 } else {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000178 isVariadic = getCurMethodDecl()->isVariadic();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000179 }
Chris Lattner30ce3442007-12-19 23:59:04 +0000180
Chris Lattnerc27c6652007-12-20 00:05:45 +0000181 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000182 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
183 return true;
184 }
185
186 // Verify that the second argument to the builtin is the last argument of the
187 // current function or method.
188 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000189 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Anders Carlsson88cf2262008-02-11 04:20:54 +0000190
191 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
192 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000193 // FIXME: This isn't correct for methods (results in bogus warning).
194 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000195 const ParmVarDecl *LastArg;
Chris Lattner371f2582008-12-04 23:50:19 +0000196 if (FunctionDecl *FD = getCurFunctionDecl())
197 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000198 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000199 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000200 SecondArgIsLastNamedArgument = PV == LastArg;
201 }
202 }
203
204 if (!SecondArgIsLastNamedArgument)
Chris Lattner925e60d2007-12-28 05:29:59 +0000205 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000206 diag::warn_second_parameter_of_va_start_not_last_named_argument);
207 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000208}
Chris Lattner30ce3442007-12-19 23:59:04 +0000209
Chris Lattner1b9a0792007-12-20 00:26:33 +0000210/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
211/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000212bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
213 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000214 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
215 << 0 /*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000216 if (TheCall->getNumArgs() > 2)
217 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000218 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000219 << 0 /*function call*/
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000220 << SourceRange(TheCall->getArg(2)->getLocStart(),
221 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner1b9a0792007-12-20 00:26:33 +0000222
Chris Lattner925e60d2007-12-28 05:29:59 +0000223 Expr *OrigArg0 = TheCall->getArg(0);
224 Expr *OrigArg1 = TheCall->getArg(1);
Chris Lattner1b9a0792007-12-20 00:26:33 +0000225
226 // Do standard promotions between the two arguments, returning their common
227 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000228 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Chris Lattner1b9a0792007-12-20 00:26:33 +0000229
230 // If the common type isn't a real floating type, then the arguments were
231 // invalid for this operation.
232 if (!Res->isRealFloatingType())
Chris Lattner925e60d2007-12-28 05:29:59 +0000233 return Diag(OrigArg0->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000234 diag::err_typecheck_call_invalid_ordered_compare)
Chris Lattnerd1625842008-11-24 06:25:27 +0000235 << OrigArg0->getType() << OrigArg1->getType()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000236 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
Chris Lattner1b9a0792007-12-20 00:26:33 +0000237
238 return false;
239}
240
Eli Friedman6cfda232008-05-20 08:23:37 +0000241bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) {
242 // The signature for these builtins is exact; the only thing we need
243 // to check is that the argument is a constant.
244 SourceLocation Loc;
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000245 if (!TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc))
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000246 return Diag(Loc, diag::err_stack_const_level) << TheCall->getSourceRange();
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000247
Eli Friedman6cfda232008-05-20 08:23:37 +0000248 return false;
249}
250
Eli Friedmand38617c2008-05-14 19:38:39 +0000251/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
252// This is declared to take (...), so we have to check everything.
253Action::ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
254 if (TheCall->getNumArgs() < 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000255 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000256 << 0 /*function call*/ << TheCall->getSourceRange();
Eli Friedmand38617c2008-05-14 19:38:39 +0000257
258 QualType FAType = TheCall->getArg(0)->getType();
259 QualType SAType = TheCall->getArg(1)->getType();
260
261 if (!FAType->isVectorType() || !SAType->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000262 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
263 << SourceRange(TheCall->getArg(0)->getLocStart(),
264 TheCall->getArg(1)->getLocEnd());
Eli Friedmand38617c2008-05-14 19:38:39 +0000265 return true;
266 }
267
Chris Lattnerb77792e2008-07-26 22:17:49 +0000268 if (Context.getCanonicalType(FAType).getUnqualifiedType() !=
269 Context.getCanonicalType(SAType).getUnqualifiedType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000270 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
271 << SourceRange(TheCall->getArg(0)->getLocStart(),
272 TheCall->getArg(1)->getLocEnd());
Eli Friedmand38617c2008-05-14 19:38:39 +0000273 return true;
274 }
275
276 unsigned numElements = FAType->getAsVectorType()->getNumElements();
277 if (TheCall->getNumArgs() != numElements+2) {
278 if (TheCall->getNumArgs() < numElements+2)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000279 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000280 << 0 /*function call*/ << TheCall->getSourceRange();
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000281 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000282 << 0 /*function call*/ << TheCall->getSourceRange();
Eli Friedmand38617c2008-05-14 19:38:39 +0000283 }
284
285 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
286 llvm::APSInt Result(32);
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000287 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
288 return Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000289 diag::err_shufflevector_nonconstant_argument)
290 << TheCall->getArg(i)->getSourceRange();
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000291
292 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
293 return Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000294 diag::err_shufflevector_argument_too_large)
295 << TheCall->getArg(i)->getSourceRange();
Eli Friedmand38617c2008-05-14 19:38:39 +0000296 }
297
298 llvm::SmallVector<Expr*, 32> exprs;
299
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000300 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000301 exprs.push_back(TheCall->getArg(i));
302 TheCall->setArg(i, 0);
303 }
304
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000305 return new ShuffleVectorExpr(exprs.begin(), numElements+2, FAType,
306 TheCall->getCallee()->getLocStart(),
307 TheCall->getRParenLoc());
Eli Friedmand38617c2008-05-14 19:38:39 +0000308}
Chris Lattner30ce3442007-12-19 23:59:04 +0000309
Daniel Dunbar4493f792008-07-21 22:59:13 +0000310/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
311// This is declared to take (const void*, ...) and can take two
312// optional constant int args.
313bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000314 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000315
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000316 if (NumArgs > 3)
317 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000318 << 0 /*function call*/ << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000319
320 // Argument 0 is checked for us and the remaining arguments must be
321 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000322 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000323 Expr *Arg = TheCall->getArg(i);
324 QualType RWType = Arg->getType();
325
326 const BuiltinType *BT = RWType->getAsBuiltinType();
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000327 llvm::APSInt Result;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000328 if (!BT || BT->getKind() != BuiltinType::Int ||
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000329 !Arg->isIntegerConstantExpr(Result, Context))
330 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument)
331 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar4493f792008-07-21 22:59:13 +0000332
333 // FIXME: gcc issues a warning and rewrites these to 0. These
334 // seems especially odd for the third argument since the default
335 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000336 if (i == 1) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000337 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000338 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
339 << "0" << "1" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar4493f792008-07-21 22:59:13 +0000340 } else {
341 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000342 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
343 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar4493f792008-07-21 22:59:13 +0000344 }
345 }
346
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000347 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000348}
349
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000350/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
351/// int type). This simply type checks that type is one of the defined
352/// constants (0-3).
353bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
354 Expr *Arg = TheCall->getArg(1);
355 QualType ArgType = Arg->getType();
356 const BuiltinType *BT = ArgType->getAsBuiltinType();
357 llvm::APSInt Result(32);
358 if (!BT || BT->getKind() != BuiltinType::Int ||
359 !Arg->isIntegerConstantExpr(Result, Context)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000360 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
361 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000362 }
363
364 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000365 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
366 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000367 }
368
369 return false;
370}
371
Ted Kremenekd30ef872009-01-12 23:09:09 +0000372// Handle i > 1 ? "x" : "y", recursivelly
373bool Sema::SemaCheckStringLiteral(Expr *E, CallExpr *TheCall, bool HasVAListArg,
374 unsigned format_idx) {
375
376 switch (E->getStmtClass()) {
377 case Stmt::ConditionalOperatorClass: {
378 ConditionalOperator *C = cast<ConditionalOperator>(E);
379 return SemaCheckStringLiteral(C->getLHS(), TheCall,
380 HasVAListArg, format_idx)
381 && SemaCheckStringLiteral(C->getRHS(), TheCall,
382 HasVAListArg, format_idx);
383 }
384
385 case Stmt::ImplicitCastExprClass: {
386 ImplicitCastExpr *Expr = dyn_cast<ImplicitCastExpr>(E);
387 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
388 format_idx);
389 }
390
391 case Stmt::ParenExprClass: {
392 ParenExpr *Expr = dyn_cast<ParenExpr>(E);
393 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
394 format_idx);
395 }
396
397 default: {
398 ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E);
399 StringLiteral *StrE = NULL;
400
401 if (ObjCFExpr)
402 StrE = ObjCFExpr->getString();
403 else
404 StrE = dyn_cast<StringLiteral>(E);
405
406 if (StrE) {
407 CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx);
408 return true;
409 }
410
411 return false;
412 }
413 }
414}
415
416
Chris Lattner59907c42007-08-10 20:18:51 +0000417/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Ted Kremenek71895b92007-08-14 17:39:48 +0000418/// correct use of format strings.
419///
420/// HasVAListArg - A predicate indicating whether the printf-like
421/// function is passed an explicit va_arg argument (e.g., vprintf)
422///
423/// format_idx - The index into Args for the format string.
424///
425/// Improper format strings to functions in the printf family can be
426/// the source of bizarre bugs and very serious security holes. A
427/// good source of information is available in the following paper
428/// (which includes additional references):
Chris Lattner59907c42007-08-10 20:18:51 +0000429///
430/// FormatGuard: Automatic Protection From printf Format String
431/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremenek71895b92007-08-14 17:39:48 +0000432///
433/// Functionality implemented:
434///
435/// We can statically check the following properties for string
436/// literal format strings for non v.*printf functions (where the
437/// arguments are passed directly):
438//
439/// (1) Are the number of format conversions equal to the number of
440/// data arguments?
441///
442/// (2) Does each format conversion correctly match the type of the
443/// corresponding data argument? (TODO)
444///
445/// Moreover, for all printf functions we can:
446///
447/// (3) Check for a missing format string (when not caught by type checking).
448///
449/// (4) Check for no-operation flags; e.g. using "#" with format
450/// conversion 'c' (TODO)
451///
452/// (5) Check the use of '%n', a major source of security holes.
453///
454/// (6) Check for malformed format conversions that don't specify anything.
455///
456/// (7) Check for empty format strings. e.g: printf("");
457///
458/// (8) Check that the format string is a wide literal.
459///
Ted Kremenek6d439592008-03-03 16:50:00 +0000460/// (9) Also check the arguments of functions with the __format__ attribute.
461/// (TODO).
462///
Ted Kremenek71895b92007-08-14 17:39:48 +0000463/// All of these checks can be done by parsing the format string.
464///
465/// For now, we ONLY do (1), (3), (5), (6), (7), and (8).
Chris Lattner59907c42007-08-10 20:18:51 +0000466void
Chris Lattner925e60d2007-12-28 05:29:59 +0000467Sema::CheckPrintfArguments(CallExpr *TheCall, bool HasVAListArg,
468 unsigned format_idx) {
469 Expr *Fn = TheCall->getCallee();
470
Ted Kremenek71895b92007-08-14 17:39:48 +0000471 // CHECK: printf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +0000472 if (format_idx >= TheCall->getNumArgs()) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000473 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string)
474 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000475 return;
476 }
477
Chris Lattner56f34942008-02-13 01:02:39 +0000478 Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Chris Lattner459e8482007-08-25 05:36:18 +0000479
Chris Lattner59907c42007-08-10 20:18:51 +0000480 // CHECK: format string is not a string literal.
481 //
Ted Kremenek71895b92007-08-14 17:39:48 +0000482 // Dynamically generated format strings are difficult to
483 // automatically vet at compile time. Requiring that format strings
484 // are string literals: (1) permits the checking of format strings by
485 // the compiler and thereby (2) can practically remove the source of
486 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000487
488 // Format string can be either ObjC string (e.g. @"%d") or
489 // C string (e.g. "%d")
490 // ObjC string uses the same format specifiers as C string, so we can use
491 // the same format string checking logic for both ObjC and C strings.
Ted Kremenekd30ef872009-01-12 23:09:09 +0000492 bool isFExpr = SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx);
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000493
Ted Kremenekd30ef872009-01-12 23:09:09 +0000494 if (!isFExpr) {
Ted Kremenek4a336462007-12-17 19:03:13 +0000495 // For vprintf* functions (i.e., HasVAListArg==true), we add a
496 // special check to see if the format string is a function parameter
497 // of the function calling the printf function. If the function
498 // has an attribute indicating it is a printf-like function, then we
499 // should suppress warnings concerning non-literals being used in a call
500 // to a vprintf function. For example:
501 //
502 // void
503 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...) {
504 // va_list ap;
505 // va_start(ap, fmt);
506 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
507 // ...
508 //
509 //
510 // FIXME: We don't have full attribute support yet, so just check to see
511 // if the argument is a DeclRefExpr that references a parameter. We'll
512 // add proper support for checking the attribute later.
513 if (HasVAListArg)
Chris Lattner998568f2007-12-28 05:38:24 +0000514 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(OrigFormatExpr))
515 if (isa<ParmVarDecl>(DR->getDecl()))
Ted Kremenek4a336462007-12-17 19:03:13 +0000516 return;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000517
Chris Lattner925e60d2007-12-28 05:29:59 +0000518 Diag(TheCall->getArg(format_idx)->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000519 diag::warn_printf_not_string_constant)
520 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000521 return;
522 }
Ted Kremenekd30ef872009-01-12 23:09:09 +0000523}
Ted Kremenek71895b92007-08-14 17:39:48 +0000524
Ted Kremenekd30ef872009-01-12 23:09:09 +0000525void Sema::CheckPrintfString(StringLiteral *FExpr, Expr *OrigFormatExpr,
526 CallExpr *TheCall, bool HasVAListArg, unsigned format_idx) {
527
528 ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(OrigFormatExpr);
Ted Kremenek71895b92007-08-14 17:39:48 +0000529 // CHECK: is the format string a wide literal?
530 if (FExpr->isWide()) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000531 Diag(FExpr->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000532 diag::warn_printf_format_string_is_wide_literal)
533 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000534 return;
535 }
536
537 // Str - The format string. NOTE: this is NOT null-terminated!
538 const char * const Str = FExpr->getStrData();
539
540 // CHECK: empty format string?
541 const unsigned StrLen = FExpr->getByteLength();
542
543 if (StrLen == 0) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000544 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string)
545 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000546 return;
547 }
548
549 // We process the format string using a binary state machine. The
550 // current state is stored in CurrentState.
551 enum {
552 state_OrdChr,
553 state_Conversion
554 } CurrentState = state_OrdChr;
555
556 // numConversions - The number of conversions seen so far. This is
557 // incremented as we traverse the format string.
558 unsigned numConversions = 0;
559
560 // numDataArgs - The number of data arguments after the format
561 // string. This can only be determined for non vprintf-like
562 // functions. For those functions, this value is 1 (the sole
563 // va_arg argument).
Chris Lattner925e60d2007-12-28 05:29:59 +0000564 unsigned numDataArgs = TheCall->getNumArgs()-(format_idx+1);
Ted Kremenek71895b92007-08-14 17:39:48 +0000565
566 // Inspect the format string.
567 unsigned StrIdx = 0;
568
569 // LastConversionIdx - Index within the format string where we last saw
570 // a '%' character that starts a new format conversion.
571 unsigned LastConversionIdx = 0;
572
Chris Lattner925e60d2007-12-28 05:29:59 +0000573 for (; StrIdx < StrLen; ++StrIdx) {
Chris Lattner998568f2007-12-28 05:38:24 +0000574
Ted Kremenek71895b92007-08-14 17:39:48 +0000575 // Is the number of detected conversion conversions greater than
576 // the number of matching data arguments? If so, stop.
577 if (!HasVAListArg && numConversions > numDataArgs) break;
578
579 // Handle "\0"
Chris Lattner925e60d2007-12-28 05:29:59 +0000580 if (Str[StrIdx] == '\0') {
Ted Kremenek71895b92007-08-14 17:39:48 +0000581 // The string returned by getStrData() is not null-terminated,
582 // so the presence of a null character is likely an error.
Chris Lattner998568f2007-12-28 05:38:24 +0000583 Diag(PP.AdvanceToTokenCharacter(FExpr->getLocStart(), StrIdx+1),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000584 diag::warn_printf_format_string_contains_null_char)
585 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000586 return;
587 }
588
589 // Ordinary characters (not processing a format conversion).
590 if (CurrentState == state_OrdChr) {
591 if (Str[StrIdx] == '%') {
592 CurrentState = state_Conversion;
593 LastConversionIdx = StrIdx;
594 }
595 continue;
596 }
597
598 // Seen '%'. Now processing a format conversion.
599 switch (Str[StrIdx]) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000600 // Handle dynamic precision or width specifier.
601 case '*': {
602 ++numConversions;
603
604 if (!HasVAListArg && numConversions > numDataArgs) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000605 SourceLocation Loc = FExpr->getLocStart();
606 Loc = PP.AdvanceToTokenCharacter(Loc, StrIdx+1);
Ted Kremenek580b6642007-10-12 20:51:52 +0000607
Ted Kremenek580b6642007-10-12 20:51:52 +0000608 if (Str[StrIdx-1] == '.')
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000609 Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg)
610 << OrigFormatExpr->getSourceRange();
Ted Kremenek580b6642007-10-12 20:51:52 +0000611 else
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000612 Diag(Loc, diag::warn_printf_asterisk_width_missing_arg)
613 << OrigFormatExpr->getSourceRange();
Ted Kremenek580b6642007-10-12 20:51:52 +0000614
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000615 // Don't do any more checking. We'll just emit spurious errors.
616 return;
Ted Kremenek580b6642007-10-12 20:51:52 +0000617 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000618
619 // Perform type checking on width/precision specifier.
620 Expr *E = TheCall->getArg(format_idx+numConversions);
621 if (const BuiltinType *BT = E->getType()->getAsBuiltinType())
622 if (BT->getKind() == BuiltinType::Int)
623 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000624
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000625 SourceLocation Loc =
626 PP.AdvanceToTokenCharacter(FExpr->getLocStart(), StrIdx+1);
627
628 if (Str[StrIdx-1] == '.')
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000629 Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000630 << E->getType() << E->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000631 else
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000632 Diag(Loc, diag::warn_printf_asterisk_width_wrong_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000633 << E->getType() << E->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000634
635 break;
636 }
637
638 // Characters which can terminate a format conversion
639 // (e.g. "%d"). Characters that specify length modifiers or
640 // other flags are handled by the default case below.
641 //
642 // FIXME: additional checks will go into the following cases.
643 case 'i':
644 case 'd':
645 case 'o':
646 case 'u':
647 case 'x':
648 case 'X':
649 case 'D':
650 case 'O':
651 case 'U':
652 case 'e':
653 case 'E':
654 case 'f':
655 case 'F':
656 case 'g':
657 case 'G':
658 case 'a':
659 case 'A':
660 case 'c':
661 case 'C':
662 case 'S':
663 case 's':
664 case 'p':
665 ++numConversions;
666 CurrentState = state_OrdChr;
667 break;
668
669 // CHECK: Are we using "%n"? Issue a warning.
670 case 'n': {
671 ++numConversions;
672 CurrentState = state_OrdChr;
673 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
674 LastConversionIdx+1);
675
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000676 Diag(Loc, diag::warn_printf_write_back)<<OrigFormatExpr->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000677 break;
678 }
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000679
680 // Handle "%@"
681 case '@':
682 // %@ is allowed in ObjC format strings only.
683 if(ObjCFExpr != NULL)
684 CurrentState = state_OrdChr;
685 else {
686 // Issue a warning: invalid format conversion.
687 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
688 LastConversionIdx+1);
689
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000690 Diag(Loc, diag::warn_printf_invalid_conversion)
691 << std::string(Str+LastConversionIdx,
692 Str+std::min(LastConversionIdx+2, StrLen))
693 << OrigFormatExpr->getSourceRange();
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000694 }
695 ++numConversions;
696 break;
697
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000698 // Handle "%%"
699 case '%':
700 // Sanity check: Was the first "%" character the previous one?
701 // If not, we will assume that we have a malformed format
702 // conversion, and that the current "%" character is the start
703 // of a new conversion.
704 if (StrIdx - LastConversionIdx == 1)
705 CurrentState = state_OrdChr;
706 else {
707 // Issue a warning: invalid format conversion.
Chris Lattner925e60d2007-12-28 05:29:59 +0000708 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
709 LastConversionIdx+1);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000710
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000711 Diag(Loc, diag::warn_printf_invalid_conversion)
712 << std::string(Str+LastConversionIdx, Str+StrIdx)
713 << OrigFormatExpr->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000714
715 // This conversion is broken. Advance to the next format
716 // conversion.
717 LastConversionIdx = StrIdx;
718 ++numConversions;
Ted Kremenek71895b92007-08-14 17:39:48 +0000719 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000720 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000721
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000722 default:
723 // This case catches all other characters: flags, widths, etc.
724 // We should eventually process those as well.
725 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000726 }
727 }
728
729 if (CurrentState == state_Conversion) {
730 // Issue a warning: invalid format conversion.
Chris Lattner925e60d2007-12-28 05:29:59 +0000731 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
732 LastConversionIdx+1);
Ted Kremenek71895b92007-08-14 17:39:48 +0000733
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000734 Diag(Loc, diag::warn_printf_invalid_conversion)
735 << std::string(Str+LastConversionIdx,
736 Str+std::min(LastConversionIdx+2, StrLen))
737 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000738 return;
739 }
740
741 if (!HasVAListArg) {
742 // CHECK: Does the number of format conversions exceed the number
743 // of data arguments?
744 if (numConversions > numDataArgs) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000745 SourceLocation Loc = PP.AdvanceToTokenCharacter(FExpr->getLocStart(),
746 LastConversionIdx);
Ted Kremenek71895b92007-08-14 17:39:48 +0000747
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000748 Diag(Loc, diag::warn_printf_insufficient_data_args)
749 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000750 }
751 // CHECK: Does the number of data arguments exceed the number of
752 // format conversions in the format string?
753 else if (numConversions < numDataArgs)
Chris Lattner925e60d2007-12-28 05:29:59 +0000754 Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000755 diag::warn_printf_too_many_data_args)
756 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000757 }
758}
Ted Kremenek06de2762007-08-17 16:46:58 +0000759
760//===--- CHECK: Return Address of Stack Variable --------------------------===//
761
762static DeclRefExpr* EvalVal(Expr *E);
763static DeclRefExpr* EvalAddr(Expr* E);
764
765/// CheckReturnStackAddr - Check if a return statement returns the address
766/// of a stack variable.
767void
768Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
769 SourceLocation ReturnLoc) {
Chris Lattner56f34942008-02-13 01:02:39 +0000770
Ted Kremenek06de2762007-08-17 16:46:58 +0000771 // Perform checking for returned stack addresses.
Steve Naroffdd972f22008-09-05 22:11:13 +0000772 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Ted Kremenek06de2762007-08-17 16:46:58 +0000773 if (DeclRefExpr *DR = EvalAddr(RetValExp))
Chris Lattner3c73c412008-11-19 08:23:25 +0000774 Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
Chris Lattner08631c52008-11-23 21:45:46 +0000775 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Steve Naroffc50a4a52008-09-16 22:25:10 +0000776
777 // Skip over implicit cast expressions when checking for block expressions.
778 if (ImplicitCastExpr *IcExpr =
779 dyn_cast_or_null<ImplicitCastExpr>(RetValExp))
780 RetValExp = IcExpr->getSubExpr();
781
Steve Naroff61f40a22008-09-10 19:17:48 +0000782 if (BlockExpr *C = dyn_cast_or_null<BlockExpr>(RetValExp))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000783 Diag(C->getLocStart(), diag::err_ret_local_block)
784 << C->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +0000785 }
786 // Perform checking for stack values returned by reference.
787 else if (lhsType->isReferenceType()) {
Douglas Gregor49badde2008-10-27 19:41:14 +0000788 // Check for a reference to the stack
789 if (DeclRefExpr *DR = EvalVal(RetValExp))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000790 Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
Chris Lattner08631c52008-11-23 21:45:46 +0000791 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +0000792 }
793}
794
795/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
796/// check if the expression in a return statement evaluates to an address
797/// to a location on the stack. The recursion is used to traverse the
798/// AST of the return expression, with recursion backtracking when we
799/// encounter a subexpression that (1) clearly does not lead to the address
800/// of a stack variable or (2) is something we cannot determine leads to
801/// the address of a stack variable based on such local checking.
802///
Ted Kremeneke8c600f2007-08-28 17:02:55 +0000803/// EvalAddr processes expressions that are pointers that are used as
804/// references (and not L-values). EvalVal handles all other values.
Ted Kremenek06de2762007-08-17 16:46:58 +0000805/// At the base case of the recursion is a check for a DeclRefExpr* in
806/// the refers to a stack variable.
807///
808/// This implementation handles:
809///
810/// * pointer-to-pointer casts
811/// * implicit conversions from array references to pointers
812/// * taking the address of fields
813/// * arbitrary interplay between "&" and "*" operators
814/// * pointer arithmetic from an address of a stack variable
815/// * taking the address of an array element where the array is on the stack
816static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek06de2762007-08-17 16:46:58 +0000817 // We should only be called for evaluating pointer expressions.
Steve Naroffdd972f22008-09-05 22:11:13 +0000818 assert((E->getType()->isPointerType() ||
819 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000820 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000821 "EvalAddr only works on pointers");
Ted Kremenek06de2762007-08-17 16:46:58 +0000822
823 // Our "symbolic interpreter" is just a dispatch off the currently
824 // viewed AST node. We then recursively traverse the AST by calling
825 // EvalAddr and EvalVal appropriately.
826 switch (E->getStmtClass()) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000827 case Stmt::ParenExprClass:
828 // Ignore parentheses.
829 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek06de2762007-08-17 16:46:58 +0000830
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000831 case Stmt::UnaryOperatorClass: {
832 // The only unary operator that make sense to handle here
833 // is AddrOf. All others don't make sense as pointers.
834 UnaryOperator *U = cast<UnaryOperator>(E);
Ted Kremenek06de2762007-08-17 16:46:58 +0000835
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000836 if (U->getOpcode() == UnaryOperator::AddrOf)
837 return EvalVal(U->getSubExpr());
838 else
Ted Kremenek06de2762007-08-17 16:46:58 +0000839 return NULL;
840 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000841
842 case Stmt::BinaryOperatorClass: {
843 // Handle pointer arithmetic. All other binary operators are not valid
844 // in this context.
845 BinaryOperator *B = cast<BinaryOperator>(E);
846 BinaryOperator::Opcode op = B->getOpcode();
847
848 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
849 return NULL;
850
851 Expr *Base = B->getLHS();
852
853 // Determine which argument is the real pointer base. It could be
854 // the RHS argument instead of the LHS.
855 if (!Base->getType()->isPointerType()) Base = B->getRHS();
856
857 assert (Base->getType()->isPointerType());
858 return EvalAddr(Base);
859 }
Steve Naroff61f40a22008-09-10 19:17:48 +0000860
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000861 // For conditional operators we need to see if either the LHS or RHS are
862 // valid DeclRefExpr*s. If one of them is valid, we return it.
863 case Stmt::ConditionalOperatorClass: {
864 ConditionalOperator *C = cast<ConditionalOperator>(E);
865
866 // Handle the GNU extension for missing LHS.
867 if (Expr *lhsExpr = C->getLHS())
868 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
869 return LHS;
870
871 return EvalAddr(C->getRHS());
872 }
873
Ted Kremenek54b52742008-08-07 00:49:01 +0000874 // For casts, we need to handle conversions from arrays to
875 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +0000876 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +0000877 case Stmt::CStyleCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +0000878 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +0000879 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +0000880 QualType T = SubExpr->getType();
881
Steve Naroffdd972f22008-09-05 22:11:13 +0000882 if (SubExpr->getType()->isPointerType() ||
883 SubExpr->getType()->isBlockPointerType() ||
884 SubExpr->getType()->isObjCQualifiedIdType())
Ted Kremenek54b52742008-08-07 00:49:01 +0000885 return EvalAddr(SubExpr);
886 else if (T->isArrayType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000887 return EvalVal(SubExpr);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000888 else
Ted Kremenek54b52742008-08-07 00:49:01 +0000889 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000890 }
891
892 // C++ casts. For dynamic casts, static casts, and const casts, we
893 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +0000894 // through the cast. In the case the dynamic cast doesn't fail (and
895 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000896 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +0000897 // FIXME: The comment about is wrong; we're not always converting
898 // from pointer to pointer. I'm guessing that this code should also
899 // handle references to objects.
900 case Stmt::CXXStaticCastExprClass:
901 case Stmt::CXXDynamicCastExprClass:
902 case Stmt::CXXConstCastExprClass:
903 case Stmt::CXXReinterpretCastExprClass: {
904 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +0000905 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000906 return EvalAddr(S);
907 else
908 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000909 }
910
911 // Everything else: we simply don't reason about them.
912 default:
913 return NULL;
914 }
Ted Kremenek06de2762007-08-17 16:46:58 +0000915}
916
917
918/// EvalVal - This function is complements EvalAddr in the mutual recursion.
919/// See the comments for EvalAddr for more details.
920static DeclRefExpr* EvalVal(Expr *E) {
921
Ted Kremeneke8c600f2007-08-28 17:02:55 +0000922 // We should only be called for evaluating non-pointer expressions, or
923 // expressions with a pointer type that are not used as references but instead
924 // are l-values (e.g., DeclRefExpr with a pointer type).
925
Ted Kremenek06de2762007-08-17 16:46:58 +0000926 // Our "symbolic interpreter" is just a dispatch off the currently
927 // viewed AST node. We then recursively traverse the AST by calling
928 // EvalAddr and EvalVal appropriately.
929 switch (E->getStmtClass()) {
Douglas Gregor1a49af92009-01-06 05:10:23 +0000930 case Stmt::DeclRefExprClass:
931 case Stmt::QualifiedDeclRefExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +0000932 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
933 // at code that refers to a variable's name. We check if it has local
934 // storage within the function, and if so, return the expression.
935 DeclRefExpr *DR = cast<DeclRefExpr>(E);
936
937 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000938 if(V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
Ted Kremenek06de2762007-08-17 16:46:58 +0000939
940 return NULL;
941 }
942
943 case Stmt::ParenExprClass:
944 // Ignore parentheses.
945 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
946
947 case Stmt::UnaryOperatorClass: {
948 // The only unary operator that make sense to handle here
949 // is Deref. All others don't resolve to a "name." This includes
950 // handling all sorts of rvalues passed to a unary operator.
951 UnaryOperator *U = cast<UnaryOperator>(E);
952
953 if (U->getOpcode() == UnaryOperator::Deref)
954 return EvalAddr(U->getSubExpr());
955
956 return NULL;
957 }
958
959 case Stmt::ArraySubscriptExprClass: {
960 // Array subscripts are potential references to data on the stack. We
961 // retrieve the DeclRefExpr* for the array variable if it indeed
962 // has local storage.
Ted Kremenek23245122007-08-20 16:18:38 +0000963 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek06de2762007-08-17 16:46:58 +0000964 }
965
966 case Stmt::ConditionalOperatorClass: {
967 // For conditional operators we need to see if either the LHS or RHS are
968 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
969 ConditionalOperator *C = cast<ConditionalOperator>(E);
970
Anders Carlsson39073232007-11-30 19:04:31 +0000971 // Handle the GNU extension for missing LHS.
972 if (Expr *lhsExpr = C->getLHS())
973 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
974 return LHS;
975
976 return EvalVal(C->getRHS());
Ted Kremenek06de2762007-08-17 16:46:58 +0000977 }
978
979 // Accesses to members are potential references to data on the stack.
980 case Stmt::MemberExprClass: {
981 MemberExpr *M = cast<MemberExpr>(E);
982
983 // Check for indirect access. We only want direct field accesses.
984 if (!M->isArrow())
985 return EvalVal(M->getBase());
986 else
987 return NULL;
988 }
989
990 // Everything else: we simply don't reason about them.
991 default:
992 return NULL;
993 }
994}
Ted Kremenek588e5eb2007-11-25 00:58:00 +0000995
996//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
997
998/// Check for comparisons of floating point operands using != and ==.
999/// Issue a warning if these are no self-comparisons, as they are not likely
1000/// to do what the programmer intended.
1001void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
1002 bool EmitWarning = true;
1003
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00001004 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek32e97b62008-01-17 17:55:13 +00001005 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001006
1007 // Special case: check for x == x (which is OK).
1008 // Do not emit warnings for such cases.
1009 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
1010 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
1011 if (DRL->getDecl() == DRR->getDecl())
1012 EmitWarning = false;
1013
Ted Kremenek1b500bb2007-11-29 00:59:04 +00001014
1015 // Special case: check for comparisons against literals that can be exactly
1016 // represented by APFloat. In such cases, do not emit a warning. This
1017 // is a heuristic: often comparison against such literals are used to
1018 // detect if a value in a variable has not changed. This clearly can
1019 // lead to false negatives.
1020 if (EmitWarning) {
1021 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
1022 if (FLL->isExact())
1023 EmitWarning = false;
1024 }
1025 else
1026 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
1027 if (FLR->isExact())
1028 EmitWarning = false;
1029 }
1030 }
1031
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001032 // Check for comparisons with builtin types.
1033 if (EmitWarning)
1034 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
1035 if (isCallBuiltin(CL))
1036 EmitWarning = false;
1037
1038 if (EmitWarning)
1039 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
1040 if (isCallBuiltin(CR))
1041 EmitWarning = false;
1042
1043 // Emit the diagnostic.
1044 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001045 Diag(loc, diag::warn_floatingpoint_eq)
1046 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001047}