blob: d2aec65cef20da8efc070a118d44a99eb836601c [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
35 // Loop over all of the tokens in this string until we find the one that
36 // contains the byte we're looking for.
37 unsigned TokNo = 0;
38 while (1) {
39 assert(TokNo < SL->getNumConcatenated() && "Invalid byte number!");
40 SourceLocation StrTokLoc = SL->getStrTokenLoc(TokNo);
41
42 // Get the spelling of the string so that we can get the data that makes up
43 // the string literal, not the identifier for the macro it is potentially
44 // expanded through.
45 SourceLocation StrTokSpellingLoc = SourceMgr.getSpellingLoc(StrTokLoc);
46
47 // Re-lex the token to get its length and original spelling.
48 std::pair<FileID, unsigned> LocInfo =
49 SourceMgr.getDecomposedLoc(StrTokSpellingLoc);
50 std::pair<const char *,const char *> Buffer =
51 SourceMgr.getBufferData(LocInfo.first);
52 const char *StrData = Buffer.first+LocInfo.second;
53
54 // Create a langops struct and enable trigraphs. This is sufficient for
55 // relexing tokens.
56 LangOptions LangOpts;
57 LangOpts.Trigraphs = true;
58
59 // Create a lexer starting at the beginning of this token.
60 Lexer TheLexer(StrTokSpellingLoc, LangOpts, Buffer.first, StrData,
61 Buffer.second);
62 Token TheTok;
63 TheLexer.LexFromRawLexer(TheTok);
64
Chris Lattner443e53c2009-02-18 19:26:42 +000065 // Use the StringLiteralParser to compute the length of the string in bytes.
66 StringLiteralParser SLP(&TheTok, 1, PP);
67 unsigned TokNumBytes = SLP.GetStringLength();
Chris Lattnerd0d082f2009-02-18 18:34:12 +000068
Chris Lattner2197c962009-02-18 18:52:52 +000069 // If the byte is in this token, return the location of the byte.
Chris Lattner60800082009-02-18 17:49:48 +000070 if (ByteNo < TokNumBytes ||
71 (ByteNo == TokNumBytes && TokNo == SL->getNumConcatenated())) {
Chris Lattner719e6152009-02-18 19:21:10 +000072 unsigned Offset =
73 StringLiteralParser::getOffsetOfStringByte(TheTok, ByteNo, PP);
74
75 // Now that we know the offset of the token in the spelling, use the
76 // preprocessor to get the offset in the original source.
77 return PP.AdvanceToTokenCharacter(StrTokLoc, Offset);
Chris Lattner60800082009-02-18 17:49:48 +000078 }
79
80 // Move to the next string token.
81 ++TokNo;
82 ByteNo -= TokNumBytes;
83 }
84}
85
86
Chris Lattner59907c42007-08-10 20:18:51 +000087/// CheckFunctionCall - Check a direct function call for various correctness
88/// and safety properties not strictly enforced by the C type system.
Sebastian Redl0eb23302009-01-19 00:08:26 +000089Action::OwningExprResult
90Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
91 OwningExprResult TheCallResult(Owned(TheCall));
Chris Lattner59907c42007-08-10 20:18:51 +000092 // Get the IdentifierInfo* for the called function.
93 IdentifierInfo *FnInfo = FDecl->getIdentifier();
Douglas Gregor2def4832008-11-17 20:34:05 +000094
95 // None of the checks below are needed for functions that don't have
96 // simple names (e.g., C++ conversion functions).
97 if (!FnInfo)
Sebastian Redl0eb23302009-01-19 00:08:26 +000098 return move(TheCallResult);
Douglas Gregor2def4832008-11-17 20:34:05 +000099
Douglas Gregor3c385e52009-02-14 18:57:46 +0000100 switch (FDecl->getBuiltinID(Context)) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000101 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000102 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000103 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000104 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000105 return ExprError();
106 return move(TheCallResult);
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000107 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000108 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000109 if (SemaBuiltinVAStart(TheCall))
110 return ExprError();
111 return move(TheCallResult);
Chris Lattner1b9a0792007-12-20 00:26:33 +0000112 case Builtin::BI__builtin_isgreater:
113 case Builtin::BI__builtin_isgreaterequal:
114 case Builtin::BI__builtin_isless:
115 case Builtin::BI__builtin_islessequal:
116 case Builtin::BI__builtin_islessgreater:
117 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000118 if (SemaBuiltinUnorderedCompare(TheCall))
119 return ExprError();
120 return move(TheCallResult);
Eli Friedman6cfda232008-05-20 08:23:37 +0000121 case Builtin::BI__builtin_return_address:
122 case Builtin::BI__builtin_frame_address:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000123 if (SemaBuiltinStackAddress(TheCall))
124 return ExprError();
125 return move(TheCallResult);
Eli Friedmand38617c2008-05-14 19:38:39 +0000126 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000127 return SemaBuiltinShuffleVector(TheCall);
128 // TheCall will be freed by the smart pointer here, but that's fine, since
129 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000130 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000131 if (SemaBuiltinPrefetch(TheCall))
132 return ExprError();
133 return move(TheCallResult);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000134 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000135 if (SemaBuiltinObjectSize(TheCall))
136 return ExprError();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000137 }
Daniel Dunbarde454282008-10-02 18:44:07 +0000138
139 // FIXME: This mechanism should be abstracted to be less fragile and
140 // more efficient. For example, just map function ids to custom
141 // handlers.
142
Chris Lattner59907c42007-08-10 20:18:51 +0000143 // Printf checking.
Douglas Gregor3c385e52009-02-14 18:57:46 +0000144 if (const FormatAttr *Format = FDecl->getAttr<FormatAttr>()) {
145 if (Format->getType() == "printf") {
Ted Kremenek3d692df2009-02-27 17:58:43 +0000146 bool HasVAListArg = Format->getFirstArg() == 0;
147 if (!HasVAListArg) {
148 if (const FunctionProtoType *Proto
149 = FDecl->getType()->getAsFunctionProtoType())
Douglas Gregor3c385e52009-02-14 18:57:46 +0000150 HasVAListArg = !Proto->isVariadic();
Ted Kremenek3d692df2009-02-27 17:58:43 +0000151 }
Douglas Gregor3c385e52009-02-14 18:57:46 +0000152 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
Ted Kremenek3d692df2009-02-27 17:58:43 +0000153 HasVAListArg ? 0 : Format->getFirstArg() - 1);
Douglas Gregor3c385e52009-02-14 18:57:46 +0000154 }
Chris Lattner59907c42007-08-10 20:18:51 +0000155 }
Sebastian Redl0eb23302009-01-19 00:08:26 +0000156
157 return move(TheCallResult);
Anders Carlsson71993dd2007-08-17 05:31:46 +0000158}
159
Chris Lattner69039812009-02-18 06:01:06 +0000160/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000161/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +0000162/// FIXME: GCC currently emits the following warning:
163/// "warning: input conversion stopped due to an input byte that does not
164/// belong to the input codeset UTF-8"
165/// Note: It might also make sense to do the UTF-16 conversion here (would
166/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +0000167bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000168 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000169 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
170
171 if (!Literal || Literal->isWide()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000172 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
173 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000174 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000175 }
176
177 const char *Data = Literal->getStrData();
178 unsigned Length = Literal->getByteLength();
179
180 for (unsigned i = 0; i < Length; ++i) {
Anders Carlsson71993dd2007-08-17 05:31:46 +0000181 if (!Data[i]) {
Chris Lattner60800082009-02-18 17:49:48 +0000182 Diag(getLocationOfStringLiteralByte(Literal, i),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000183 diag::warn_cfstring_literal_contains_nul_character)
184 << Arg->getSourceRange();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000185 break;
186 }
187 }
188
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000189 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000190}
191
Chris Lattnerc27c6652007-12-20 00:05:45 +0000192/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
193/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000194bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
195 Expr *Fn = TheCall->getCallee();
196 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000197 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000198 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000199 << 0 /*function call*/ << Fn->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000200 << SourceRange(TheCall->getArg(2)->getLocStart(),
201 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000202 return true;
203 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000204
205 if (TheCall->getNumArgs() < 2) {
206 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
207 << 0 /*function call*/;
208 }
209
Chris Lattnerc27c6652007-12-20 00:05:45 +0000210 // Determine whether the current function is variadic or not.
211 bool isVariadic;
Eli Friedman56f20ae2008-12-15 22:05:35 +0000212 if (getCurFunctionDecl()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000213 if (FunctionProtoType* FTP =
214 dyn_cast<FunctionProtoType>(getCurFunctionDecl()->getType()))
Eli Friedman56f20ae2008-12-15 22:05:35 +0000215 isVariadic = FTP->isVariadic();
216 else
217 isVariadic = false;
218 } else {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000219 isVariadic = getCurMethodDecl()->isVariadic();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000220 }
Chris Lattner30ce3442007-12-19 23:59:04 +0000221
Chris Lattnerc27c6652007-12-20 00:05:45 +0000222 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000223 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
224 return true;
225 }
226
227 // Verify that the second argument to the builtin is the last argument of the
228 // current function or method.
229 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000230 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Anders Carlsson88cf2262008-02-11 04:20:54 +0000231
232 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
233 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000234 // FIXME: This isn't correct for methods (results in bogus warning).
235 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000236 const ParmVarDecl *LastArg;
Chris Lattner371f2582008-12-04 23:50:19 +0000237 if (FunctionDecl *FD = getCurFunctionDecl())
238 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000239 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000240 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000241 SecondArgIsLastNamedArgument = PV == LastArg;
242 }
243 }
244
245 if (!SecondArgIsLastNamedArgument)
Chris Lattner925e60d2007-12-28 05:29:59 +0000246 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000247 diag::warn_second_parameter_of_va_start_not_last_named_argument);
248 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000249}
Chris Lattner30ce3442007-12-19 23:59:04 +0000250
Chris Lattner1b9a0792007-12-20 00:26:33 +0000251/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
252/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000253bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
254 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000255 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
256 << 0 /*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000257 if (TheCall->getNumArgs() > 2)
258 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000259 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000260 << 0 /*function call*/
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000261 << SourceRange(TheCall->getArg(2)->getLocStart(),
262 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner1b9a0792007-12-20 00:26:33 +0000263
Chris Lattner925e60d2007-12-28 05:29:59 +0000264 Expr *OrigArg0 = TheCall->getArg(0);
265 Expr *OrigArg1 = TheCall->getArg(1);
Chris Lattner1b9a0792007-12-20 00:26:33 +0000266
267 // Do standard promotions between the two arguments, returning their common
268 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000269 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Daniel Dunbar403bc2b2009-02-19 19:28:43 +0000270
271 // Make sure any conversions are pushed back into the call; this is
272 // type safe since unordered compare builtins are declared as "_Bool
273 // foo(...)".
274 TheCall->setArg(0, OrigArg0);
275 TheCall->setArg(1, OrigArg1);
Chris Lattner1b9a0792007-12-20 00:26:33 +0000276
277 // If the common type isn't a real floating type, then the arguments were
278 // invalid for this operation.
279 if (!Res->isRealFloatingType())
Chris Lattner925e60d2007-12-28 05:29:59 +0000280 return Diag(OrigArg0->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000281 diag::err_typecheck_call_invalid_ordered_compare)
Chris Lattnerd1625842008-11-24 06:25:27 +0000282 << OrigArg0->getType() << OrigArg1->getType()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000283 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
Chris Lattner1b9a0792007-12-20 00:26:33 +0000284
285 return false;
286}
287
Eli Friedman6cfda232008-05-20 08:23:37 +0000288bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) {
289 // The signature for these builtins is exact; the only thing we need
290 // to check is that the argument is a constant.
291 SourceLocation Loc;
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000292 if (!TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc))
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000293 return Diag(Loc, diag::err_stack_const_level) << TheCall->getSourceRange();
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000294
Eli Friedman6cfda232008-05-20 08:23:37 +0000295 return false;
296}
297
Eli Friedmand38617c2008-05-14 19:38:39 +0000298/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
299// This is declared to take (...), so we have to check everything.
Sebastian Redl0eb23302009-01-19 00:08:26 +0000300Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000301 if (TheCall->getNumArgs() < 3)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000302 return ExprError(Diag(TheCall->getLocEnd(),
303 diag::err_typecheck_call_too_few_args)
304 << 0 /*function call*/ << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000305
306 QualType FAType = TheCall->getArg(0)->getType();
307 QualType SAType = TheCall->getArg(1)->getType();
308
309 if (!FAType->isVectorType() || !SAType->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000310 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
311 << SourceRange(TheCall->getArg(0)->getLocStart(),
312 TheCall->getArg(1)->getLocEnd());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000313 return ExprError();
Eli Friedmand38617c2008-05-14 19:38:39 +0000314 }
315
Chris Lattnerb77792e2008-07-26 22:17:49 +0000316 if (Context.getCanonicalType(FAType).getUnqualifiedType() !=
317 Context.getCanonicalType(SAType).getUnqualifiedType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000318 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
319 << SourceRange(TheCall->getArg(0)->getLocStart(),
320 TheCall->getArg(1)->getLocEnd());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000321 return ExprError();
Eli Friedmand38617c2008-05-14 19:38:39 +0000322 }
323
324 unsigned numElements = FAType->getAsVectorType()->getNumElements();
325 if (TheCall->getNumArgs() != numElements+2) {
326 if (TheCall->getNumArgs() < numElements+2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000327 return ExprError(Diag(TheCall->getLocEnd(),
328 diag::err_typecheck_call_too_few_args)
329 << 0 /*function call*/ << TheCall->getSourceRange());
330 return ExprError(Diag(TheCall->getLocEnd(),
331 diag::err_typecheck_call_too_many_args)
332 << 0 /*function call*/ << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000333 }
334
335 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
336 llvm::APSInt Result(32);
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000337 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000338 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000339 diag::err_shufflevector_nonconstant_argument)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000340 << TheCall->getArg(i)->getSourceRange());
341
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000342 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000343 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000344 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000345 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000346 }
347
348 llvm::SmallVector<Expr*, 32> exprs;
349
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000350 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000351 exprs.push_back(TheCall->getArg(i));
352 TheCall->setArg(i, 0);
353 }
354
Ted Kremenek8189cde2009-02-07 01:47:29 +0000355 return Owned(new (Context) ShuffleVectorExpr(exprs.begin(), numElements+2,
356 FAType,
357 TheCall->getCallee()->getLocStart(),
358 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000359}
Chris Lattner30ce3442007-12-19 23:59:04 +0000360
Daniel Dunbar4493f792008-07-21 22:59:13 +0000361/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
362// This is declared to take (const void*, ...) and can take two
363// optional constant int args.
364bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000365 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000366
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000367 if (NumArgs > 3)
368 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000369 << 0 /*function call*/ << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000370
371 // Argument 0 is checked for us and the remaining arguments must be
372 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000373 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000374 Expr *Arg = TheCall->getArg(i);
375 QualType RWType = Arg->getType();
376
377 const BuiltinType *BT = RWType->getAsBuiltinType();
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000378 llvm::APSInt Result;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000379 if (!BT || BT->getKind() != BuiltinType::Int ||
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000380 !Arg->isIntegerConstantExpr(Result, Context))
381 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument)
382 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar4493f792008-07-21 22:59:13 +0000383
384 // FIXME: gcc issues a warning and rewrites these to 0. These
385 // seems especially odd for the third argument since the default
386 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000387 if (i == 1) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000388 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000389 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
390 << "0" << "1" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar4493f792008-07-21 22:59:13 +0000391 } else {
392 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000393 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
394 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar4493f792008-07-21 22:59:13 +0000395 }
396 }
397
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000398 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000399}
400
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000401/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
402/// int type). This simply type checks that type is one of the defined
403/// constants (0-3).
404bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
405 Expr *Arg = TheCall->getArg(1);
406 QualType ArgType = Arg->getType();
407 const BuiltinType *BT = ArgType->getAsBuiltinType();
408 llvm::APSInt Result(32);
409 if (!BT || BT->getKind() != BuiltinType::Int ||
410 !Arg->isIntegerConstantExpr(Result, Context)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000411 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
412 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000413 }
414
415 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000416 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
417 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000418 }
419
420 return false;
421}
422
Ted Kremenekd30ef872009-01-12 23:09:09 +0000423// Handle i > 1 ? "x" : "y", recursivelly
Ted Kremenek082d9362009-03-20 21:35:28 +0000424bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
425 bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000426 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenekd30ef872009-01-12 23:09:09 +0000427
428 switch (E->getStmtClass()) {
429 case Stmt::ConditionalOperatorClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000430 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000431 return SemaCheckStringLiteral(C->getLHS(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000432 HasVAListArg, format_idx, firstDataArg)
Ted Kremenekd30ef872009-01-12 23:09:09 +0000433 && SemaCheckStringLiteral(C->getRHS(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000434 HasVAListArg, format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000435 }
436
437 case Stmt::ImplicitCastExprClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000438 const ImplicitCastExpr *Expr = cast<ImplicitCastExpr>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000439 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000440 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000441 }
442
443 case Stmt::ParenExprClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000444 const ParenExpr *Expr = cast<ParenExpr>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000445 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 }
Ted Kremenek082d9362009-03-20 21:35:28 +0000448
449 case Stmt::DeclRefExprClass: {
450 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
451
452 // As an exception, do not flag errors for variables binding to
453 // const string literals.
454 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
455 bool isConstant = false;
456 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +0000457
Ted Kremenek082d9362009-03-20 21:35:28 +0000458 if (const ArrayType *AT = Context.getAsArrayType(T)) {
459 isConstant = AT->getElementType().isConstant(Context);
460 }
461 else if (const PointerType *PT = T->getAsPointerType()) {
462 isConstant = T.isConstant(Context) &&
463 PT->getPointeeType().isConstant(Context);
464 }
465
466 if (isConstant) {
467 const VarDecl *Def = 0;
468 if (const Expr *Init = VD->getDefinition(Def))
469 return SemaCheckStringLiteral(Init, TheCall,
470 HasVAListArg, format_idx, firstDataArg);
471 }
472 }
473
474 return false;
475 }
Ted Kremenekd30ef872009-01-12 23:09:09 +0000476
Ted Kremenek082d9362009-03-20 21:35:28 +0000477 case Stmt::ObjCStringLiteralClass:
478 case Stmt::StringLiteralClass: {
479 const StringLiteral *StrE = NULL;
480
481 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +0000482 StrE = ObjCFExpr->getString();
483 else
Ted Kremenek082d9362009-03-20 21:35:28 +0000484 StrE = cast<StringLiteral>(E);
485
Ted Kremenekd30ef872009-01-12 23:09:09 +0000486 if (StrE) {
Douglas Gregor3c385e52009-02-14 18:57:46 +0000487 CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx,
488 firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000489 return true;
490 }
491
492 return false;
493 }
Ted Kremenek082d9362009-03-20 21:35:28 +0000494
495 default:
496 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000497 }
498}
499
500
Chris Lattner59907c42007-08-10 20:18:51 +0000501/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Ted Kremenek71895b92007-08-14 17:39:48 +0000502/// correct use of format strings.
503///
504/// HasVAListArg - A predicate indicating whether the printf-like
505/// function is passed an explicit va_arg argument (e.g., vprintf)
506///
507/// format_idx - The index into Args for the format string.
508///
509/// Improper format strings to functions in the printf family can be
510/// the source of bizarre bugs and very serious security holes. A
511/// good source of information is available in the following paper
512/// (which includes additional references):
Chris Lattner59907c42007-08-10 20:18:51 +0000513///
514/// FormatGuard: Automatic Protection From printf Format String
515/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremenek71895b92007-08-14 17:39:48 +0000516///
517/// Functionality implemented:
518///
519/// We can statically check the following properties for string
520/// literal format strings for non v.*printf functions (where the
521/// arguments are passed directly):
522//
523/// (1) Are the number of format conversions equal to the number of
524/// data arguments?
525///
526/// (2) Does each format conversion correctly match the type of the
527/// corresponding data argument? (TODO)
528///
529/// Moreover, for all printf functions we can:
530///
531/// (3) Check for a missing format string (when not caught by type checking).
532///
533/// (4) Check for no-operation flags; e.g. using "#" with format
534/// conversion 'c' (TODO)
535///
536/// (5) Check the use of '%n', a major source of security holes.
537///
538/// (6) Check for malformed format conversions that don't specify anything.
539///
540/// (7) Check for empty format strings. e.g: printf("");
541///
542/// (8) Check that the format string is a wide literal.
543///
Ted Kremenek6d439592008-03-03 16:50:00 +0000544/// (9) Also check the arguments of functions with the __format__ attribute.
545/// (TODO).
546///
Ted Kremenek71895b92007-08-14 17:39:48 +0000547/// All of these checks can be done by parsing the format string.
548///
549/// For now, we ONLY do (1), (3), (5), (6), (7), and (8).
Chris Lattner59907c42007-08-10 20:18:51 +0000550void
Ted Kremenek082d9362009-03-20 21:35:28 +0000551Sema::CheckPrintfArguments(const CallExpr *TheCall, bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000552 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenek082d9362009-03-20 21:35:28 +0000553 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +0000554
Ted Kremenek71895b92007-08-14 17:39:48 +0000555 // CHECK: printf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +0000556 if (format_idx >= TheCall->getNumArgs()) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000557 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string)
558 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000559 return;
560 }
561
Ted Kremenek082d9362009-03-20 21:35:28 +0000562 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Chris Lattner459e8482007-08-25 05:36:18 +0000563
Chris Lattner59907c42007-08-10 20:18:51 +0000564 // CHECK: format string is not a string literal.
565 //
Ted Kremenek71895b92007-08-14 17:39:48 +0000566 // Dynamically generated format strings are difficult to
567 // automatically vet at compile time. Requiring that format strings
568 // are string literals: (1) permits the checking of format strings by
569 // the compiler and thereby (2) can practically remove the source of
570 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000571
572 // Format string can be either ObjC string (e.g. @"%d") or
573 // C string (e.g. "%d")
574 // ObjC string uses the same format specifiers as C string, so we can use
575 // the same format string checking logic for both ObjC and C strings.
Douglas Gregor3c385e52009-02-14 18:57:46 +0000576 bool isFExpr = SemaCheckStringLiteral(OrigFormatExpr, TheCall,
577 HasVAListArg, format_idx,
578 firstDataArg);
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000579
Ted Kremenekd30ef872009-01-12 23:09:09 +0000580 if (!isFExpr) {
Ted Kremenek4a336462007-12-17 19:03:13 +0000581 // For vprintf* functions (i.e., HasVAListArg==true), we add a
582 // special check to see if the format string is a function parameter
583 // of the function calling the printf function. If the function
584 // has an attribute indicating it is a printf-like function, then we
585 // should suppress warnings concerning non-literals being used in a call
586 // to a vprintf function. For example:
587 //
588 // void
589 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...) {
590 // va_list ap;
591 // va_start(ap, fmt);
592 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
593 // ...
594 //
595 //
596 // FIXME: We don't have full attribute support yet, so just check to see
597 // if the argument is a DeclRefExpr that references a parameter. We'll
598 // add proper support for checking the attribute later.
599 if (HasVAListArg)
Ted Kremenek082d9362009-03-20 21:35:28 +0000600 if (const DeclRefExpr* DR = dyn_cast<DeclRefExpr>(OrigFormatExpr))
Chris Lattner998568f2007-12-28 05:38:24 +0000601 if (isa<ParmVarDecl>(DR->getDecl()))
Ted Kremenek4a336462007-12-17 19:03:13 +0000602 return;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000603
Chris Lattner925e60d2007-12-28 05:29:59 +0000604 Diag(TheCall->getArg(format_idx)->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000605 diag::warn_printf_not_string_constant)
Ted Kremenek082d9362009-03-20 21:35:28 +0000606 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000607 return;
608 }
Ted Kremenekd30ef872009-01-12 23:09:09 +0000609}
Ted Kremenek71895b92007-08-14 17:39:48 +0000610
Ted Kremenek082d9362009-03-20 21:35:28 +0000611void Sema::CheckPrintfString(const StringLiteral *FExpr,
612 const Expr *OrigFormatExpr,
613 const CallExpr *TheCall, bool HasVAListArg,
614 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenekd30ef872009-01-12 23:09:09 +0000615
Ted Kremenek082d9362009-03-20 21:35:28 +0000616 const ObjCStringLiteral *ObjCFExpr =
617 dyn_cast<ObjCStringLiteral>(OrigFormatExpr);
618
Ted Kremenek71895b92007-08-14 17:39:48 +0000619 // CHECK: is the format string a wide literal?
620 if (FExpr->isWide()) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000621 Diag(FExpr->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000622 diag::warn_printf_format_string_is_wide_literal)
623 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000624 return;
625 }
626
627 // Str - The format string. NOTE: this is NOT null-terminated!
628 const char * const Str = FExpr->getStrData();
629
630 // CHECK: empty format string?
631 const unsigned StrLen = FExpr->getByteLength();
632
633 if (StrLen == 0) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000634 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string)
635 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000636 return;
637 }
638
639 // We process the format string using a binary state machine. The
640 // current state is stored in CurrentState.
641 enum {
642 state_OrdChr,
643 state_Conversion
644 } CurrentState = state_OrdChr;
645
646 // numConversions - The number of conversions seen so far. This is
647 // incremented as we traverse the format string.
648 unsigned numConversions = 0;
649
650 // numDataArgs - The number of data arguments after the format
651 // string. This can only be determined for non vprintf-like
652 // functions. For those functions, this value is 1 (the sole
653 // va_arg argument).
Douglas Gregor3c385e52009-02-14 18:57:46 +0000654 unsigned numDataArgs = TheCall->getNumArgs()-firstDataArg;
Ted Kremenek71895b92007-08-14 17:39:48 +0000655
656 // Inspect the format string.
657 unsigned StrIdx = 0;
658
659 // LastConversionIdx - Index within the format string where we last saw
660 // a '%' character that starts a new format conversion.
661 unsigned LastConversionIdx = 0;
662
Chris Lattner925e60d2007-12-28 05:29:59 +0000663 for (; StrIdx < StrLen; ++StrIdx) {
Chris Lattner998568f2007-12-28 05:38:24 +0000664
Ted Kremenek71895b92007-08-14 17:39:48 +0000665 // Is the number of detected conversion conversions greater than
666 // the number of matching data arguments? If so, stop.
667 if (!HasVAListArg && numConversions > numDataArgs) break;
668
669 // Handle "\0"
Chris Lattner925e60d2007-12-28 05:29:59 +0000670 if (Str[StrIdx] == '\0') {
Ted Kremenek71895b92007-08-14 17:39:48 +0000671 // The string returned by getStrData() is not null-terminated,
672 // so the presence of a null character is likely an error.
Chris Lattner60800082009-02-18 17:49:48 +0000673 Diag(getLocationOfStringLiteralByte(FExpr, StrIdx),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000674 diag::warn_printf_format_string_contains_null_char)
675 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000676 return;
677 }
678
679 // Ordinary characters (not processing a format conversion).
680 if (CurrentState == state_OrdChr) {
681 if (Str[StrIdx] == '%') {
682 CurrentState = state_Conversion;
683 LastConversionIdx = StrIdx;
684 }
685 continue;
686 }
687
688 // Seen '%'. Now processing a format conversion.
689 switch (Str[StrIdx]) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000690 // Handle dynamic precision or width specifier.
691 case '*': {
692 ++numConversions;
693
694 if (!HasVAListArg && numConversions > numDataArgs) {
Chris Lattner60800082009-02-18 17:49:48 +0000695 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx);
Ted Kremenek580b6642007-10-12 20:51:52 +0000696
Ted Kremenek580b6642007-10-12 20:51:52 +0000697 if (Str[StrIdx-1] == '.')
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000698 Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg)
699 << OrigFormatExpr->getSourceRange();
Ted Kremenek580b6642007-10-12 20:51:52 +0000700 else
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000701 Diag(Loc, diag::warn_printf_asterisk_width_missing_arg)
702 << OrigFormatExpr->getSourceRange();
Ted Kremenek580b6642007-10-12 20:51:52 +0000703
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000704 // Don't do any more checking. We'll just emit spurious errors.
705 return;
Ted Kremenek580b6642007-10-12 20:51:52 +0000706 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000707
708 // Perform type checking on width/precision specifier.
Ted Kremenek082d9362009-03-20 21:35:28 +0000709 const Expr *E = TheCall->getArg(format_idx+numConversions);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000710 if (const BuiltinType *BT = E->getType()->getAsBuiltinType())
711 if (BT->getKind() == BuiltinType::Int)
712 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000713
Chris Lattner60800082009-02-18 17:49:48 +0000714 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000715
716 if (Str[StrIdx-1] == '.')
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000717 Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000718 << E->getType() << E->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000719 else
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000720 Diag(Loc, diag::warn_printf_asterisk_width_wrong_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000721 << E->getType() << E->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000722
723 break;
724 }
725
726 // Characters which can terminate a format conversion
727 // (e.g. "%d"). Characters that specify length modifiers or
728 // other flags are handled by the default case below.
729 //
730 // FIXME: additional checks will go into the following cases.
731 case 'i':
732 case 'd':
733 case 'o':
734 case 'u':
735 case 'x':
736 case 'X':
737 case 'D':
738 case 'O':
739 case 'U':
740 case 'e':
741 case 'E':
742 case 'f':
743 case 'F':
744 case 'g':
745 case 'G':
746 case 'a':
747 case 'A':
748 case 'c':
749 case 'C':
750 case 'S':
751 case 's':
752 case 'p':
753 ++numConversions;
754 CurrentState = state_OrdChr;
755 break;
756
757 // CHECK: Are we using "%n"? Issue a warning.
758 case 'n': {
759 ++numConversions;
760 CurrentState = state_OrdChr;
Chris Lattner60800082009-02-18 17:49:48 +0000761 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr,
762 LastConversionIdx);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000763
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000764 Diag(Loc, diag::warn_printf_write_back)<<OrigFormatExpr->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000765 break;
766 }
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000767
768 // Handle "%@"
769 case '@':
770 // %@ is allowed in ObjC format strings only.
771 if(ObjCFExpr != NULL)
772 CurrentState = state_OrdChr;
773 else {
774 // Issue a warning: invalid format conversion.
Chris Lattner60800082009-02-18 17:49:48 +0000775 SourceLocation Loc =
776 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000777
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000778 Diag(Loc, diag::warn_printf_invalid_conversion)
779 << std::string(Str+LastConversionIdx,
780 Str+std::min(LastConversionIdx+2, StrLen))
781 << OrigFormatExpr->getSourceRange();
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000782 }
783 ++numConversions;
784 break;
785
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000786 // Handle "%%"
787 case '%':
788 // Sanity check: Was the first "%" character the previous one?
789 // If not, we will assume that we have a malformed format
790 // conversion, and that the current "%" character is the start
791 // of a new conversion.
792 if (StrIdx - LastConversionIdx == 1)
793 CurrentState = state_OrdChr;
794 else {
795 // Issue a warning: invalid format conversion.
Chris Lattner60800082009-02-18 17:49:48 +0000796 SourceLocation Loc =
797 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000798
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000799 Diag(Loc, diag::warn_printf_invalid_conversion)
800 << std::string(Str+LastConversionIdx, Str+StrIdx)
801 << OrigFormatExpr->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000802
803 // This conversion is broken. Advance to the next format
804 // conversion.
805 LastConversionIdx = StrIdx;
806 ++numConversions;
Ted Kremenek71895b92007-08-14 17:39:48 +0000807 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000808 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000809
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000810 default:
811 // This case catches all other characters: flags, widths, etc.
812 // We should eventually process those as well.
813 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000814 }
815 }
816
817 if (CurrentState == state_Conversion) {
818 // Issue a warning: invalid format conversion.
Chris Lattner60800082009-02-18 17:49:48 +0000819 SourceLocation Loc =
820 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Ted Kremenek71895b92007-08-14 17:39:48 +0000821
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000822 Diag(Loc, diag::warn_printf_invalid_conversion)
823 << std::string(Str+LastConversionIdx,
824 Str+std::min(LastConversionIdx+2, StrLen))
825 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000826 return;
827 }
828
829 if (!HasVAListArg) {
830 // CHECK: Does the number of format conversions exceed the number
831 // of data arguments?
832 if (numConversions > numDataArgs) {
Chris Lattner60800082009-02-18 17:49:48 +0000833 SourceLocation Loc =
834 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Ted Kremenek71895b92007-08-14 17:39:48 +0000835
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000836 Diag(Loc, diag::warn_printf_insufficient_data_args)
837 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000838 }
839 // CHECK: Does the number of data arguments exceed the number of
840 // format conversions in the format string?
841 else if (numConversions < numDataArgs)
Chris Lattner925e60d2007-12-28 05:29:59 +0000842 Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000843 diag::warn_printf_too_many_data_args)
844 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000845 }
846}
Ted Kremenek06de2762007-08-17 16:46:58 +0000847
848//===--- CHECK: Return Address of Stack Variable --------------------------===//
849
850static DeclRefExpr* EvalVal(Expr *E);
851static DeclRefExpr* EvalAddr(Expr* E);
852
853/// CheckReturnStackAddr - Check if a return statement returns the address
854/// of a stack variable.
855void
856Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
857 SourceLocation ReturnLoc) {
Chris Lattner56f34942008-02-13 01:02:39 +0000858
Ted Kremenek06de2762007-08-17 16:46:58 +0000859 // Perform checking for returned stack addresses.
Steve Naroffdd972f22008-09-05 22:11:13 +0000860 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Ted Kremenek06de2762007-08-17 16:46:58 +0000861 if (DeclRefExpr *DR = EvalAddr(RetValExp))
Chris Lattner3c73c412008-11-19 08:23:25 +0000862 Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
Chris Lattner08631c52008-11-23 21:45:46 +0000863 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Steve Naroffc50a4a52008-09-16 22:25:10 +0000864
865 // Skip over implicit cast expressions when checking for block expressions.
866 if (ImplicitCastExpr *IcExpr =
867 dyn_cast_or_null<ImplicitCastExpr>(RetValExp))
868 RetValExp = IcExpr->getSubExpr();
869
Steve Naroff61f40a22008-09-10 19:17:48 +0000870 if (BlockExpr *C = dyn_cast_or_null<BlockExpr>(RetValExp))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000871 Diag(C->getLocStart(), diag::err_ret_local_block)
872 << C->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +0000873 }
874 // Perform checking for stack values returned by reference.
875 else if (lhsType->isReferenceType()) {
Douglas Gregor49badde2008-10-27 19:41:14 +0000876 // Check for a reference to the stack
877 if (DeclRefExpr *DR = EvalVal(RetValExp))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000878 Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
Chris Lattner08631c52008-11-23 21:45:46 +0000879 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +0000880 }
881}
882
883/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
884/// check if the expression in a return statement evaluates to an address
885/// to a location on the stack. The recursion is used to traverse the
886/// AST of the return expression, with recursion backtracking when we
887/// encounter a subexpression that (1) clearly does not lead to the address
888/// of a stack variable or (2) is something we cannot determine leads to
889/// the address of a stack variable based on such local checking.
890///
Ted Kremeneke8c600f2007-08-28 17:02:55 +0000891/// EvalAddr processes expressions that are pointers that are used as
892/// references (and not L-values). EvalVal handles all other values.
Ted Kremenek06de2762007-08-17 16:46:58 +0000893/// At the base case of the recursion is a check for a DeclRefExpr* in
894/// the refers to a stack variable.
895///
896/// This implementation handles:
897///
898/// * pointer-to-pointer casts
899/// * implicit conversions from array references to pointers
900/// * taking the address of fields
901/// * arbitrary interplay between "&" and "*" operators
902/// * pointer arithmetic from an address of a stack variable
903/// * taking the address of an array element where the array is on the stack
904static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek06de2762007-08-17 16:46:58 +0000905 // We should only be called for evaluating pointer expressions.
Steve Naroffdd972f22008-09-05 22:11:13 +0000906 assert((E->getType()->isPointerType() ||
907 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000908 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000909 "EvalAddr only works on pointers");
Ted Kremenek06de2762007-08-17 16:46:58 +0000910
911 // Our "symbolic interpreter" is just a dispatch off the currently
912 // viewed AST node. We then recursively traverse the AST by calling
913 // EvalAddr and EvalVal appropriately.
914 switch (E->getStmtClass()) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000915 case Stmt::ParenExprClass:
916 // Ignore parentheses.
917 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek06de2762007-08-17 16:46:58 +0000918
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000919 case Stmt::UnaryOperatorClass: {
920 // The only unary operator that make sense to handle here
921 // is AddrOf. All others don't make sense as pointers.
922 UnaryOperator *U = cast<UnaryOperator>(E);
Ted Kremenek06de2762007-08-17 16:46:58 +0000923
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000924 if (U->getOpcode() == UnaryOperator::AddrOf)
925 return EvalVal(U->getSubExpr());
926 else
Ted Kremenek06de2762007-08-17 16:46:58 +0000927 return NULL;
928 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000929
930 case Stmt::BinaryOperatorClass: {
931 // Handle pointer arithmetic. All other binary operators are not valid
932 // in this context.
933 BinaryOperator *B = cast<BinaryOperator>(E);
934 BinaryOperator::Opcode op = B->getOpcode();
935
936 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
937 return NULL;
938
939 Expr *Base = B->getLHS();
940
941 // Determine which argument is the real pointer base. It could be
942 // the RHS argument instead of the LHS.
943 if (!Base->getType()->isPointerType()) Base = B->getRHS();
944
945 assert (Base->getType()->isPointerType());
946 return EvalAddr(Base);
947 }
Steve Naroff61f40a22008-09-10 19:17:48 +0000948
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000949 // For conditional operators we need to see if either the LHS or RHS are
950 // valid DeclRefExpr*s. If one of them is valid, we return it.
951 case Stmt::ConditionalOperatorClass: {
952 ConditionalOperator *C = cast<ConditionalOperator>(E);
953
954 // Handle the GNU extension for missing LHS.
955 if (Expr *lhsExpr = C->getLHS())
956 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
957 return LHS;
958
959 return EvalAddr(C->getRHS());
960 }
961
Ted Kremenek54b52742008-08-07 00:49:01 +0000962 // For casts, we need to handle conversions from arrays to
963 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +0000964 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +0000965 case Stmt::CStyleCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +0000966 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +0000967 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +0000968 QualType T = SubExpr->getType();
969
Steve Naroffdd972f22008-09-05 22:11:13 +0000970 if (SubExpr->getType()->isPointerType() ||
971 SubExpr->getType()->isBlockPointerType() ||
972 SubExpr->getType()->isObjCQualifiedIdType())
Ted Kremenek54b52742008-08-07 00:49:01 +0000973 return EvalAddr(SubExpr);
974 else if (T->isArrayType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000975 return EvalVal(SubExpr);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000976 else
Ted Kremenek54b52742008-08-07 00:49:01 +0000977 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000978 }
979
980 // C++ casts. For dynamic casts, static casts, and const casts, we
981 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +0000982 // through the cast. In the case the dynamic cast doesn't fail (and
983 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000984 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +0000985 // FIXME: The comment about is wrong; we're not always converting
986 // from pointer to pointer. I'm guessing that this code should also
987 // handle references to objects.
988 case Stmt::CXXStaticCastExprClass:
989 case Stmt::CXXDynamicCastExprClass:
990 case Stmt::CXXConstCastExprClass:
991 case Stmt::CXXReinterpretCastExprClass: {
992 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +0000993 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000994 return EvalAddr(S);
995 else
996 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000997 }
998
999 // Everything else: we simply don't reason about them.
1000 default:
1001 return NULL;
1002 }
Ted Kremenek06de2762007-08-17 16:46:58 +00001003}
1004
1005
1006/// EvalVal - This function is complements EvalAddr in the mutual recursion.
1007/// See the comments for EvalAddr for more details.
1008static DeclRefExpr* EvalVal(Expr *E) {
1009
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001010 // We should only be called for evaluating non-pointer expressions, or
1011 // expressions with a pointer type that are not used as references but instead
1012 // are l-values (e.g., DeclRefExpr with a pointer type).
1013
Ted Kremenek06de2762007-08-17 16:46:58 +00001014 // Our "symbolic interpreter" is just a dispatch off the currently
1015 // viewed AST node. We then recursively traverse the AST by calling
1016 // EvalAddr and EvalVal appropriately.
1017 switch (E->getStmtClass()) {
Douglas Gregor1a49af92009-01-06 05:10:23 +00001018 case Stmt::DeclRefExprClass:
1019 case Stmt::QualifiedDeclRefExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00001020 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
1021 // at code that refers to a variable's name. We check if it has local
1022 // storage within the function, and if so, return the expression.
1023 DeclRefExpr *DR = cast<DeclRefExpr>(E);
1024
1025 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001026 if(V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
Ted Kremenek06de2762007-08-17 16:46:58 +00001027
1028 return NULL;
1029 }
1030
1031 case Stmt::ParenExprClass:
1032 // Ignore parentheses.
1033 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
1034
1035 case Stmt::UnaryOperatorClass: {
1036 // The only unary operator that make sense to handle here
1037 // is Deref. All others don't resolve to a "name." This includes
1038 // handling all sorts of rvalues passed to a unary operator.
1039 UnaryOperator *U = cast<UnaryOperator>(E);
1040
1041 if (U->getOpcode() == UnaryOperator::Deref)
1042 return EvalAddr(U->getSubExpr());
1043
1044 return NULL;
1045 }
1046
1047 case Stmt::ArraySubscriptExprClass: {
1048 // Array subscripts are potential references to data on the stack. We
1049 // retrieve the DeclRefExpr* for the array variable if it indeed
1050 // has local storage.
Ted Kremenek23245122007-08-20 16:18:38 +00001051 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek06de2762007-08-17 16:46:58 +00001052 }
1053
1054 case Stmt::ConditionalOperatorClass: {
1055 // For conditional operators we need to see if either the LHS or RHS are
1056 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
1057 ConditionalOperator *C = cast<ConditionalOperator>(E);
1058
Anders Carlsson39073232007-11-30 19:04:31 +00001059 // Handle the GNU extension for missing LHS.
1060 if (Expr *lhsExpr = C->getLHS())
1061 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
1062 return LHS;
1063
1064 return EvalVal(C->getRHS());
Ted Kremenek06de2762007-08-17 16:46:58 +00001065 }
1066
1067 // Accesses to members are potential references to data on the stack.
1068 case Stmt::MemberExprClass: {
1069 MemberExpr *M = cast<MemberExpr>(E);
1070
1071 // Check for indirect access. We only want direct field accesses.
1072 if (!M->isArrow())
1073 return EvalVal(M->getBase());
1074 else
1075 return NULL;
1076 }
1077
1078 // Everything else: we simply don't reason about them.
1079 default:
1080 return NULL;
1081 }
1082}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001083
1084//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
1085
1086/// Check for comparisons of floating point operands using != and ==.
1087/// Issue a warning if these are no self-comparisons, as they are not likely
1088/// to do what the programmer intended.
1089void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
1090 bool EmitWarning = true;
1091
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00001092 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek32e97b62008-01-17 17:55:13 +00001093 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001094
1095 // Special case: check for x == x (which is OK).
1096 // Do not emit warnings for such cases.
1097 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
1098 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
1099 if (DRL->getDecl() == DRR->getDecl())
1100 EmitWarning = false;
1101
Ted Kremenek1b500bb2007-11-29 00:59:04 +00001102
1103 // Special case: check for comparisons against literals that can be exactly
1104 // represented by APFloat. In such cases, do not emit a warning. This
1105 // is a heuristic: often comparison against such literals are used to
1106 // detect if a value in a variable has not changed. This clearly can
1107 // lead to false negatives.
1108 if (EmitWarning) {
1109 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
1110 if (FLL->isExact())
1111 EmitWarning = false;
1112 }
1113 else
1114 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
1115 if (FLR->isExact())
1116 EmitWarning = false;
1117 }
1118 }
1119
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001120 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001121 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001122 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001123 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001124 EmitWarning = false;
1125
Sebastian Redl0eb23302009-01-19 00:08:26 +00001126 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001127 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001128 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001129 EmitWarning = false;
1130
1131 // Emit the diagnostic.
1132 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001133 Diag(loc, diag::warn_floatingpoint_eq)
1134 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001135}