blob: b22932bb9a9fd2a093720392c284c1bc9203d988 [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 Lattner719e6152009-02-18 19:21:10 +000020#include "clang/Lex/LiteralSupport.h"
Chris Lattner59907c42007-08-10 20:18:51 +000021#include "clang/Lex/Preprocessor.h"
Chris Lattner59907c42007-08-10 20:18:51 +000022using namespace clang;
23
Chris Lattner60800082009-02-18 17:49:48 +000024/// getLocationOfStringLiteralByte - Return a source location that points to the
25/// specified byte of the specified string literal.
26///
27/// Strings are amazingly complex. They can be formed from multiple tokens and
28/// can have escape sequences in them in addition to the usual trigraph and
29/// escaped newline business. This routine handles this complexity.
30///
31SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
32 unsigned ByteNo) const {
33 assert(!SL->isWide() && "This doesn't work for wide strings yet");
34
Chris Lattner719e6152009-02-18 19:21:10 +000035 llvm::SmallString<16> SpellingBuffer;
Chris Lattnerd0d082f2009-02-18 18:34:12 +000036
Chris Lattner60800082009-02-18 17:49:48 +000037 // Loop over all of the tokens in this string until we find the one that
38 // contains the byte we're looking for.
39 unsigned TokNo = 0;
40 while (1) {
41 assert(TokNo < SL->getNumConcatenated() && "Invalid byte number!");
42 SourceLocation StrTokLoc = SL->getStrTokenLoc(TokNo);
43
44 // Get the spelling of the string so that we can get the data that makes up
45 // the string literal, not the identifier for the macro it is potentially
46 // expanded through.
47 SourceLocation StrTokSpellingLoc = SourceMgr.getSpellingLoc(StrTokLoc);
48
49 // Re-lex the token to get its length and original spelling.
50 std::pair<FileID, unsigned> LocInfo =
51 SourceMgr.getDecomposedLoc(StrTokSpellingLoc);
52 std::pair<const char *,const char *> Buffer =
53 SourceMgr.getBufferData(LocInfo.first);
54 const char *StrData = Buffer.first+LocInfo.second;
55
56 // Create a langops struct and enable trigraphs. This is sufficient for
57 // relexing tokens.
58 LangOptions LangOpts;
59 LangOpts.Trigraphs = true;
60
61 // Create a lexer starting at the beginning of this token.
62 Lexer TheLexer(StrTokSpellingLoc, LangOpts, Buffer.first, StrData,
63 Buffer.second);
64 Token TheTok;
65 TheLexer.LexFromRawLexer(TheTok);
66
Chris Lattner0150cdf2009-02-18 18:40:20 +000067 // We generally care about the length of the token, which is known by the
68 // lexer as long as we don't need to clean it (trigraphs/newlines).
69 unsigned TokNumBytes;
70 if (!TheTok.needsCleaning()) {
71 TokNumBytes = TheTok.getLength();
72 } else {
73 // Get the spelling of the token to remove trigraphs and escaped newlines.
74 SpellingBuffer.resize(TheTok.getLength());
75 const char *SpellingPtr = &SpellingBuffer[0];
76 TokNumBytes = PP.getSpelling(TheTok, SpellingPtr);
77 }
Chris Lattnerd0d082f2009-02-18 18:34:12 +000078
Chris Lattner60800082009-02-18 17:49:48 +000079 // The length of the string is the token length minus the two quotes.
Chris Lattner0150cdf2009-02-18 18:40:20 +000080 TokNumBytes -= 2;
Chris Lattner2197c962009-02-18 18:52:52 +000081
Chris Lattner2197c962009-02-18 18:52:52 +000082 // If the byte is in this token, return the location of the byte.
Chris Lattner60800082009-02-18 17:49:48 +000083 if (ByteNo < TokNumBytes ||
84 (ByteNo == TokNumBytes && TokNo == SL->getNumConcatenated())) {
Chris Lattner719e6152009-02-18 19:21:10 +000085 unsigned Offset =
86 StringLiteralParser::getOffsetOfStringByte(TheTok, ByteNo, PP);
87
88 // Now that we know the offset of the token in the spelling, use the
89 // preprocessor to get the offset in the original source.
90 return PP.AdvanceToTokenCharacter(StrTokLoc, Offset);
Chris Lattner60800082009-02-18 17:49:48 +000091 }
92
93 // Move to the next string token.
94 ++TokNo;
95 ByteNo -= TokNumBytes;
96 }
97}
98
99
Chris Lattner59907c42007-08-10 20:18:51 +0000100/// CheckFunctionCall - Check a direct function call for various correctness
101/// and safety properties not strictly enforced by the C type system.
Sebastian Redl0eb23302009-01-19 00:08:26 +0000102Action::OwningExprResult
103Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
104 OwningExprResult TheCallResult(Owned(TheCall));
Chris Lattner59907c42007-08-10 20:18:51 +0000105 // Get the IdentifierInfo* for the called function.
106 IdentifierInfo *FnInfo = FDecl->getIdentifier();
Douglas Gregor2def4832008-11-17 20:34:05 +0000107
108 // None of the checks below are needed for functions that don't have
109 // simple names (e.g., C++ conversion functions).
110 if (!FnInfo)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000111 return move(TheCallResult);
Douglas Gregor2def4832008-11-17 20:34:05 +0000112
Douglas Gregor3c385e52009-02-14 18:57:46 +0000113 switch (FDecl->getBuiltinID(Context)) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000114 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000115 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000116 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000117 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000118 return ExprError();
119 return move(TheCallResult);
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000120 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000121 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000122 if (SemaBuiltinVAStart(TheCall))
123 return ExprError();
124 return move(TheCallResult);
Chris Lattner1b9a0792007-12-20 00:26:33 +0000125 case Builtin::BI__builtin_isgreater:
126 case Builtin::BI__builtin_isgreaterequal:
127 case Builtin::BI__builtin_isless:
128 case Builtin::BI__builtin_islessequal:
129 case Builtin::BI__builtin_islessgreater:
130 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000131 if (SemaBuiltinUnorderedCompare(TheCall))
132 return ExprError();
133 return move(TheCallResult);
Eli Friedman6cfda232008-05-20 08:23:37 +0000134 case Builtin::BI__builtin_return_address:
135 case Builtin::BI__builtin_frame_address:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000136 if (SemaBuiltinStackAddress(TheCall))
137 return ExprError();
138 return move(TheCallResult);
Eli Friedmand38617c2008-05-14 19:38:39 +0000139 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000140 return SemaBuiltinShuffleVector(TheCall);
141 // TheCall will be freed by the smart pointer here, but that's fine, since
142 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000143 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000144 if (SemaBuiltinPrefetch(TheCall))
145 return ExprError();
146 return move(TheCallResult);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000147 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000148 if (SemaBuiltinObjectSize(TheCall))
149 return ExprError();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000150 }
Daniel Dunbarde454282008-10-02 18:44:07 +0000151
152 // FIXME: This mechanism should be abstracted to be less fragile and
153 // more efficient. For example, just map function ids to custom
154 // handlers.
155
Chris Lattner59907c42007-08-10 20:18:51 +0000156 // Printf checking.
Douglas Gregor3c385e52009-02-14 18:57:46 +0000157 if (const FormatAttr *Format = FDecl->getAttr<FormatAttr>()) {
158 if (Format->getType() == "printf") {
159 bool HasVAListArg = false;
160 if (const FunctionTypeProto *Proto
161 = FDecl->getType()->getAsFunctionTypeProto())
162 HasVAListArg = !Proto->isVariadic();
163 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
164 Format->getFirstArg() - 1);
165 }
Chris Lattner59907c42007-08-10 20:18:51 +0000166 }
Sebastian Redl0eb23302009-01-19 00:08:26 +0000167
168 return move(TheCallResult);
Anders Carlsson71993dd2007-08-17 05:31:46 +0000169}
170
Chris Lattner69039812009-02-18 06:01:06 +0000171/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000172/// CFString constructor is correct
Chris Lattner69039812009-02-18 06:01:06 +0000173bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000174 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000175 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
176
177 if (!Literal || Literal->isWide()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000178 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
179 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000180 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000181 }
182
183 const char *Data = Literal->getStrData();
184 unsigned Length = Literal->getByteLength();
185
186 for (unsigned i = 0; i < Length; ++i) {
187 if (!isascii(Data[i])) {
Chris Lattner60800082009-02-18 17:49:48 +0000188 Diag(getLocationOfStringLiteralByte(Literal, i),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000189 diag::warn_cfstring_literal_contains_non_ascii_character)
190 << Arg->getSourceRange();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000191 break;
192 }
193
194 if (!Data[i]) {
Chris Lattner60800082009-02-18 17:49:48 +0000195 Diag(getLocationOfStringLiteralByte(Literal, i),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000196 diag::warn_cfstring_literal_contains_nul_character)
197 << Arg->getSourceRange();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000198 break;
199 }
200 }
201
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000202 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000203}
204
Chris Lattnerc27c6652007-12-20 00:05:45 +0000205/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
206/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000207bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
208 Expr *Fn = TheCall->getCallee();
209 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000210 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000211 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000212 << 0 /*function call*/ << Fn->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000213 << SourceRange(TheCall->getArg(2)->getLocStart(),
214 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000215 return true;
216 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000217
218 if (TheCall->getNumArgs() < 2) {
219 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
220 << 0 /*function call*/;
221 }
222
Chris Lattnerc27c6652007-12-20 00:05:45 +0000223 // Determine whether the current function is variadic or not.
224 bool isVariadic;
Eli Friedman56f20ae2008-12-15 22:05:35 +0000225 if (getCurFunctionDecl()) {
226 if (FunctionTypeProto* FTP =
227 dyn_cast<FunctionTypeProto>(getCurFunctionDecl()->getType()))
228 isVariadic = FTP->isVariadic();
229 else
230 isVariadic = false;
231 } else {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000232 isVariadic = getCurMethodDecl()->isVariadic();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000233 }
Chris Lattner30ce3442007-12-19 23:59:04 +0000234
Chris Lattnerc27c6652007-12-20 00:05:45 +0000235 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000236 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
237 return true;
238 }
239
240 // Verify that the second argument to the builtin is the last argument of the
241 // current function or method.
242 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000243 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Anders Carlsson88cf2262008-02-11 04:20:54 +0000244
245 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
246 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000247 // FIXME: This isn't correct for methods (results in bogus warning).
248 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000249 const ParmVarDecl *LastArg;
Chris Lattner371f2582008-12-04 23:50:19 +0000250 if (FunctionDecl *FD = getCurFunctionDecl())
251 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000252 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000253 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000254 SecondArgIsLastNamedArgument = PV == LastArg;
255 }
256 }
257
258 if (!SecondArgIsLastNamedArgument)
Chris Lattner925e60d2007-12-28 05:29:59 +0000259 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000260 diag::warn_second_parameter_of_va_start_not_last_named_argument);
261 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000262}
Chris Lattner30ce3442007-12-19 23:59:04 +0000263
Chris Lattner1b9a0792007-12-20 00:26:33 +0000264/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
265/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000266bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
267 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000268 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
269 << 0 /*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000270 if (TheCall->getNumArgs() > 2)
271 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000272 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000273 << 0 /*function call*/
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000274 << SourceRange(TheCall->getArg(2)->getLocStart(),
275 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner1b9a0792007-12-20 00:26:33 +0000276
Chris Lattner925e60d2007-12-28 05:29:59 +0000277 Expr *OrigArg0 = TheCall->getArg(0);
278 Expr *OrigArg1 = TheCall->getArg(1);
Chris Lattner1b9a0792007-12-20 00:26:33 +0000279
280 // Do standard promotions between the two arguments, returning their common
281 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000282 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Chris Lattner1b9a0792007-12-20 00:26:33 +0000283
284 // If the common type isn't a real floating type, then the arguments were
285 // invalid for this operation.
286 if (!Res->isRealFloatingType())
Chris Lattner925e60d2007-12-28 05:29:59 +0000287 return Diag(OrigArg0->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000288 diag::err_typecheck_call_invalid_ordered_compare)
Chris Lattnerd1625842008-11-24 06:25:27 +0000289 << OrigArg0->getType() << OrigArg1->getType()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000290 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
Chris Lattner1b9a0792007-12-20 00:26:33 +0000291
292 return false;
293}
294
Eli Friedman6cfda232008-05-20 08:23:37 +0000295bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) {
296 // The signature for these builtins is exact; the only thing we need
297 // to check is that the argument is a constant.
298 SourceLocation Loc;
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000299 if (!TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc))
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000300 return Diag(Loc, diag::err_stack_const_level) << TheCall->getSourceRange();
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000301
Eli Friedman6cfda232008-05-20 08:23:37 +0000302 return false;
303}
304
Eli Friedmand38617c2008-05-14 19:38:39 +0000305/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
306// This is declared to take (...), so we have to check everything.
Sebastian Redl0eb23302009-01-19 00:08:26 +0000307Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000308 if (TheCall->getNumArgs() < 3)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000309 return ExprError(Diag(TheCall->getLocEnd(),
310 diag::err_typecheck_call_too_few_args)
311 << 0 /*function call*/ << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000312
313 QualType FAType = TheCall->getArg(0)->getType();
314 QualType SAType = TheCall->getArg(1)->getType();
315
316 if (!FAType->isVectorType() || !SAType->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000317 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
318 << SourceRange(TheCall->getArg(0)->getLocStart(),
319 TheCall->getArg(1)->getLocEnd());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000320 return ExprError();
Eli Friedmand38617c2008-05-14 19:38:39 +0000321 }
322
Chris Lattnerb77792e2008-07-26 22:17:49 +0000323 if (Context.getCanonicalType(FAType).getUnqualifiedType() !=
324 Context.getCanonicalType(SAType).getUnqualifiedType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000325 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
326 << SourceRange(TheCall->getArg(0)->getLocStart(),
327 TheCall->getArg(1)->getLocEnd());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000328 return ExprError();
Eli Friedmand38617c2008-05-14 19:38:39 +0000329 }
330
331 unsigned numElements = FAType->getAsVectorType()->getNumElements();
332 if (TheCall->getNumArgs() != numElements+2) {
333 if (TheCall->getNumArgs() < numElements+2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000334 return ExprError(Diag(TheCall->getLocEnd(),
335 diag::err_typecheck_call_too_few_args)
336 << 0 /*function call*/ << TheCall->getSourceRange());
337 return ExprError(Diag(TheCall->getLocEnd(),
338 diag::err_typecheck_call_too_many_args)
339 << 0 /*function call*/ << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000340 }
341
342 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
343 llvm::APSInt Result(32);
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000344 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000345 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000346 diag::err_shufflevector_nonconstant_argument)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000347 << TheCall->getArg(i)->getSourceRange());
348
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000349 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000350 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000351 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000352 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000353 }
354
355 llvm::SmallVector<Expr*, 32> exprs;
356
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000357 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000358 exprs.push_back(TheCall->getArg(i));
359 TheCall->setArg(i, 0);
360 }
361
Ted Kremenek8189cde2009-02-07 01:47:29 +0000362 return Owned(new (Context) ShuffleVectorExpr(exprs.begin(), numElements+2,
363 FAType,
364 TheCall->getCallee()->getLocStart(),
365 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000366}
Chris Lattner30ce3442007-12-19 23:59:04 +0000367
Daniel Dunbar4493f792008-07-21 22:59:13 +0000368/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
369// This is declared to take (const void*, ...) and can take two
370// optional constant int args.
371bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000372 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000373
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000374 if (NumArgs > 3)
375 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000376 << 0 /*function call*/ << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000377
378 // Argument 0 is checked for us and the remaining arguments must be
379 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000380 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000381 Expr *Arg = TheCall->getArg(i);
382 QualType RWType = Arg->getType();
383
384 const BuiltinType *BT = RWType->getAsBuiltinType();
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000385 llvm::APSInt Result;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000386 if (!BT || BT->getKind() != BuiltinType::Int ||
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000387 !Arg->isIntegerConstantExpr(Result, Context))
388 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument)
389 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar4493f792008-07-21 22:59:13 +0000390
391 // FIXME: gcc issues a warning and rewrites these to 0. These
392 // seems especially odd for the third argument since the default
393 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000394 if (i == 1) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000395 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000396 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
397 << "0" << "1" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar4493f792008-07-21 22:59:13 +0000398 } else {
399 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000400 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
401 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar4493f792008-07-21 22:59:13 +0000402 }
403 }
404
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000405 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000406}
407
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000408/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
409/// int type). This simply type checks that type is one of the defined
410/// constants (0-3).
411bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
412 Expr *Arg = TheCall->getArg(1);
413 QualType ArgType = Arg->getType();
414 const BuiltinType *BT = ArgType->getAsBuiltinType();
415 llvm::APSInt Result(32);
416 if (!BT || BT->getKind() != BuiltinType::Int ||
417 !Arg->isIntegerConstantExpr(Result, Context)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000418 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
419 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000420 }
421
422 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000423 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
424 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000425 }
426
427 return false;
428}
429
Ted Kremenekd30ef872009-01-12 23:09:09 +0000430// Handle i > 1 ? "x" : "y", recursivelly
431bool Sema::SemaCheckStringLiteral(Expr *E, CallExpr *TheCall, bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000432 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenekd30ef872009-01-12 23:09:09 +0000433
434 switch (E->getStmtClass()) {
435 case Stmt::ConditionalOperatorClass: {
436 ConditionalOperator *C = cast<ConditionalOperator>(E);
437 return SemaCheckStringLiteral(C->getLHS(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000438 HasVAListArg, format_idx, firstDataArg)
Ted Kremenekd30ef872009-01-12 23:09:09 +0000439 && SemaCheckStringLiteral(C->getRHS(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000440 HasVAListArg, format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000441 }
442
443 case Stmt::ImplicitCastExprClass: {
444 ImplicitCastExpr *Expr = dyn_cast<ImplicitCastExpr>(E);
445 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000446 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000447 }
448
449 case Stmt::ParenExprClass: {
450 ParenExpr *Expr = dyn_cast<ParenExpr>(E);
451 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000452 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000453 }
454
455 default: {
456 ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E);
457 StringLiteral *StrE = NULL;
458
459 if (ObjCFExpr)
460 StrE = ObjCFExpr->getString();
461 else
462 StrE = dyn_cast<StringLiteral>(E);
463
464 if (StrE) {
Douglas Gregor3c385e52009-02-14 18:57:46 +0000465 CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx,
466 firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000467 return true;
468 }
469
470 return false;
471 }
472 }
473}
474
475
Chris Lattner59907c42007-08-10 20:18:51 +0000476/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Ted Kremenek71895b92007-08-14 17:39:48 +0000477/// correct use of format strings.
478///
479/// HasVAListArg - A predicate indicating whether the printf-like
480/// function is passed an explicit va_arg argument (e.g., vprintf)
481///
482/// format_idx - The index into Args for the format string.
483///
484/// Improper format strings to functions in the printf family can be
485/// the source of bizarre bugs and very serious security holes. A
486/// good source of information is available in the following paper
487/// (which includes additional references):
Chris Lattner59907c42007-08-10 20:18:51 +0000488///
489/// FormatGuard: Automatic Protection From printf Format String
490/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremenek71895b92007-08-14 17:39:48 +0000491///
492/// Functionality implemented:
493///
494/// We can statically check the following properties for string
495/// literal format strings for non v.*printf functions (where the
496/// arguments are passed directly):
497//
498/// (1) Are the number of format conversions equal to the number of
499/// data arguments?
500///
501/// (2) Does each format conversion correctly match the type of the
502/// corresponding data argument? (TODO)
503///
504/// Moreover, for all printf functions we can:
505///
506/// (3) Check for a missing format string (when not caught by type checking).
507///
508/// (4) Check for no-operation flags; e.g. using "#" with format
509/// conversion 'c' (TODO)
510///
511/// (5) Check the use of '%n', a major source of security holes.
512///
513/// (6) Check for malformed format conversions that don't specify anything.
514///
515/// (7) Check for empty format strings. e.g: printf("");
516///
517/// (8) Check that the format string is a wide literal.
518///
Ted Kremenek6d439592008-03-03 16:50:00 +0000519/// (9) Also check the arguments of functions with the __format__ attribute.
520/// (TODO).
521///
Ted Kremenek71895b92007-08-14 17:39:48 +0000522/// All of these checks can be done by parsing the format string.
523///
524/// For now, we ONLY do (1), (3), (5), (6), (7), and (8).
Chris Lattner59907c42007-08-10 20:18:51 +0000525void
Chris Lattner925e60d2007-12-28 05:29:59 +0000526Sema::CheckPrintfArguments(CallExpr *TheCall, bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000527 unsigned format_idx, unsigned firstDataArg) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000528 Expr *Fn = TheCall->getCallee();
529
Ted Kremenek71895b92007-08-14 17:39:48 +0000530 // CHECK: printf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +0000531 if (format_idx >= TheCall->getNumArgs()) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000532 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string)
533 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000534 return;
535 }
536
Chris Lattner56f34942008-02-13 01:02:39 +0000537 Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Chris Lattner459e8482007-08-25 05:36:18 +0000538
Chris Lattner59907c42007-08-10 20:18:51 +0000539 // CHECK: format string is not a string literal.
540 //
Ted Kremenek71895b92007-08-14 17:39:48 +0000541 // Dynamically generated format strings are difficult to
542 // automatically vet at compile time. Requiring that format strings
543 // are string literals: (1) permits the checking of format strings by
544 // the compiler and thereby (2) can practically remove the source of
545 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000546
547 // Format string can be either ObjC string (e.g. @"%d") or
548 // C string (e.g. "%d")
549 // ObjC string uses the same format specifiers as C string, so we can use
550 // the same format string checking logic for both ObjC and C strings.
Douglas Gregor3c385e52009-02-14 18:57:46 +0000551 bool isFExpr = SemaCheckStringLiteral(OrigFormatExpr, TheCall,
552 HasVAListArg, format_idx,
553 firstDataArg);
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000554
Ted Kremenekd30ef872009-01-12 23:09:09 +0000555 if (!isFExpr) {
Ted Kremenek4a336462007-12-17 19:03:13 +0000556 // For vprintf* functions (i.e., HasVAListArg==true), we add a
557 // special check to see if the format string is a function parameter
558 // of the function calling the printf function. If the function
559 // has an attribute indicating it is a printf-like function, then we
560 // should suppress warnings concerning non-literals being used in a call
561 // to a vprintf function. For example:
562 //
563 // void
564 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...) {
565 // va_list ap;
566 // va_start(ap, fmt);
567 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
568 // ...
569 //
570 //
571 // FIXME: We don't have full attribute support yet, so just check to see
572 // if the argument is a DeclRefExpr that references a parameter. We'll
573 // add proper support for checking the attribute later.
574 if (HasVAListArg)
Chris Lattner998568f2007-12-28 05:38:24 +0000575 if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(OrigFormatExpr))
576 if (isa<ParmVarDecl>(DR->getDecl()))
Ted Kremenek4a336462007-12-17 19:03:13 +0000577 return;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000578
Chris Lattner925e60d2007-12-28 05:29:59 +0000579 Diag(TheCall->getArg(format_idx)->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000580 diag::warn_printf_not_string_constant)
581 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000582 return;
583 }
Ted Kremenekd30ef872009-01-12 23:09:09 +0000584}
Ted Kremenek71895b92007-08-14 17:39:48 +0000585
Ted Kremenekd30ef872009-01-12 23:09:09 +0000586void Sema::CheckPrintfString(StringLiteral *FExpr, Expr *OrigFormatExpr,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000587 CallExpr *TheCall, bool HasVAListArg, unsigned format_idx,
588 unsigned firstDataArg) {
Ted Kremenekd30ef872009-01-12 23:09:09 +0000589
590 ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(OrigFormatExpr);
Ted Kremenek71895b92007-08-14 17:39:48 +0000591 // CHECK: is the format string a wide literal?
592 if (FExpr->isWide()) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000593 Diag(FExpr->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000594 diag::warn_printf_format_string_is_wide_literal)
595 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000596 return;
597 }
598
599 // Str - The format string. NOTE: this is NOT null-terminated!
600 const char * const Str = FExpr->getStrData();
601
602 // CHECK: empty format string?
603 const unsigned StrLen = FExpr->getByteLength();
604
605 if (StrLen == 0) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000606 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string)
607 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000608 return;
609 }
610
611 // We process the format string using a binary state machine. The
612 // current state is stored in CurrentState.
613 enum {
614 state_OrdChr,
615 state_Conversion
616 } CurrentState = state_OrdChr;
617
618 // numConversions - The number of conversions seen so far. This is
619 // incremented as we traverse the format string.
620 unsigned numConversions = 0;
621
622 // numDataArgs - The number of data arguments after the format
623 // string. This can only be determined for non vprintf-like
624 // functions. For those functions, this value is 1 (the sole
625 // va_arg argument).
Douglas Gregor3c385e52009-02-14 18:57:46 +0000626 unsigned numDataArgs = TheCall->getNumArgs()-firstDataArg;
Ted Kremenek71895b92007-08-14 17:39:48 +0000627
628 // Inspect the format string.
629 unsigned StrIdx = 0;
630
631 // LastConversionIdx - Index within the format string where we last saw
632 // a '%' character that starts a new format conversion.
633 unsigned LastConversionIdx = 0;
634
Chris Lattner925e60d2007-12-28 05:29:59 +0000635 for (; StrIdx < StrLen; ++StrIdx) {
Chris Lattner998568f2007-12-28 05:38:24 +0000636
Ted Kremenek71895b92007-08-14 17:39:48 +0000637 // Is the number of detected conversion conversions greater than
638 // the number of matching data arguments? If so, stop.
639 if (!HasVAListArg && numConversions > numDataArgs) break;
640
641 // Handle "\0"
Chris Lattner925e60d2007-12-28 05:29:59 +0000642 if (Str[StrIdx] == '\0') {
Ted Kremenek71895b92007-08-14 17:39:48 +0000643 // The string returned by getStrData() is not null-terminated,
644 // so the presence of a null character is likely an error.
Chris Lattner60800082009-02-18 17:49:48 +0000645 Diag(getLocationOfStringLiteralByte(FExpr, StrIdx),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000646 diag::warn_printf_format_string_contains_null_char)
647 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000648 return;
649 }
650
651 // Ordinary characters (not processing a format conversion).
652 if (CurrentState == state_OrdChr) {
653 if (Str[StrIdx] == '%') {
654 CurrentState = state_Conversion;
655 LastConversionIdx = StrIdx;
656 }
657 continue;
658 }
659
660 // Seen '%'. Now processing a format conversion.
661 switch (Str[StrIdx]) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000662 // Handle dynamic precision or width specifier.
663 case '*': {
664 ++numConversions;
665
666 if (!HasVAListArg && numConversions > numDataArgs) {
Chris Lattner60800082009-02-18 17:49:48 +0000667 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx);
Ted Kremenek580b6642007-10-12 20:51:52 +0000668
Ted Kremenek580b6642007-10-12 20:51:52 +0000669 if (Str[StrIdx-1] == '.')
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000670 Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg)
671 << OrigFormatExpr->getSourceRange();
Ted Kremenek580b6642007-10-12 20:51:52 +0000672 else
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000673 Diag(Loc, diag::warn_printf_asterisk_width_missing_arg)
674 << OrigFormatExpr->getSourceRange();
Ted Kremenek580b6642007-10-12 20:51:52 +0000675
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000676 // Don't do any more checking. We'll just emit spurious errors.
677 return;
Ted Kremenek580b6642007-10-12 20:51:52 +0000678 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000679
680 // Perform type checking on width/precision specifier.
681 Expr *E = TheCall->getArg(format_idx+numConversions);
682 if (const BuiltinType *BT = E->getType()->getAsBuiltinType())
683 if (BT->getKind() == BuiltinType::Int)
684 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000685
Chris Lattner60800082009-02-18 17:49:48 +0000686 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000687
688 if (Str[StrIdx-1] == '.')
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000689 Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000690 << E->getType() << E->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000691 else
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000692 Diag(Loc, diag::warn_printf_asterisk_width_wrong_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000693 << E->getType() << E->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000694
695 break;
696 }
697
698 // Characters which can terminate a format conversion
699 // (e.g. "%d"). Characters that specify length modifiers or
700 // other flags are handled by the default case below.
701 //
702 // FIXME: additional checks will go into the following cases.
703 case 'i':
704 case 'd':
705 case 'o':
706 case 'u':
707 case 'x':
708 case 'X':
709 case 'D':
710 case 'O':
711 case 'U':
712 case 'e':
713 case 'E':
714 case 'f':
715 case 'F':
716 case 'g':
717 case 'G':
718 case 'a':
719 case 'A':
720 case 'c':
721 case 'C':
722 case 'S':
723 case 's':
724 case 'p':
725 ++numConversions;
726 CurrentState = state_OrdChr;
727 break;
728
729 // CHECK: Are we using "%n"? Issue a warning.
730 case 'n': {
731 ++numConversions;
732 CurrentState = state_OrdChr;
Chris Lattner60800082009-02-18 17:49:48 +0000733 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr,
734 LastConversionIdx);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000735
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000736 Diag(Loc, diag::warn_printf_write_back)<<OrigFormatExpr->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000737 break;
738 }
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000739
740 // Handle "%@"
741 case '@':
742 // %@ is allowed in ObjC format strings only.
743 if(ObjCFExpr != NULL)
744 CurrentState = state_OrdChr;
745 else {
746 // Issue a warning: invalid format conversion.
Chris Lattner60800082009-02-18 17:49:48 +0000747 SourceLocation Loc =
748 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000749
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000750 Diag(Loc, diag::warn_printf_invalid_conversion)
751 << std::string(Str+LastConversionIdx,
752 Str+std::min(LastConversionIdx+2, StrLen))
753 << OrigFormatExpr->getSourceRange();
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000754 }
755 ++numConversions;
756 break;
757
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000758 // Handle "%%"
759 case '%':
760 // Sanity check: Was the first "%" character the previous one?
761 // If not, we will assume that we have a malformed format
762 // conversion, and that the current "%" character is the start
763 // of a new conversion.
764 if (StrIdx - LastConversionIdx == 1)
765 CurrentState = state_OrdChr;
766 else {
767 // Issue a warning: invalid format conversion.
Chris Lattner60800082009-02-18 17:49:48 +0000768 SourceLocation Loc =
769 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000770
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000771 Diag(Loc, diag::warn_printf_invalid_conversion)
772 << std::string(Str+LastConversionIdx, Str+StrIdx)
773 << OrigFormatExpr->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000774
775 // This conversion is broken. Advance to the next format
776 // conversion.
777 LastConversionIdx = StrIdx;
778 ++numConversions;
Ted Kremenek71895b92007-08-14 17:39:48 +0000779 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000780 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000781
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000782 default:
783 // This case catches all other characters: flags, widths, etc.
784 // We should eventually process those as well.
785 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000786 }
787 }
788
789 if (CurrentState == state_Conversion) {
790 // Issue a warning: invalid format conversion.
Chris Lattner60800082009-02-18 17:49:48 +0000791 SourceLocation Loc =
792 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Ted Kremenek71895b92007-08-14 17:39:48 +0000793
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000794 Diag(Loc, diag::warn_printf_invalid_conversion)
795 << std::string(Str+LastConversionIdx,
796 Str+std::min(LastConversionIdx+2, StrLen))
797 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000798 return;
799 }
800
801 if (!HasVAListArg) {
802 // CHECK: Does the number of format conversions exceed the number
803 // of data arguments?
804 if (numConversions > numDataArgs) {
Chris Lattner60800082009-02-18 17:49:48 +0000805 SourceLocation Loc =
806 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Ted Kremenek71895b92007-08-14 17:39:48 +0000807
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000808 Diag(Loc, diag::warn_printf_insufficient_data_args)
809 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000810 }
811 // CHECK: Does the number of data arguments exceed the number of
812 // format conversions in the format string?
813 else if (numConversions < numDataArgs)
Chris Lattner925e60d2007-12-28 05:29:59 +0000814 Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000815 diag::warn_printf_too_many_data_args)
816 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000817 }
818}
Ted Kremenek06de2762007-08-17 16:46:58 +0000819
820//===--- CHECK: Return Address of Stack Variable --------------------------===//
821
822static DeclRefExpr* EvalVal(Expr *E);
823static DeclRefExpr* EvalAddr(Expr* E);
824
825/// CheckReturnStackAddr - Check if a return statement returns the address
826/// of a stack variable.
827void
828Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
829 SourceLocation ReturnLoc) {
Chris Lattner56f34942008-02-13 01:02:39 +0000830
Ted Kremenek06de2762007-08-17 16:46:58 +0000831 // Perform checking for returned stack addresses.
Steve Naroffdd972f22008-09-05 22:11:13 +0000832 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Ted Kremenek06de2762007-08-17 16:46:58 +0000833 if (DeclRefExpr *DR = EvalAddr(RetValExp))
Chris Lattner3c73c412008-11-19 08:23:25 +0000834 Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
Chris Lattner08631c52008-11-23 21:45:46 +0000835 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Steve Naroffc50a4a52008-09-16 22:25:10 +0000836
837 // Skip over implicit cast expressions when checking for block expressions.
838 if (ImplicitCastExpr *IcExpr =
839 dyn_cast_or_null<ImplicitCastExpr>(RetValExp))
840 RetValExp = IcExpr->getSubExpr();
841
Steve Naroff61f40a22008-09-10 19:17:48 +0000842 if (BlockExpr *C = dyn_cast_or_null<BlockExpr>(RetValExp))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000843 Diag(C->getLocStart(), diag::err_ret_local_block)
844 << C->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +0000845 }
846 // Perform checking for stack values returned by reference.
847 else if (lhsType->isReferenceType()) {
Douglas Gregor49badde2008-10-27 19:41:14 +0000848 // Check for a reference to the stack
849 if (DeclRefExpr *DR = EvalVal(RetValExp))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000850 Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
Chris Lattner08631c52008-11-23 21:45:46 +0000851 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +0000852 }
853}
854
855/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
856/// check if the expression in a return statement evaluates to an address
857/// to a location on the stack. The recursion is used to traverse the
858/// AST of the return expression, with recursion backtracking when we
859/// encounter a subexpression that (1) clearly does not lead to the address
860/// of a stack variable or (2) is something we cannot determine leads to
861/// the address of a stack variable based on such local checking.
862///
Ted Kremeneke8c600f2007-08-28 17:02:55 +0000863/// EvalAddr processes expressions that are pointers that are used as
864/// references (and not L-values). EvalVal handles all other values.
Ted Kremenek06de2762007-08-17 16:46:58 +0000865/// At the base case of the recursion is a check for a DeclRefExpr* in
866/// the refers to a stack variable.
867///
868/// This implementation handles:
869///
870/// * pointer-to-pointer casts
871/// * implicit conversions from array references to pointers
872/// * taking the address of fields
873/// * arbitrary interplay between "&" and "*" operators
874/// * pointer arithmetic from an address of a stack variable
875/// * taking the address of an array element where the array is on the stack
876static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek06de2762007-08-17 16:46:58 +0000877 // We should only be called for evaluating pointer expressions.
Steve Naroffdd972f22008-09-05 22:11:13 +0000878 assert((E->getType()->isPointerType() ||
879 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000880 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000881 "EvalAddr only works on pointers");
Ted Kremenek06de2762007-08-17 16:46:58 +0000882
883 // Our "symbolic interpreter" is just a dispatch off the currently
884 // viewed AST node. We then recursively traverse the AST by calling
885 // EvalAddr and EvalVal appropriately.
886 switch (E->getStmtClass()) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000887 case Stmt::ParenExprClass:
888 // Ignore parentheses.
889 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek06de2762007-08-17 16:46:58 +0000890
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000891 case Stmt::UnaryOperatorClass: {
892 // The only unary operator that make sense to handle here
893 // is AddrOf. All others don't make sense as pointers.
894 UnaryOperator *U = cast<UnaryOperator>(E);
Ted Kremenek06de2762007-08-17 16:46:58 +0000895
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000896 if (U->getOpcode() == UnaryOperator::AddrOf)
897 return EvalVal(U->getSubExpr());
898 else
Ted Kremenek06de2762007-08-17 16:46:58 +0000899 return NULL;
900 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000901
902 case Stmt::BinaryOperatorClass: {
903 // Handle pointer arithmetic. All other binary operators are not valid
904 // in this context.
905 BinaryOperator *B = cast<BinaryOperator>(E);
906 BinaryOperator::Opcode op = B->getOpcode();
907
908 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
909 return NULL;
910
911 Expr *Base = B->getLHS();
912
913 // Determine which argument is the real pointer base. It could be
914 // the RHS argument instead of the LHS.
915 if (!Base->getType()->isPointerType()) Base = B->getRHS();
916
917 assert (Base->getType()->isPointerType());
918 return EvalAddr(Base);
919 }
Steve Naroff61f40a22008-09-10 19:17:48 +0000920
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000921 // For conditional operators we need to see if either the LHS or RHS are
922 // valid DeclRefExpr*s. If one of them is valid, we return it.
923 case Stmt::ConditionalOperatorClass: {
924 ConditionalOperator *C = cast<ConditionalOperator>(E);
925
926 // Handle the GNU extension for missing LHS.
927 if (Expr *lhsExpr = C->getLHS())
928 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
929 return LHS;
930
931 return EvalAddr(C->getRHS());
932 }
933
Ted Kremenek54b52742008-08-07 00:49:01 +0000934 // For casts, we need to handle conversions from arrays to
935 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +0000936 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +0000937 case Stmt::CStyleCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +0000938 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +0000939 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +0000940 QualType T = SubExpr->getType();
941
Steve Naroffdd972f22008-09-05 22:11:13 +0000942 if (SubExpr->getType()->isPointerType() ||
943 SubExpr->getType()->isBlockPointerType() ||
944 SubExpr->getType()->isObjCQualifiedIdType())
Ted Kremenek54b52742008-08-07 00:49:01 +0000945 return EvalAddr(SubExpr);
946 else if (T->isArrayType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000947 return EvalVal(SubExpr);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000948 else
Ted Kremenek54b52742008-08-07 00:49:01 +0000949 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000950 }
951
952 // C++ casts. For dynamic casts, static casts, and const casts, we
953 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +0000954 // through the cast. In the case the dynamic cast doesn't fail (and
955 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000956 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +0000957 // FIXME: The comment about is wrong; we're not always converting
958 // from pointer to pointer. I'm guessing that this code should also
959 // handle references to objects.
960 case Stmt::CXXStaticCastExprClass:
961 case Stmt::CXXDynamicCastExprClass:
962 case Stmt::CXXConstCastExprClass:
963 case Stmt::CXXReinterpretCastExprClass: {
964 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +0000965 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000966 return EvalAddr(S);
967 else
968 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000969 }
970
971 // Everything else: we simply don't reason about them.
972 default:
973 return NULL;
974 }
Ted Kremenek06de2762007-08-17 16:46:58 +0000975}
976
977
978/// EvalVal - This function is complements EvalAddr in the mutual recursion.
979/// See the comments for EvalAddr for more details.
980static DeclRefExpr* EvalVal(Expr *E) {
981
Ted Kremeneke8c600f2007-08-28 17:02:55 +0000982 // We should only be called for evaluating non-pointer expressions, or
983 // expressions with a pointer type that are not used as references but instead
984 // are l-values (e.g., DeclRefExpr with a pointer type).
985
Ted Kremenek06de2762007-08-17 16:46:58 +0000986 // Our "symbolic interpreter" is just a dispatch off the currently
987 // viewed AST node. We then recursively traverse the AST by calling
988 // EvalAddr and EvalVal appropriately.
989 switch (E->getStmtClass()) {
Douglas Gregor1a49af92009-01-06 05:10:23 +0000990 case Stmt::DeclRefExprClass:
991 case Stmt::QualifiedDeclRefExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +0000992 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
993 // at code that refers to a variable's name. We check if it has local
994 // storage within the function, and if so, return the expression.
995 DeclRefExpr *DR = cast<DeclRefExpr>(E);
996
997 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000998 if(V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
Ted Kremenek06de2762007-08-17 16:46:58 +0000999
1000 return NULL;
1001 }
1002
1003 case Stmt::ParenExprClass:
1004 // Ignore parentheses.
1005 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
1006
1007 case Stmt::UnaryOperatorClass: {
1008 // The only unary operator that make sense to handle here
1009 // is Deref. All others don't resolve to a "name." This includes
1010 // handling all sorts of rvalues passed to a unary operator.
1011 UnaryOperator *U = cast<UnaryOperator>(E);
1012
1013 if (U->getOpcode() == UnaryOperator::Deref)
1014 return EvalAddr(U->getSubExpr());
1015
1016 return NULL;
1017 }
1018
1019 case Stmt::ArraySubscriptExprClass: {
1020 // Array subscripts are potential references to data on the stack. We
1021 // retrieve the DeclRefExpr* for the array variable if it indeed
1022 // has local storage.
Ted Kremenek23245122007-08-20 16:18:38 +00001023 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek06de2762007-08-17 16:46:58 +00001024 }
1025
1026 case Stmt::ConditionalOperatorClass: {
1027 // For conditional operators we need to see if either the LHS or RHS are
1028 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
1029 ConditionalOperator *C = cast<ConditionalOperator>(E);
1030
Anders Carlsson39073232007-11-30 19:04:31 +00001031 // Handle the GNU extension for missing LHS.
1032 if (Expr *lhsExpr = C->getLHS())
1033 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
1034 return LHS;
1035
1036 return EvalVal(C->getRHS());
Ted Kremenek06de2762007-08-17 16:46:58 +00001037 }
1038
1039 // Accesses to members are potential references to data on the stack.
1040 case Stmt::MemberExprClass: {
1041 MemberExpr *M = cast<MemberExpr>(E);
1042
1043 // Check for indirect access. We only want direct field accesses.
1044 if (!M->isArrow())
1045 return EvalVal(M->getBase());
1046 else
1047 return NULL;
1048 }
1049
1050 // Everything else: we simply don't reason about them.
1051 default:
1052 return NULL;
1053 }
1054}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001055
1056//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
1057
1058/// Check for comparisons of floating point operands using != and ==.
1059/// Issue a warning if these are no self-comparisons, as they are not likely
1060/// to do what the programmer intended.
1061void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
1062 bool EmitWarning = true;
1063
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00001064 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek32e97b62008-01-17 17:55:13 +00001065 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001066
1067 // Special case: check for x == x (which is OK).
1068 // Do not emit warnings for such cases.
1069 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
1070 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
1071 if (DRL->getDecl() == DRR->getDecl())
1072 EmitWarning = false;
1073
Ted Kremenek1b500bb2007-11-29 00:59:04 +00001074
1075 // Special case: check for comparisons against literals that can be exactly
1076 // represented by APFloat. In such cases, do not emit a warning. This
1077 // is a heuristic: often comparison against such literals are used to
1078 // detect if a value in a variable has not changed. This clearly can
1079 // lead to false negatives.
1080 if (EmitWarning) {
1081 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
1082 if (FLL->isExact())
1083 EmitWarning = false;
1084 }
1085 else
1086 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
1087 if (FLR->isExact())
1088 EmitWarning = false;
1089 }
1090 }
1091
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001092 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001093 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001094 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001095 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001096 EmitWarning = false;
1097
Sebastian Redl0eb23302009-01-19 00:08:26 +00001098 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001099 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001100 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001101 EmitWarning = false;
1102
1103 // Emit the diagnostic.
1104 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001105 Diag(loc, diag::warn_floatingpoint_eq)
1106 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001107}