blob: 38cc427a0044a0777aadd0aeb440cb1343e64c63 [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
Chris Lattner60800082009-02-18 17:49:48 +000023/// getLocationOfStringLiteralByte - Return a source location that points to the
24/// specified byte of the specified string literal.
25///
26/// Strings are amazingly complex. They can be formed from multiple tokens and
27/// can have escape sequences in them in addition to the usual trigraph and
28/// escaped newline business. This routine handles this complexity.
29///
30SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
31 unsigned ByteNo) const {
32 assert(!SL->isWide() && "This doesn't work for wide strings yet");
33
Chris Lattnerd0d082f2009-02-18 18:34:12 +000034 llvm::SmallString<32> SpellingBuffer;
35
Chris Lattner60800082009-02-18 17:49:48 +000036 // Loop over all of the tokens in this string until we find the one that
37 // contains the byte we're looking for.
38 unsigned TokNo = 0;
39 while (1) {
40 assert(TokNo < SL->getNumConcatenated() && "Invalid byte number!");
41 SourceLocation StrTokLoc = SL->getStrTokenLoc(TokNo);
42
43 // Get the spelling of the string so that we can get the data that makes up
44 // the string literal, not the identifier for the macro it is potentially
45 // expanded through.
46 SourceLocation StrTokSpellingLoc = SourceMgr.getSpellingLoc(StrTokLoc);
47
48 // Re-lex the token to get its length and original spelling.
49 std::pair<FileID, unsigned> LocInfo =
50 SourceMgr.getDecomposedLoc(StrTokSpellingLoc);
51 std::pair<const char *,const char *> Buffer =
52 SourceMgr.getBufferData(LocInfo.first);
53 const char *StrData = Buffer.first+LocInfo.second;
54
55 // Create a langops struct and enable trigraphs. This is sufficient for
56 // relexing tokens.
57 LangOptions LangOpts;
58 LangOpts.Trigraphs = true;
59
60 // Create a lexer starting at the beginning of this token.
61 Lexer TheLexer(StrTokSpellingLoc, LangOpts, Buffer.first, StrData,
62 Buffer.second);
63 Token TheTok;
64 TheLexer.LexFromRawLexer(TheTok);
65
Chris Lattner0150cdf2009-02-18 18:40:20 +000066 // We generally care about the length of the token, which is known by the
67 // lexer as long as we don't need to clean it (trigraphs/newlines).
68 unsigned TokNumBytes;
69 if (!TheTok.needsCleaning()) {
70 TokNumBytes = TheTok.getLength();
71 } else {
72 // Get the spelling of the token to remove trigraphs and escaped newlines.
73 SpellingBuffer.resize(TheTok.getLength());
74 const char *SpellingPtr = &SpellingBuffer[0];
75 TokNumBytes = PP.getSpelling(TheTok, SpellingPtr);
76 }
Chris Lattnerd0d082f2009-02-18 18:34:12 +000077
Chris Lattner60800082009-02-18 17:49:48 +000078 // The length of the string is the token length minus the two quotes.
Chris Lattner0150cdf2009-02-18 18:40:20 +000079 TokNumBytes -= 2;
Chris Lattner2197c962009-02-18 18:52:52 +000080
Chris Lattner60800082009-02-18 17:49:48 +000081 // FIXME: This should consider character escapes!
Chris Lattner2197c962009-02-18 18:52:52 +000082
83 // If the byte is in this token, return the location of the byte.
Chris Lattner60800082009-02-18 17:49:48 +000084 if (ByteNo < TokNumBytes ||
85 (ByteNo == TokNumBytes && TokNo == SL->getNumConcatenated())) {
Chris Lattner60800082009-02-18 17:49:48 +000086 // We advance +1 to step over the '"'.
87 return PP.AdvanceToTokenCharacter(StrTokLoc, ByteNo+1);
88 }
89
90 // Move to the next string token.
91 ++TokNo;
92 ByteNo -= TokNumBytes;
93 }
94}
95
96
Chris Lattner59907c42007-08-10 20:18:51 +000097/// CheckFunctionCall - Check a direct function call for various correctness
98/// and safety properties not strictly enforced by the C type system.
Sebastian Redl0eb23302009-01-19 00:08:26 +000099Action::OwningExprResult
100Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
101 OwningExprResult TheCallResult(Owned(TheCall));
Chris Lattner59907c42007-08-10 20:18:51 +0000102 // Get the IdentifierInfo* for the called function.
103 IdentifierInfo *FnInfo = FDecl->getIdentifier();
Douglas Gregor2def4832008-11-17 20:34:05 +0000104
105 // None of the checks below are needed for functions that don't have
106 // simple names (e.g., C++ conversion functions).
107 if (!FnInfo)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000108 return move(TheCallResult);
Douglas Gregor2def4832008-11-17 20:34:05 +0000109
Douglas Gregor3c385e52009-02-14 18:57:46 +0000110 switch (FDecl->getBuiltinID(Context)) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000111 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000112 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000113 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000114 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000115 return ExprError();
116 return move(TheCallResult);
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000117 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000118 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000119 if (SemaBuiltinVAStart(TheCall))
120 return ExprError();
121 return move(TheCallResult);
Chris Lattner1b9a0792007-12-20 00:26:33 +0000122 case Builtin::BI__builtin_isgreater:
123 case Builtin::BI__builtin_isgreaterequal:
124 case Builtin::BI__builtin_isless:
125 case Builtin::BI__builtin_islessequal:
126 case Builtin::BI__builtin_islessgreater:
127 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000128 if (SemaBuiltinUnorderedCompare(TheCall))
129 return ExprError();
130 return move(TheCallResult);
Eli Friedman6cfda232008-05-20 08:23:37 +0000131 case Builtin::BI__builtin_return_address:
132 case Builtin::BI__builtin_frame_address:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000133 if (SemaBuiltinStackAddress(TheCall))
134 return ExprError();
135 return move(TheCallResult);
Eli Friedmand38617c2008-05-14 19:38:39 +0000136 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000137 return SemaBuiltinShuffleVector(TheCall);
138 // TheCall will be freed by the smart pointer here, but that's fine, since
139 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000140 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000141 if (SemaBuiltinPrefetch(TheCall))
142 return ExprError();
143 return move(TheCallResult);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000144 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000145 if (SemaBuiltinObjectSize(TheCall))
146 return ExprError();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000147 }
Daniel Dunbarde454282008-10-02 18:44:07 +0000148
149 // FIXME: This mechanism should be abstracted to be less fragile and
150 // more efficient. For example, just map function ids to custom
151 // handlers.
152
Chris Lattner59907c42007-08-10 20:18:51 +0000153 // Printf checking.
Douglas Gregor3c385e52009-02-14 18:57:46 +0000154 if (const FormatAttr *Format = FDecl->getAttr<FormatAttr>()) {
155 if (Format->getType() == "printf") {
156 bool HasVAListArg = false;
157 if (const FunctionTypeProto *Proto
158 = FDecl->getType()->getAsFunctionTypeProto())
159 HasVAListArg = !Proto->isVariadic();
160 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
161 Format->getFirstArg() - 1);
162 }
Chris Lattner59907c42007-08-10 20:18:51 +0000163 }
Sebastian Redl0eb23302009-01-19 00:08:26 +0000164
165 return move(TheCallResult);
Anders Carlsson71993dd2007-08-17 05:31:46 +0000166}
167
Chris Lattner69039812009-02-18 06:01:06 +0000168/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000169/// CFString constructor is correct
Chris Lattner69039812009-02-18 06:01:06 +0000170bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000171 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000172 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
173
174 if (!Literal || Literal->isWide()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000175 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
176 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000177 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000178 }
179
180 const char *Data = Literal->getStrData();
181 unsigned Length = Literal->getByteLength();
182
183 for (unsigned i = 0; i < Length; ++i) {
184 if (!isascii(Data[i])) {
Chris Lattner60800082009-02-18 17:49:48 +0000185 Diag(getLocationOfStringLiteralByte(Literal, i),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000186 diag::warn_cfstring_literal_contains_non_ascii_character)
187 << Arg->getSourceRange();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000188 break;
189 }
190
191 if (!Data[i]) {
Chris Lattner60800082009-02-18 17:49:48 +0000192 Diag(getLocationOfStringLiteralByte(Literal, i),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000193 diag::warn_cfstring_literal_contains_nul_character)
194 << Arg->getSourceRange();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000195 break;
196 }
197 }
198
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000199 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000200}
201
Chris Lattnerc27c6652007-12-20 00:05:45 +0000202/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
203/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000204bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
205 Expr *Fn = TheCall->getCallee();
206 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000207 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000208 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000209 << 0 /*function call*/ << Fn->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000210 << SourceRange(TheCall->getArg(2)->getLocStart(),
211 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000212 return true;
213 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000214
215 if (TheCall->getNumArgs() < 2) {
216 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
217 << 0 /*function call*/;
218 }
219
Chris Lattnerc27c6652007-12-20 00:05:45 +0000220 // Determine whether the current function is variadic or not.
221 bool isVariadic;
Eli Friedman56f20ae2008-12-15 22:05:35 +0000222 if (getCurFunctionDecl()) {
223 if (FunctionTypeProto* FTP =
224 dyn_cast<FunctionTypeProto>(getCurFunctionDecl()->getType()))
225 isVariadic = FTP->isVariadic();
226 else
227 isVariadic = false;
228 } else {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000229 isVariadic = getCurMethodDecl()->isVariadic();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000230 }
Chris Lattner30ce3442007-12-19 23:59:04 +0000231
Chris Lattnerc27c6652007-12-20 00:05:45 +0000232 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000233 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
234 return true;
235 }
236
237 // Verify that the second argument to the builtin is the last argument of the
238 // current function or method.
239 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000240 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Anders Carlsson88cf2262008-02-11 04:20:54 +0000241
242 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
243 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000244 // FIXME: This isn't correct for methods (results in bogus warning).
245 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000246 const ParmVarDecl *LastArg;
Chris Lattner371f2582008-12-04 23:50:19 +0000247 if (FunctionDecl *FD = getCurFunctionDecl())
248 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000249 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000250 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000251 SecondArgIsLastNamedArgument = PV == LastArg;
252 }
253 }
254
255 if (!SecondArgIsLastNamedArgument)
Chris Lattner925e60d2007-12-28 05:29:59 +0000256 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000257 diag::warn_second_parameter_of_va_start_not_last_named_argument);
258 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000259}
Chris Lattner30ce3442007-12-19 23:59:04 +0000260
Chris Lattner1b9a0792007-12-20 00:26:33 +0000261/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
262/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000263bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
264 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000265 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
266 << 0 /*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000267 if (TheCall->getNumArgs() > 2)
268 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000269 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000270 << 0 /*function call*/
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000271 << SourceRange(TheCall->getArg(2)->getLocStart(),
272 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner1b9a0792007-12-20 00:26:33 +0000273
Chris Lattner925e60d2007-12-28 05:29:59 +0000274 Expr *OrigArg0 = TheCall->getArg(0);
275 Expr *OrigArg1 = TheCall->getArg(1);
Chris Lattner1b9a0792007-12-20 00:26:33 +0000276
277 // Do standard promotions between the two arguments, returning their common
278 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000279 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Chris Lattner1b9a0792007-12-20 00:26:33 +0000280
281 // If the common type isn't a real floating type, then the arguments were
282 // invalid for this operation.
283 if (!Res->isRealFloatingType())
Chris Lattner925e60d2007-12-28 05:29:59 +0000284 return Diag(OrigArg0->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000285 diag::err_typecheck_call_invalid_ordered_compare)
Chris Lattnerd1625842008-11-24 06:25:27 +0000286 << OrigArg0->getType() << OrigArg1->getType()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000287 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
Chris Lattner1b9a0792007-12-20 00:26:33 +0000288
289 return false;
290}
291
Eli Friedman6cfda232008-05-20 08:23:37 +0000292bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) {
293 // The signature for these builtins is exact; the only thing we need
294 // to check is that the argument is a constant.
295 SourceLocation Loc;
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000296 if (!TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc))
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000297 return Diag(Loc, diag::err_stack_const_level) << TheCall->getSourceRange();
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000298
Eli Friedman6cfda232008-05-20 08:23:37 +0000299 return false;
300}
301
Eli Friedmand38617c2008-05-14 19:38:39 +0000302/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
303// This is declared to take (...), so we have to check everything.
Sebastian Redl0eb23302009-01-19 00:08:26 +0000304Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000305 if (TheCall->getNumArgs() < 3)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000306 return ExprError(Diag(TheCall->getLocEnd(),
307 diag::err_typecheck_call_too_few_args)
308 << 0 /*function call*/ << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000309
310 QualType FAType = TheCall->getArg(0)->getType();
311 QualType SAType = TheCall->getArg(1)->getType();
312
313 if (!FAType->isVectorType() || !SAType->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000314 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
315 << SourceRange(TheCall->getArg(0)->getLocStart(),
316 TheCall->getArg(1)->getLocEnd());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000317 return ExprError();
Eli Friedmand38617c2008-05-14 19:38:39 +0000318 }
319
Chris Lattnerb77792e2008-07-26 22:17:49 +0000320 if (Context.getCanonicalType(FAType).getUnqualifiedType() !=
321 Context.getCanonicalType(SAType).getUnqualifiedType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000322 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
323 << SourceRange(TheCall->getArg(0)->getLocStart(),
324 TheCall->getArg(1)->getLocEnd());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000325 return ExprError();
Eli Friedmand38617c2008-05-14 19:38:39 +0000326 }
327
328 unsigned numElements = FAType->getAsVectorType()->getNumElements();
329 if (TheCall->getNumArgs() != numElements+2) {
330 if (TheCall->getNumArgs() < numElements+2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000331 return ExprError(Diag(TheCall->getLocEnd(),
332 diag::err_typecheck_call_too_few_args)
333 << 0 /*function call*/ << TheCall->getSourceRange());
334 return ExprError(Diag(TheCall->getLocEnd(),
335 diag::err_typecheck_call_too_many_args)
336 << 0 /*function call*/ << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000337 }
338
339 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
340 llvm::APSInt Result(32);
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000341 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000342 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000343 diag::err_shufflevector_nonconstant_argument)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000344 << TheCall->getArg(i)->getSourceRange());
345
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000346 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000347 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000348 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000349 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000350 }
351
352 llvm::SmallVector<Expr*, 32> exprs;
353
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000354 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000355 exprs.push_back(TheCall->getArg(i));
356 TheCall->setArg(i, 0);
357 }
358
Ted Kremenek8189cde2009-02-07 01:47:29 +0000359 return Owned(new (Context) ShuffleVectorExpr(exprs.begin(), numElements+2,
360 FAType,
361 TheCall->getCallee()->getLocStart(),
362 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000363}
Chris Lattner30ce3442007-12-19 23:59:04 +0000364
Daniel Dunbar4493f792008-07-21 22:59:13 +0000365/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
366// This is declared to take (const void*, ...) and can take two
367// optional constant int args.
368bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000369 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000370
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000371 if (NumArgs > 3)
372 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000373 << 0 /*function call*/ << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000374
375 // Argument 0 is checked for us and the remaining arguments must be
376 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000377 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000378 Expr *Arg = TheCall->getArg(i);
379 QualType RWType = Arg->getType();
380
381 const BuiltinType *BT = RWType->getAsBuiltinType();
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000382 llvm::APSInt Result;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000383 if (!BT || BT->getKind() != BuiltinType::Int ||
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000384 !Arg->isIntegerConstantExpr(Result, Context))
385 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument)
386 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar4493f792008-07-21 22:59:13 +0000387
388 // FIXME: gcc issues a warning and rewrites these to 0. These
389 // seems especially odd for the third argument since the default
390 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000391 if (i == 1) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000392 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000393 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
394 << "0" << "1" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar4493f792008-07-21 22:59:13 +0000395 } else {
396 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000397 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
398 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar4493f792008-07-21 22:59:13 +0000399 }
400 }
401
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000402 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000403}
404
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000405/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
406/// int type). This simply type checks that type is one of the defined
407/// constants (0-3).
408bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
409 Expr *Arg = TheCall->getArg(1);
410 QualType ArgType = Arg->getType();
411 const BuiltinType *BT = ArgType->getAsBuiltinType();
412 llvm::APSInt Result(32);
413 if (!BT || BT->getKind() != BuiltinType::Int ||
414 !Arg->isIntegerConstantExpr(Result, Context)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000415 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
416 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000417 }
418
419 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000420 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
421 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000422 }
423
424 return false;
425}
426
Ted Kremenekd30ef872009-01-12 23:09:09 +0000427// Handle i > 1 ? "x" : "y", recursivelly
428bool Sema::SemaCheckStringLiteral(Expr *E, CallExpr *TheCall, bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000429 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenekd30ef872009-01-12 23:09:09 +0000430
431 switch (E->getStmtClass()) {
432 case Stmt::ConditionalOperatorClass: {
433 ConditionalOperator *C = cast<ConditionalOperator>(E);
434 return SemaCheckStringLiteral(C->getLHS(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000435 HasVAListArg, format_idx, firstDataArg)
Ted Kremenekd30ef872009-01-12 23:09:09 +0000436 && SemaCheckStringLiteral(C->getRHS(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000437 HasVAListArg, format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000438 }
439
440 case Stmt::ImplicitCastExprClass: {
441 ImplicitCastExpr *Expr = dyn_cast<ImplicitCastExpr>(E);
442 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000443 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000444 }
445
446 case Stmt::ParenExprClass: {
447 ParenExpr *Expr = dyn_cast<ParenExpr>(E);
448 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000449 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000450 }
451
452 default: {
453 ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E);
454 StringLiteral *StrE = NULL;
455
456 if (ObjCFExpr)
457 StrE = ObjCFExpr->getString();
458 else
459 StrE = dyn_cast<StringLiteral>(E);
460
461 if (StrE) {
Douglas Gregor3c385e52009-02-14 18:57:46 +0000462 CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx,
463 firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000464 return true;
465 }
466
467 return false;
468 }
469 }
470}
471
472
Chris Lattner59907c42007-08-10 20:18:51 +0000473/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Ted Kremenek71895b92007-08-14 17:39:48 +0000474/// correct use of format strings.
475///
476/// HasVAListArg - A predicate indicating whether the printf-like
477/// function is passed an explicit va_arg argument (e.g., vprintf)
478///
479/// format_idx - The index into Args for the format string.
480///
481/// Improper format strings to functions in the printf family can be
482/// the source of bizarre bugs and very serious security holes. A
483/// good source of information is available in the following paper
484/// (which includes additional references):
Chris Lattner59907c42007-08-10 20:18:51 +0000485///
486/// FormatGuard: Automatic Protection From printf Format String
487/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremenek71895b92007-08-14 17:39:48 +0000488///
489/// Functionality implemented:
490///
491/// We can statically check the following properties for string
492/// literal format strings for non v.*printf functions (where the
493/// arguments are passed directly):
494//
495/// (1) Are the number of format conversions equal to the number of
496/// data arguments?
497///
498/// (2) Does each format conversion correctly match the type of the
499/// corresponding data argument? (TODO)
500///
501/// Moreover, for all printf functions we can:
502///
503/// (3) Check for a missing format string (when not caught by type checking).
504///
505/// (4) Check for no-operation flags; e.g. using "#" with format
506/// conversion 'c' (TODO)
507///
508/// (5) Check the use of '%n', a major source of security holes.
509///
510/// (6) Check for malformed format conversions that don't specify anything.
511///
512/// (7) Check for empty format strings. e.g: printf("");
513///
514/// (8) Check that the format string is a wide literal.
515///
Ted Kremenek6d439592008-03-03 16:50:00 +0000516/// (9) Also check the arguments of functions with the __format__ attribute.
517/// (TODO).
518///
Ted Kremenek71895b92007-08-14 17:39:48 +0000519/// All of these checks can be done by parsing the format string.
520///
521/// For now, we ONLY do (1), (3), (5), (6), (7), and (8).
Chris Lattner59907c42007-08-10 20:18:51 +0000522void
Chris Lattner925e60d2007-12-28 05:29:59 +0000523Sema::CheckPrintfArguments(CallExpr *TheCall, bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000524 unsigned format_idx, unsigned firstDataArg) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000525 Expr *Fn = TheCall->getCallee();
526
Ted Kremenek71895b92007-08-14 17:39:48 +0000527 // CHECK: printf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +0000528 if (format_idx >= TheCall->getNumArgs()) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000529 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string)
530 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000531 return;
532 }
533
Chris Lattner56f34942008-02-13 01:02:39 +0000534 Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Chris Lattner459e8482007-08-25 05:36:18 +0000535
Chris Lattner59907c42007-08-10 20:18:51 +0000536 // CHECK: format string is not a string literal.
537 //
Ted Kremenek71895b92007-08-14 17:39:48 +0000538 // Dynamically generated format strings are difficult to
539 // automatically vet at compile time. Requiring that format strings
540 // are string literals: (1) permits the checking of format strings by
541 // the compiler and thereby (2) can practically remove the source of
542 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000543
544 // Format string can be either ObjC string (e.g. @"%d") or
545 // C string (e.g. "%d")
546 // ObjC string uses the same format specifiers as C string, so we can use
547 // the same format string checking logic for both ObjC and C strings.
Douglas Gregor3c385e52009-02-14 18:57:46 +0000548 bool isFExpr = SemaCheckStringLiteral(OrigFormatExpr, TheCall,
549 HasVAListArg, format_idx,
550 firstDataArg);
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000551
Ted Kremenekd30ef872009-01-12 23:09:09 +0000552 if (!isFExpr) {
Ted Kremenek4a336462007-12-17 19:03:13 +0000553 // For vprintf* functions (i.e., HasVAListArg==true), we add a
554 // special check to see if the format string is a function parameter
555 // of the function calling the printf function. If the function
556 // has an attribute indicating it is a printf-like function, then we
557 // should suppress warnings concerning non-literals being used in a call
558 // to a vprintf function. For example:
559 //
560 // void
561 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...) {
562 // va_list ap;
563 // va_start(ap, fmt);
564 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
565 // ...
566 //
567 //
568 // FIXME: We don't have full attribute support yet, so just check to see
569 // if the argument is a DeclRefExpr that references a parameter. We'll
570 // add proper support for checking the attribute later.
571 if (HasVAListArg)
Chris Lattner998568f2007-12-28 05:38:24 +0000572 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(OrigFormatExpr))
573 if (isa<ParmVarDecl>(DR->getDecl()))
Ted Kremenek4a336462007-12-17 19:03:13 +0000574 return;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000575
Chris Lattner925e60d2007-12-28 05:29:59 +0000576 Diag(TheCall->getArg(format_idx)->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000577 diag::warn_printf_not_string_constant)
578 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000579 return;
580 }
Ted Kremenekd30ef872009-01-12 23:09:09 +0000581}
Ted Kremenek71895b92007-08-14 17:39:48 +0000582
Ted Kremenekd30ef872009-01-12 23:09:09 +0000583void Sema::CheckPrintfString(StringLiteral *FExpr, Expr *OrigFormatExpr,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000584 CallExpr *TheCall, bool HasVAListArg, unsigned format_idx,
585 unsigned firstDataArg) {
Ted Kremenekd30ef872009-01-12 23:09:09 +0000586
587 ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(OrigFormatExpr);
Ted Kremenek71895b92007-08-14 17:39:48 +0000588 // CHECK: is the format string a wide literal?
589 if (FExpr->isWide()) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000590 Diag(FExpr->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000591 diag::warn_printf_format_string_is_wide_literal)
592 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000593 return;
594 }
595
596 // Str - The format string. NOTE: this is NOT null-terminated!
597 const char * const Str = FExpr->getStrData();
598
599 // CHECK: empty format string?
600 const unsigned StrLen = FExpr->getByteLength();
601
602 if (StrLen == 0) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000603 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string)
604 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000605 return;
606 }
607
608 // We process the format string using a binary state machine. The
609 // current state is stored in CurrentState.
610 enum {
611 state_OrdChr,
612 state_Conversion
613 } CurrentState = state_OrdChr;
614
615 // numConversions - The number of conversions seen so far. This is
616 // incremented as we traverse the format string.
617 unsigned numConversions = 0;
618
619 // numDataArgs - The number of data arguments after the format
620 // string. This can only be determined for non vprintf-like
621 // functions. For those functions, this value is 1 (the sole
622 // va_arg argument).
Douglas Gregor3c385e52009-02-14 18:57:46 +0000623 unsigned numDataArgs = TheCall->getNumArgs()-firstDataArg;
Ted Kremenek71895b92007-08-14 17:39:48 +0000624
625 // Inspect the format string.
626 unsigned StrIdx = 0;
627
628 // LastConversionIdx - Index within the format string where we last saw
629 // a '%' character that starts a new format conversion.
630 unsigned LastConversionIdx = 0;
631
Chris Lattner925e60d2007-12-28 05:29:59 +0000632 for (; StrIdx < StrLen; ++StrIdx) {
Chris Lattner998568f2007-12-28 05:38:24 +0000633
Ted Kremenek71895b92007-08-14 17:39:48 +0000634 // Is the number of detected conversion conversions greater than
635 // the number of matching data arguments? If so, stop.
636 if (!HasVAListArg && numConversions > numDataArgs) break;
637
638 // Handle "\0"
Chris Lattner925e60d2007-12-28 05:29:59 +0000639 if (Str[StrIdx] == '\0') {
Ted Kremenek71895b92007-08-14 17:39:48 +0000640 // The string returned by getStrData() is not null-terminated,
641 // so the presence of a null character is likely an error.
Chris Lattner60800082009-02-18 17:49:48 +0000642 Diag(getLocationOfStringLiteralByte(FExpr, StrIdx),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000643 diag::warn_printf_format_string_contains_null_char)
644 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000645 return;
646 }
647
648 // Ordinary characters (not processing a format conversion).
649 if (CurrentState == state_OrdChr) {
650 if (Str[StrIdx] == '%') {
651 CurrentState = state_Conversion;
652 LastConversionIdx = StrIdx;
653 }
654 continue;
655 }
656
657 // Seen '%'. Now processing a format conversion.
658 switch (Str[StrIdx]) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000659 // Handle dynamic precision or width specifier.
660 case '*': {
661 ++numConversions;
662
663 if (!HasVAListArg && numConversions > numDataArgs) {
Chris Lattner60800082009-02-18 17:49:48 +0000664 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx);
Ted Kremenek580b6642007-10-12 20:51:52 +0000665
Ted Kremenek580b6642007-10-12 20:51:52 +0000666 if (Str[StrIdx-1] == '.')
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000667 Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg)
668 << OrigFormatExpr->getSourceRange();
Ted Kremenek580b6642007-10-12 20:51:52 +0000669 else
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000670 Diag(Loc, diag::warn_printf_asterisk_width_missing_arg)
671 << OrigFormatExpr->getSourceRange();
Ted Kremenek580b6642007-10-12 20:51:52 +0000672
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000673 // Don't do any more checking. We'll just emit spurious errors.
674 return;
Ted Kremenek580b6642007-10-12 20:51:52 +0000675 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000676
677 // Perform type checking on width/precision specifier.
678 Expr *E = TheCall->getArg(format_idx+numConversions);
679 if (const BuiltinType *BT = E->getType()->getAsBuiltinType())
680 if (BT->getKind() == BuiltinType::Int)
681 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000682
Chris Lattner60800082009-02-18 17:49:48 +0000683 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000684
685 if (Str[StrIdx-1] == '.')
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000686 Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000687 << E->getType() << E->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000688 else
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000689 Diag(Loc, diag::warn_printf_asterisk_width_wrong_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000690 << E->getType() << E->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000691
692 break;
693 }
694
695 // Characters which can terminate a format conversion
696 // (e.g. "%d"). Characters that specify length modifiers or
697 // other flags are handled by the default case below.
698 //
699 // FIXME: additional checks will go into the following cases.
700 case 'i':
701 case 'd':
702 case 'o':
703 case 'u':
704 case 'x':
705 case 'X':
706 case 'D':
707 case 'O':
708 case 'U':
709 case 'e':
710 case 'E':
711 case 'f':
712 case 'F':
713 case 'g':
714 case 'G':
715 case 'a':
716 case 'A':
717 case 'c':
718 case 'C':
719 case 'S':
720 case 's':
721 case 'p':
722 ++numConversions;
723 CurrentState = state_OrdChr;
724 break;
725
726 // CHECK: Are we using "%n"? Issue a warning.
727 case 'n': {
728 ++numConversions;
729 CurrentState = state_OrdChr;
Chris Lattner60800082009-02-18 17:49:48 +0000730 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr,
731 LastConversionIdx);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000732
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000733 Diag(Loc, diag::warn_printf_write_back)<<OrigFormatExpr->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000734 break;
735 }
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000736
737 // Handle "%@"
738 case '@':
739 // %@ is allowed in ObjC format strings only.
740 if(ObjCFExpr != NULL)
741 CurrentState = state_OrdChr;
742 else {
743 // Issue a warning: invalid format conversion.
Chris Lattner60800082009-02-18 17:49:48 +0000744 SourceLocation Loc =
745 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000746
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000747 Diag(Loc, diag::warn_printf_invalid_conversion)
748 << std::string(Str+LastConversionIdx,
749 Str+std::min(LastConversionIdx+2, StrLen))
750 << OrigFormatExpr->getSourceRange();
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000751 }
752 ++numConversions;
753 break;
754
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000755 // Handle "%%"
756 case '%':
757 // Sanity check: Was the first "%" character the previous one?
758 // If not, we will assume that we have a malformed format
759 // conversion, and that the current "%" character is the start
760 // of a new conversion.
761 if (StrIdx - LastConversionIdx == 1)
762 CurrentState = state_OrdChr;
763 else {
764 // Issue a warning: invalid format conversion.
Chris Lattner60800082009-02-18 17:49:48 +0000765 SourceLocation Loc =
766 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000767
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000768 Diag(Loc, diag::warn_printf_invalid_conversion)
769 << std::string(Str+LastConversionIdx, Str+StrIdx)
770 << OrigFormatExpr->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000771
772 // This conversion is broken. Advance to the next format
773 // conversion.
774 LastConversionIdx = StrIdx;
775 ++numConversions;
Ted Kremenek71895b92007-08-14 17:39:48 +0000776 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000777 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000778
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000779 default:
780 // This case catches all other characters: flags, widths, etc.
781 // We should eventually process those as well.
782 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000783 }
784 }
785
786 if (CurrentState == state_Conversion) {
787 // Issue a warning: invalid format conversion.
Chris Lattner60800082009-02-18 17:49:48 +0000788 SourceLocation Loc =
789 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Ted Kremenek71895b92007-08-14 17:39:48 +0000790
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000791 Diag(Loc, diag::warn_printf_invalid_conversion)
792 << std::string(Str+LastConversionIdx,
793 Str+std::min(LastConversionIdx+2, StrLen))
794 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000795 return;
796 }
797
798 if (!HasVAListArg) {
799 // CHECK: Does the number of format conversions exceed the number
800 // of data arguments?
801 if (numConversions > numDataArgs) {
Chris Lattner60800082009-02-18 17:49:48 +0000802 SourceLocation Loc =
803 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Ted Kremenek71895b92007-08-14 17:39:48 +0000804
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000805 Diag(Loc, diag::warn_printf_insufficient_data_args)
806 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000807 }
808 // CHECK: Does the number of data arguments exceed the number of
809 // format conversions in the format string?
810 else if (numConversions < numDataArgs)
Chris Lattner925e60d2007-12-28 05:29:59 +0000811 Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000812 diag::warn_printf_too_many_data_args)
813 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000814 }
815}
Ted Kremenek06de2762007-08-17 16:46:58 +0000816
817//===--- CHECK: Return Address of Stack Variable --------------------------===//
818
819static DeclRefExpr* EvalVal(Expr *E);
820static DeclRefExpr* EvalAddr(Expr* E);
821
822/// CheckReturnStackAddr - Check if a return statement returns the address
823/// of a stack variable.
824void
825Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
826 SourceLocation ReturnLoc) {
Chris Lattner56f34942008-02-13 01:02:39 +0000827
Ted Kremenek06de2762007-08-17 16:46:58 +0000828 // Perform checking for returned stack addresses.
Steve Naroffdd972f22008-09-05 22:11:13 +0000829 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Ted Kremenek06de2762007-08-17 16:46:58 +0000830 if (DeclRefExpr *DR = EvalAddr(RetValExp))
Chris Lattner3c73c412008-11-19 08:23:25 +0000831 Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
Chris Lattner08631c52008-11-23 21:45:46 +0000832 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Steve Naroffc50a4a52008-09-16 22:25:10 +0000833
834 // Skip over implicit cast expressions when checking for block expressions.
835 if (ImplicitCastExpr *IcExpr =
836 dyn_cast_or_null<ImplicitCastExpr>(RetValExp))
837 RetValExp = IcExpr->getSubExpr();
838
Steve Naroff61f40a22008-09-10 19:17:48 +0000839 if (BlockExpr *C = dyn_cast_or_null<BlockExpr>(RetValExp))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000840 Diag(C->getLocStart(), diag::err_ret_local_block)
841 << C->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +0000842 }
843 // Perform checking for stack values returned by reference.
844 else if (lhsType->isReferenceType()) {
Douglas Gregor49badde2008-10-27 19:41:14 +0000845 // Check for a reference to the stack
846 if (DeclRefExpr *DR = EvalVal(RetValExp))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000847 Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
Chris Lattner08631c52008-11-23 21:45:46 +0000848 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +0000849 }
850}
851
852/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
853/// check if the expression in a return statement evaluates to an address
854/// to a location on the stack. The recursion is used to traverse the
855/// AST of the return expression, with recursion backtracking when we
856/// encounter a subexpression that (1) clearly does not lead to the address
857/// of a stack variable or (2) is something we cannot determine leads to
858/// the address of a stack variable based on such local checking.
859///
Ted Kremeneke8c600f2007-08-28 17:02:55 +0000860/// EvalAddr processes expressions that are pointers that are used as
861/// references (and not L-values). EvalVal handles all other values.
Ted Kremenek06de2762007-08-17 16:46:58 +0000862/// At the base case of the recursion is a check for a DeclRefExpr* in
863/// the refers to a stack variable.
864///
865/// This implementation handles:
866///
867/// * pointer-to-pointer casts
868/// * implicit conversions from array references to pointers
869/// * taking the address of fields
870/// * arbitrary interplay between "&" and "*" operators
871/// * pointer arithmetic from an address of a stack variable
872/// * taking the address of an array element where the array is on the stack
873static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek06de2762007-08-17 16:46:58 +0000874 // We should only be called for evaluating pointer expressions.
Steve Naroffdd972f22008-09-05 22:11:13 +0000875 assert((E->getType()->isPointerType() ||
876 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000877 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000878 "EvalAddr only works on pointers");
Ted Kremenek06de2762007-08-17 16:46:58 +0000879
880 // Our "symbolic interpreter" is just a dispatch off the currently
881 // viewed AST node. We then recursively traverse the AST by calling
882 // EvalAddr and EvalVal appropriately.
883 switch (E->getStmtClass()) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000884 case Stmt::ParenExprClass:
885 // Ignore parentheses.
886 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek06de2762007-08-17 16:46:58 +0000887
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000888 case Stmt::UnaryOperatorClass: {
889 // The only unary operator that make sense to handle here
890 // is AddrOf. All others don't make sense as pointers.
891 UnaryOperator *U = cast<UnaryOperator>(E);
Ted Kremenek06de2762007-08-17 16:46:58 +0000892
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000893 if (U->getOpcode() == UnaryOperator::AddrOf)
894 return EvalVal(U->getSubExpr());
895 else
Ted Kremenek06de2762007-08-17 16:46:58 +0000896 return NULL;
897 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000898
899 case Stmt::BinaryOperatorClass: {
900 // Handle pointer arithmetic. All other binary operators are not valid
901 // in this context.
902 BinaryOperator *B = cast<BinaryOperator>(E);
903 BinaryOperator::Opcode op = B->getOpcode();
904
905 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
906 return NULL;
907
908 Expr *Base = B->getLHS();
909
910 // Determine which argument is the real pointer base. It could be
911 // the RHS argument instead of the LHS.
912 if (!Base->getType()->isPointerType()) Base = B->getRHS();
913
914 assert (Base->getType()->isPointerType());
915 return EvalAddr(Base);
916 }
Steve Naroff61f40a22008-09-10 19:17:48 +0000917
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000918 // For conditional operators we need to see if either the LHS or RHS are
919 // valid DeclRefExpr*s. If one of them is valid, we return it.
920 case Stmt::ConditionalOperatorClass: {
921 ConditionalOperator *C = cast<ConditionalOperator>(E);
922
923 // Handle the GNU extension for missing LHS.
924 if (Expr *lhsExpr = C->getLHS())
925 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
926 return LHS;
927
928 return EvalAddr(C->getRHS());
929 }
930
Ted Kremenek54b52742008-08-07 00:49:01 +0000931 // For casts, we need to handle conversions from arrays to
932 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +0000933 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +0000934 case Stmt::CStyleCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +0000935 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +0000936 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +0000937 QualType T = SubExpr->getType();
938
Steve Naroffdd972f22008-09-05 22:11:13 +0000939 if (SubExpr->getType()->isPointerType() ||
940 SubExpr->getType()->isBlockPointerType() ||
941 SubExpr->getType()->isObjCQualifiedIdType())
Ted Kremenek54b52742008-08-07 00:49:01 +0000942 return EvalAddr(SubExpr);
943 else if (T->isArrayType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000944 return EvalVal(SubExpr);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000945 else
Ted Kremenek54b52742008-08-07 00:49:01 +0000946 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000947 }
948
949 // C++ casts. For dynamic casts, static casts, and const casts, we
950 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +0000951 // through the cast. In the case the dynamic cast doesn't fail (and
952 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000953 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +0000954 // FIXME: The comment about is wrong; we're not always converting
955 // from pointer to pointer. I'm guessing that this code should also
956 // handle references to objects.
957 case Stmt::CXXStaticCastExprClass:
958 case Stmt::CXXDynamicCastExprClass:
959 case Stmt::CXXConstCastExprClass:
960 case Stmt::CXXReinterpretCastExprClass: {
961 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +0000962 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000963 return EvalAddr(S);
964 else
965 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000966 }
967
968 // Everything else: we simply don't reason about them.
969 default:
970 return NULL;
971 }
Ted Kremenek06de2762007-08-17 16:46:58 +0000972}
973
974
975/// EvalVal - This function is complements EvalAddr in the mutual recursion.
976/// See the comments for EvalAddr for more details.
977static DeclRefExpr* EvalVal(Expr *E) {
978
Ted Kremeneke8c600f2007-08-28 17:02:55 +0000979 // We should only be called for evaluating non-pointer expressions, or
980 // expressions with a pointer type that are not used as references but instead
981 // are l-values (e.g., DeclRefExpr with a pointer type).
982
Ted Kremenek06de2762007-08-17 16:46:58 +0000983 // Our "symbolic interpreter" is just a dispatch off the currently
984 // viewed AST node. We then recursively traverse the AST by calling
985 // EvalAddr and EvalVal appropriately.
986 switch (E->getStmtClass()) {
Douglas Gregor1a49af92009-01-06 05:10:23 +0000987 case Stmt::DeclRefExprClass:
988 case Stmt::QualifiedDeclRefExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +0000989 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
990 // at code that refers to a variable's name. We check if it has local
991 // storage within the function, and if so, return the expression.
992 DeclRefExpr *DR = cast<DeclRefExpr>(E);
993
994 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000995 if(V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
Ted Kremenek06de2762007-08-17 16:46:58 +0000996
997 return NULL;
998 }
999
1000 case Stmt::ParenExprClass:
1001 // Ignore parentheses.
1002 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
1003
1004 case Stmt::UnaryOperatorClass: {
1005 // The only unary operator that make sense to handle here
1006 // is Deref. All others don't resolve to a "name." This includes
1007 // handling all sorts of rvalues passed to a unary operator.
1008 UnaryOperator *U = cast<UnaryOperator>(E);
1009
1010 if (U->getOpcode() == UnaryOperator::Deref)
1011 return EvalAddr(U->getSubExpr());
1012
1013 return NULL;
1014 }
1015
1016 case Stmt::ArraySubscriptExprClass: {
1017 // Array subscripts are potential references to data on the stack. We
1018 // retrieve the DeclRefExpr* for the array variable if it indeed
1019 // has local storage.
Ted Kremenek23245122007-08-20 16:18:38 +00001020 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek06de2762007-08-17 16:46:58 +00001021 }
1022
1023 case Stmt::ConditionalOperatorClass: {
1024 // For conditional operators we need to see if either the LHS or RHS are
1025 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
1026 ConditionalOperator *C = cast<ConditionalOperator>(E);
1027
Anders Carlsson39073232007-11-30 19:04:31 +00001028 // Handle the GNU extension for missing LHS.
1029 if (Expr *lhsExpr = C->getLHS())
1030 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
1031 return LHS;
1032
1033 return EvalVal(C->getRHS());
Ted Kremenek06de2762007-08-17 16:46:58 +00001034 }
1035
1036 // Accesses to members are potential references to data on the stack.
1037 case Stmt::MemberExprClass: {
1038 MemberExpr *M = cast<MemberExpr>(E);
1039
1040 // Check for indirect access. We only want direct field accesses.
1041 if (!M->isArrow())
1042 return EvalVal(M->getBase());
1043 else
1044 return NULL;
1045 }
1046
1047 // Everything else: we simply don't reason about them.
1048 default:
1049 return NULL;
1050 }
1051}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001052
1053//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
1054
1055/// Check for comparisons of floating point operands using != and ==.
1056/// Issue a warning if these are no self-comparisons, as they are not likely
1057/// to do what the programmer intended.
1058void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
1059 bool EmitWarning = true;
1060
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00001061 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek32e97b62008-01-17 17:55:13 +00001062 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001063
1064 // Special case: check for x == x (which is OK).
1065 // Do not emit warnings for such cases.
1066 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
1067 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
1068 if (DRL->getDecl() == DRR->getDecl())
1069 EmitWarning = false;
1070
Ted Kremenek1b500bb2007-11-29 00:59:04 +00001071
1072 // Special case: check for comparisons against literals that can be exactly
1073 // represented by APFloat. In such cases, do not emit a warning. This
1074 // is a heuristic: often comparison against such literals are used to
1075 // detect if a value in a variable has not changed. This clearly can
1076 // lead to false negatives.
1077 if (EmitWarning) {
1078 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
1079 if (FLL->isExact())
1080 EmitWarning = false;
1081 }
1082 else
1083 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
1084 if (FLR->isExact())
1085 EmitWarning = false;
1086 }
1087 }
1088
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001089 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001090 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001091 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001092 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001093 EmitWarning = false;
1094
Sebastian Redl0eb23302009-01-19 00:08:26 +00001095 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001096 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001097 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001098 EmitWarning = false;
1099
1100 // Emit the diagnostic.
1101 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001102 Diag(loc, diag::warn_floatingpoint_eq)
1103 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001104}