blob: be1faace9c8499ebb2c65d2f127fe21ffefd9037 [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();
Eli Friedman586d6a82009-05-03 06:04:26 +0000137 return move(TheCallResult);
Eli Friedmand875fed2009-05-03 04:46:36 +0000138 case Builtin::BI__builtin_longjmp:
139 if (SemaBuiltinLongjmp(TheCall))
140 return ExprError();
Eli Friedman586d6a82009-05-03 06:04:26 +0000141 return move(TheCallResult);
Anders Carlsson71993dd2007-08-17 05:31:46 +0000142 }
Daniel Dunbarde454282008-10-02 18:44:07 +0000143
144 // FIXME: This mechanism should be abstracted to be less fragile and
145 // more efficient. For example, just map function ids to custom
146 // handlers.
147
Chris Lattner59907c42007-08-10 20:18:51 +0000148 // Printf checking.
Douglas Gregor3c385e52009-02-14 18:57:46 +0000149 if (const FormatAttr *Format = FDecl->getAttr<FormatAttr>()) {
150 if (Format->getType() == "printf") {
Ted Kremenek3d692df2009-02-27 17:58:43 +0000151 bool HasVAListArg = Format->getFirstArg() == 0;
152 if (!HasVAListArg) {
153 if (const FunctionProtoType *Proto
154 = FDecl->getType()->getAsFunctionProtoType())
Douglas Gregor3c385e52009-02-14 18:57:46 +0000155 HasVAListArg = !Proto->isVariadic();
Ted Kremenek3d692df2009-02-27 17:58:43 +0000156 }
Douglas Gregor3c385e52009-02-14 18:57:46 +0000157 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
Ted Kremenek3d692df2009-02-27 17:58:43 +0000158 HasVAListArg ? 0 : Format->getFirstArg() - 1);
Douglas Gregor3c385e52009-02-14 18:57:46 +0000159 }
Chris Lattner59907c42007-08-10 20:18:51 +0000160 }
Sebastian Redl0eb23302009-01-19 00:08:26 +0000161
162 return move(TheCallResult);
Anders Carlsson71993dd2007-08-17 05:31:46 +0000163}
164
Chris Lattner69039812009-02-18 06:01:06 +0000165/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000166/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +0000167/// FIXME: GCC currently emits the following warning:
168/// "warning: input conversion stopped due to an input byte that does not
169/// belong to the input codeset UTF-8"
170/// Note: It might also make sense to do the UTF-16 conversion here (would
171/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +0000172bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000173 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000174 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
175
176 if (!Literal || Literal->isWide()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000177 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
178 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000179 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000180 }
181
182 const char *Data = Literal->getStrData();
183 unsigned Length = Literal->getByteLength();
184
185 for (unsigned i = 0; i < Length; ++i) {
Anders Carlsson71993dd2007-08-17 05:31:46 +0000186 if (!Data[i]) {
Chris Lattner60800082009-02-18 17:49:48 +0000187 Diag(getLocationOfStringLiteralByte(Literal, i),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000188 diag::warn_cfstring_literal_contains_nul_character)
189 << Arg->getSourceRange();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000190 break;
191 }
192 }
193
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000194 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000195}
196
Chris Lattnerc27c6652007-12-20 00:05:45 +0000197/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
198/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000199bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
200 Expr *Fn = TheCall->getCallee();
201 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000202 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000203 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000204 << 0 /*function call*/ << Fn->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000205 << SourceRange(TheCall->getArg(2)->getLocStart(),
206 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000207 return true;
208 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000209
210 if (TheCall->getNumArgs() < 2) {
211 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
212 << 0 /*function call*/;
213 }
214
Chris Lattnerc27c6652007-12-20 00:05:45 +0000215 // Determine whether the current function is variadic or not.
216 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000217 if (CurBlock)
218 isVariadic = CurBlock->isVariadic;
219 else if (getCurFunctionDecl()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000220 if (FunctionProtoType* FTP =
221 dyn_cast<FunctionProtoType>(getCurFunctionDecl()->getType()))
Eli Friedman56f20ae2008-12-15 22:05:35 +0000222 isVariadic = FTP->isVariadic();
223 else
224 isVariadic = false;
225 } else {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000226 isVariadic = getCurMethodDecl()->isVariadic();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000227 }
Chris Lattner30ce3442007-12-19 23:59:04 +0000228
Chris Lattnerc27c6652007-12-20 00:05:45 +0000229 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000230 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
231 return true;
232 }
233
234 // Verify that the second argument to the builtin is the last argument of the
235 // current function or method.
236 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000237 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Anders Carlsson88cf2262008-02-11 04:20:54 +0000238
239 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
240 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000241 // FIXME: This isn't correct for methods (results in bogus warning).
242 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000243 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000244 if (CurBlock)
245 LastArg = *(CurBlock->TheDecl->param_end()-1);
246 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +0000247 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000248 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000249 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000250 SecondArgIsLastNamedArgument = PV == LastArg;
251 }
252 }
253
254 if (!SecondArgIsLastNamedArgument)
Chris Lattner925e60d2007-12-28 05:29:59 +0000255 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000256 diag::warn_second_parameter_of_va_start_not_last_named_argument);
257 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000258}
Chris Lattner30ce3442007-12-19 23:59:04 +0000259
Chris Lattner1b9a0792007-12-20 00:26:33 +0000260/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
261/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000262bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
263 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000264 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
265 << 0 /*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000266 if (TheCall->getNumArgs() > 2)
267 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000268 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000269 << 0 /*function call*/
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000270 << SourceRange(TheCall->getArg(2)->getLocStart(),
271 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner1b9a0792007-12-20 00:26:33 +0000272
Chris Lattner925e60d2007-12-28 05:29:59 +0000273 Expr *OrigArg0 = TheCall->getArg(0);
274 Expr *OrigArg1 = TheCall->getArg(1);
Chris Lattner1b9a0792007-12-20 00:26:33 +0000275
276 // Do standard promotions between the two arguments, returning their common
277 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000278 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Daniel Dunbar403bc2b2009-02-19 19:28:43 +0000279
280 // Make sure any conversions are pushed back into the call; this is
281 // type safe since unordered compare builtins are declared as "_Bool
282 // foo(...)".
283 TheCall->setArg(0, OrigArg0);
284 TheCall->setArg(1, OrigArg1);
Chris Lattner1b9a0792007-12-20 00:26:33 +0000285
286 // If the common type isn't a real floating type, then the arguments were
287 // invalid for this operation.
288 if (!Res->isRealFloatingType())
Chris Lattner925e60d2007-12-28 05:29:59 +0000289 return Diag(OrigArg0->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000290 diag::err_typecheck_call_invalid_ordered_compare)
Chris Lattnerd1625842008-11-24 06:25:27 +0000291 << OrigArg0->getType() << OrigArg1->getType()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000292 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
Chris Lattner1b9a0792007-12-20 00:26:33 +0000293
294 return false;
295}
296
Eli Friedman6cfda232008-05-20 08:23:37 +0000297bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) {
298 // The signature for these builtins is exact; the only thing we need
299 // to check is that the argument is a constant.
300 SourceLocation Loc;
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000301 if (!TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc))
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000302 return Diag(Loc, diag::err_stack_const_level) << TheCall->getSourceRange();
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000303
Eli Friedman6cfda232008-05-20 08:23:37 +0000304 return false;
305}
306
Eli Friedmand38617c2008-05-14 19:38:39 +0000307/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
308// This is declared to take (...), so we have to check everything.
Sebastian Redl0eb23302009-01-19 00:08:26 +0000309Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000310 if (TheCall->getNumArgs() < 3)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000311 return ExprError(Diag(TheCall->getLocEnd(),
312 diag::err_typecheck_call_too_few_args)
313 << 0 /*function call*/ << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000314
315 QualType FAType = TheCall->getArg(0)->getType();
316 QualType SAType = TheCall->getArg(1)->getType();
317
318 if (!FAType->isVectorType() || !SAType->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000319 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
320 << SourceRange(TheCall->getArg(0)->getLocStart(),
321 TheCall->getArg(1)->getLocEnd());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000322 return ExprError();
Eli Friedmand38617c2008-05-14 19:38:39 +0000323 }
324
Chris Lattnerb77792e2008-07-26 22:17:49 +0000325 if (Context.getCanonicalType(FAType).getUnqualifiedType() !=
326 Context.getCanonicalType(SAType).getUnqualifiedType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000327 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
328 << SourceRange(TheCall->getArg(0)->getLocStart(),
329 TheCall->getArg(1)->getLocEnd());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000330 return ExprError();
Eli Friedmand38617c2008-05-14 19:38:39 +0000331 }
332
333 unsigned numElements = FAType->getAsVectorType()->getNumElements();
334 if (TheCall->getNumArgs() != numElements+2) {
335 if (TheCall->getNumArgs() < numElements+2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000336 return ExprError(Diag(TheCall->getLocEnd(),
337 diag::err_typecheck_call_too_few_args)
338 << 0 /*function call*/ << TheCall->getSourceRange());
339 return ExprError(Diag(TheCall->getLocEnd(),
340 diag::err_typecheck_call_too_many_args)
341 << 0 /*function call*/ << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000342 }
343
344 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
345 llvm::APSInt Result(32);
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000346 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000347 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000348 diag::err_shufflevector_nonconstant_argument)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000349 << TheCall->getArg(i)->getSourceRange());
350
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000351 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000352 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000353 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000354 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000355 }
356
357 llvm::SmallVector<Expr*, 32> exprs;
358
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000359 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000360 exprs.push_back(TheCall->getArg(i));
361 TheCall->setArg(i, 0);
362 }
363
Ted Kremenek8189cde2009-02-07 01:47:29 +0000364 return Owned(new (Context) ShuffleVectorExpr(exprs.begin(), numElements+2,
365 FAType,
366 TheCall->getCallee()->getLocStart(),
367 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000368}
Chris Lattner30ce3442007-12-19 23:59:04 +0000369
Daniel Dunbar4493f792008-07-21 22:59:13 +0000370/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
371// This is declared to take (const void*, ...) and can take two
372// optional constant int args.
373bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000374 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000375
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000376 if (NumArgs > 3)
377 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000378 << 0 /*function call*/ << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000379
380 // Argument 0 is checked for us and the remaining arguments must be
381 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000382 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000383 Expr *Arg = TheCall->getArg(i);
384 QualType RWType = Arg->getType();
385
386 const BuiltinType *BT = RWType->getAsBuiltinType();
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000387 llvm::APSInt Result;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000388 if (!BT || BT->getKind() != BuiltinType::Int ||
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000389 !Arg->isIntegerConstantExpr(Result, Context))
390 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument)
391 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar4493f792008-07-21 22:59:13 +0000392
393 // FIXME: gcc issues a warning and rewrites these to 0. These
394 // seems especially odd for the third argument since the default
395 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000396 if (i == 1) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000397 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000398 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
399 << "0" << "1" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar4493f792008-07-21 22:59:13 +0000400 } else {
401 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000402 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
403 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar4493f792008-07-21 22:59:13 +0000404 }
405 }
406
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000407 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000408}
409
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000410/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
411/// int type). This simply type checks that type is one of the defined
412/// constants (0-3).
413bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
414 Expr *Arg = TheCall->getArg(1);
415 QualType ArgType = Arg->getType();
416 const BuiltinType *BT = ArgType->getAsBuiltinType();
417 llvm::APSInt Result(32);
418 if (!BT || BT->getKind() != BuiltinType::Int ||
419 !Arg->isIntegerConstantExpr(Result, Context)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000420 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
421 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000422 }
423
424 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000425 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
426 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000427 }
428
429 return false;
430}
431
Eli Friedman586d6a82009-05-03 06:04:26 +0000432/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +0000433/// This checks that val is a constant 1.
434bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
435 Expr *Arg = TheCall->getArg(1);
436 llvm::APSInt Result(32);
437 if (!Arg->isIntegerConstantExpr(Result, Context) || Result != 1)
438 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
439 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
440
441 return false;
442}
443
Ted Kremenekd30ef872009-01-12 23:09:09 +0000444// Handle i > 1 ? "x" : "y", recursivelly
Ted Kremenek082d9362009-03-20 21:35:28 +0000445bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
446 bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000447 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenekd30ef872009-01-12 23:09:09 +0000448
449 switch (E->getStmtClass()) {
450 case Stmt::ConditionalOperatorClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000451 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000452 return SemaCheckStringLiteral(C->getLHS(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000453 HasVAListArg, format_idx, firstDataArg)
Ted Kremenekd30ef872009-01-12 23:09:09 +0000454 && SemaCheckStringLiteral(C->getRHS(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000455 HasVAListArg, format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000456 }
457
458 case Stmt::ImplicitCastExprClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000459 const ImplicitCastExpr *Expr = cast<ImplicitCastExpr>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000460 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000461 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000462 }
463
464 case Stmt::ParenExprClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000465 const ParenExpr *Expr = cast<ParenExpr>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000466 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000467 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000468 }
Ted Kremenek082d9362009-03-20 21:35:28 +0000469
470 case Stmt::DeclRefExprClass: {
471 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
472
473 // As an exception, do not flag errors for variables binding to
474 // const string literals.
475 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
476 bool isConstant = false;
477 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +0000478
Ted Kremenek082d9362009-03-20 21:35:28 +0000479 if (const ArrayType *AT = Context.getAsArrayType(T)) {
480 isConstant = AT->getElementType().isConstant(Context);
481 }
482 else if (const PointerType *PT = T->getAsPointerType()) {
483 isConstant = T.isConstant(Context) &&
484 PT->getPointeeType().isConstant(Context);
485 }
486
487 if (isConstant) {
488 const VarDecl *Def = 0;
489 if (const Expr *Init = VD->getDefinition(Def))
490 return SemaCheckStringLiteral(Init, TheCall,
491 HasVAListArg, format_idx, firstDataArg);
492 }
493 }
494
495 return false;
496 }
Ted Kremenekd30ef872009-01-12 23:09:09 +0000497
Ted Kremenek082d9362009-03-20 21:35:28 +0000498 case Stmt::ObjCStringLiteralClass:
499 case Stmt::StringLiteralClass: {
500 const StringLiteral *StrE = NULL;
501
502 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +0000503 StrE = ObjCFExpr->getString();
504 else
Ted Kremenek082d9362009-03-20 21:35:28 +0000505 StrE = cast<StringLiteral>(E);
506
Ted Kremenekd30ef872009-01-12 23:09:09 +0000507 if (StrE) {
Douglas Gregor3c385e52009-02-14 18:57:46 +0000508 CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx,
509 firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000510 return true;
511 }
512
513 return false;
514 }
Ted Kremenek082d9362009-03-20 21:35:28 +0000515
516 default:
517 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000518 }
519}
520
521
Chris Lattner59907c42007-08-10 20:18:51 +0000522/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Ted Kremenek71895b92007-08-14 17:39:48 +0000523/// correct use of format strings.
524///
525/// HasVAListArg - A predicate indicating whether the printf-like
526/// function is passed an explicit va_arg argument (e.g., vprintf)
527///
528/// format_idx - The index into Args for the format string.
529///
530/// Improper format strings to functions in the printf family can be
531/// the source of bizarre bugs and very serious security holes. A
532/// good source of information is available in the following paper
533/// (which includes additional references):
Chris Lattner59907c42007-08-10 20:18:51 +0000534///
535/// FormatGuard: Automatic Protection From printf Format String
536/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremenek71895b92007-08-14 17:39:48 +0000537///
538/// Functionality implemented:
539///
540/// We can statically check the following properties for string
541/// literal format strings for non v.*printf functions (where the
542/// arguments are passed directly):
543//
544/// (1) Are the number of format conversions equal to the number of
545/// data arguments?
546///
547/// (2) Does each format conversion correctly match the type of the
548/// corresponding data argument? (TODO)
549///
550/// Moreover, for all printf functions we can:
551///
552/// (3) Check for a missing format string (when not caught by type checking).
553///
554/// (4) Check for no-operation flags; e.g. using "#" with format
555/// conversion 'c' (TODO)
556///
557/// (5) Check the use of '%n', a major source of security holes.
558///
559/// (6) Check for malformed format conversions that don't specify anything.
560///
561/// (7) Check for empty format strings. e.g: printf("");
562///
563/// (8) Check that the format string is a wide literal.
564///
Ted Kremenek6d439592008-03-03 16:50:00 +0000565/// (9) Also check the arguments of functions with the __format__ attribute.
566/// (TODO).
567///
Ted Kremenek71895b92007-08-14 17:39:48 +0000568/// All of these checks can be done by parsing the format string.
569///
570/// For now, we ONLY do (1), (3), (5), (6), (7), and (8).
Chris Lattner59907c42007-08-10 20:18:51 +0000571void
Ted Kremenek082d9362009-03-20 21:35:28 +0000572Sema::CheckPrintfArguments(const CallExpr *TheCall, bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000573 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenek082d9362009-03-20 21:35:28 +0000574 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +0000575
Ted Kremenek71895b92007-08-14 17:39:48 +0000576 // CHECK: printf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +0000577 if (format_idx >= TheCall->getNumArgs()) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000578 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string)
579 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000580 return;
581 }
582
Ted Kremenek082d9362009-03-20 21:35:28 +0000583 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Chris Lattner459e8482007-08-25 05:36:18 +0000584
Chris Lattner59907c42007-08-10 20:18:51 +0000585 // CHECK: format string is not a string literal.
586 //
Ted Kremenek71895b92007-08-14 17:39:48 +0000587 // Dynamically generated format strings are difficult to
588 // automatically vet at compile time. Requiring that format strings
589 // are string literals: (1) permits the checking of format strings by
590 // the compiler and thereby (2) can practically remove the source of
591 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000592
593 // Format string can be either ObjC string (e.g. @"%d") or
594 // C string (e.g. "%d")
595 // ObjC string uses the same format specifiers as C string, so we can use
596 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +0000597 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
598 firstDataArg))
599 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000600
Chris Lattner1cd3e1f2009-04-29 04:49:34 +0000601 // For vprintf* functions (i.e., HasVAListArg==true), we add a
602 // special check to see if the format string is a function parameter
603 // of the function calling the printf function. If the function
604 // has an attribute indicating it is a printf-like function, then we
605 // should suppress warnings concerning non-literals being used in a call
606 // to a vprintf function. For example:
607 //
608 // void
609 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...) {
610 // va_list ap;
611 // va_start(ap, fmt);
612 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
613 // ...
614 //
615 //
616 // FIXME: We don't have full attribute support yet, so just check to see
617 // if the argument is a DeclRefExpr that references a parameter. We'll
618 // add proper support for checking the attribute later.
619 if (HasVAListArg)
620 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OrigFormatExpr))
621 if (isa<ParmVarDecl>(DR->getDecl()))
622 return;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000623
Chris Lattner655f1412009-04-29 04:59:47 +0000624 // If there are no arguments specified, warn with -Wformat-security, otherwise
625 // warn only with -Wformat-nonliteral.
626 if (TheCall->getNumArgs() == format_idx+1)
627 Diag(TheCall->getArg(format_idx)->getLocStart(),
628 diag::warn_printf_nonliteral_noargs)
629 << OrigFormatExpr->getSourceRange();
630 else
631 Diag(TheCall->getArg(format_idx)->getLocStart(),
632 diag::warn_printf_nonliteral)
633 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +0000634}
Ted Kremenek71895b92007-08-14 17:39:48 +0000635
Ted Kremenek082d9362009-03-20 21:35:28 +0000636void Sema::CheckPrintfString(const StringLiteral *FExpr,
637 const Expr *OrigFormatExpr,
638 const CallExpr *TheCall, bool HasVAListArg,
639 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenekd30ef872009-01-12 23:09:09 +0000640
Ted Kremenek082d9362009-03-20 21:35:28 +0000641 const ObjCStringLiteral *ObjCFExpr =
642 dyn_cast<ObjCStringLiteral>(OrigFormatExpr);
643
Ted Kremenek71895b92007-08-14 17:39:48 +0000644 // CHECK: is the format string a wide literal?
645 if (FExpr->isWide()) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000646 Diag(FExpr->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000647 diag::warn_printf_format_string_is_wide_literal)
648 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000649 return;
650 }
651
652 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattnerb9fc8562009-04-29 04:12:34 +0000653 const char *Str = FExpr->getStrData();
Ted Kremenek71895b92007-08-14 17:39:48 +0000654
655 // CHECK: empty format string?
Chris Lattnerb9fc8562009-04-29 04:12:34 +0000656 unsigned StrLen = FExpr->getByteLength();
Ted Kremenek71895b92007-08-14 17:39:48 +0000657
658 if (StrLen == 0) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000659 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string)
660 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000661 return;
662 }
663
664 // We process the format string using a binary state machine. The
665 // current state is stored in CurrentState.
666 enum {
667 state_OrdChr,
668 state_Conversion
669 } CurrentState = state_OrdChr;
670
671 // numConversions - The number of conversions seen so far. This is
672 // incremented as we traverse the format string.
673 unsigned numConversions = 0;
674
675 // numDataArgs - The number of data arguments after the format
676 // string. This can only be determined for non vprintf-like
677 // functions. For those functions, this value is 1 (the sole
678 // va_arg argument).
Douglas Gregor3c385e52009-02-14 18:57:46 +0000679 unsigned numDataArgs = TheCall->getNumArgs()-firstDataArg;
Ted Kremenek71895b92007-08-14 17:39:48 +0000680
681 // Inspect the format string.
682 unsigned StrIdx = 0;
683
684 // LastConversionIdx - Index within the format string where we last saw
685 // a '%' character that starts a new format conversion.
686 unsigned LastConversionIdx = 0;
687
Chris Lattner925e60d2007-12-28 05:29:59 +0000688 for (; StrIdx < StrLen; ++StrIdx) {
Chris Lattner998568f2007-12-28 05:38:24 +0000689
Ted Kremenek71895b92007-08-14 17:39:48 +0000690 // Is the number of detected conversion conversions greater than
691 // the number of matching data arguments? If so, stop.
692 if (!HasVAListArg && numConversions > numDataArgs) break;
693
694 // Handle "\0"
Chris Lattner925e60d2007-12-28 05:29:59 +0000695 if (Str[StrIdx] == '\0') {
Ted Kremenek71895b92007-08-14 17:39:48 +0000696 // The string returned by getStrData() is not null-terminated,
697 // so the presence of a null character is likely an error.
Chris Lattner60800082009-02-18 17:49:48 +0000698 Diag(getLocationOfStringLiteralByte(FExpr, StrIdx),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000699 diag::warn_printf_format_string_contains_null_char)
700 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000701 return;
702 }
703
704 // Ordinary characters (not processing a format conversion).
705 if (CurrentState == state_OrdChr) {
706 if (Str[StrIdx] == '%') {
707 CurrentState = state_Conversion;
708 LastConversionIdx = StrIdx;
709 }
710 continue;
711 }
712
713 // Seen '%'. Now processing a format conversion.
714 switch (Str[StrIdx]) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000715 // Handle dynamic precision or width specifier.
716 case '*': {
717 ++numConversions;
718
719 if (!HasVAListArg && numConversions > numDataArgs) {
Chris Lattner60800082009-02-18 17:49:48 +0000720 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx);
Ted Kremenek580b6642007-10-12 20:51:52 +0000721
Ted Kremenek580b6642007-10-12 20:51:52 +0000722 if (Str[StrIdx-1] == '.')
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000723 Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg)
724 << OrigFormatExpr->getSourceRange();
Ted Kremenek580b6642007-10-12 20:51:52 +0000725 else
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000726 Diag(Loc, diag::warn_printf_asterisk_width_missing_arg)
727 << OrigFormatExpr->getSourceRange();
Ted Kremenek580b6642007-10-12 20:51:52 +0000728
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000729 // Don't do any more checking. We'll just emit spurious errors.
730 return;
Ted Kremenek580b6642007-10-12 20:51:52 +0000731 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000732
733 // Perform type checking on width/precision specifier.
Ted Kremenek082d9362009-03-20 21:35:28 +0000734 const Expr *E = TheCall->getArg(format_idx+numConversions);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000735 if (const BuiltinType *BT = E->getType()->getAsBuiltinType())
736 if (BT->getKind() == BuiltinType::Int)
737 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000738
Chris Lattner60800082009-02-18 17:49:48 +0000739 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000740
741 if (Str[StrIdx-1] == '.')
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000742 Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000743 << E->getType() << E->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000744 else
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000745 Diag(Loc, diag::warn_printf_asterisk_width_wrong_type)
Chris Lattnerd1625842008-11-24 06:25:27 +0000746 << E->getType() << E->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000747
748 break;
749 }
750
751 // Characters which can terminate a format conversion
752 // (e.g. "%d"). Characters that specify length modifiers or
753 // other flags are handled by the default case below.
754 //
755 // FIXME: additional checks will go into the following cases.
756 case 'i':
757 case 'd':
758 case 'o':
759 case 'u':
760 case 'x':
761 case 'X':
762 case 'D':
763 case 'O':
764 case 'U':
765 case 'e':
766 case 'E':
767 case 'f':
768 case 'F':
769 case 'g':
770 case 'G':
771 case 'a':
772 case 'A':
773 case 'c':
774 case 'C':
775 case 'S':
776 case 's':
777 case 'p':
778 ++numConversions;
779 CurrentState = state_OrdChr;
780 break;
781
782 // CHECK: Are we using "%n"? Issue a warning.
783 case 'n': {
784 ++numConversions;
785 CurrentState = state_OrdChr;
Chris Lattner60800082009-02-18 17:49:48 +0000786 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr,
787 LastConversionIdx);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000788
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000789 Diag(Loc, diag::warn_printf_write_back)<<OrigFormatExpr->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000790 break;
791 }
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000792
793 // Handle "%@"
794 case '@':
795 // %@ is allowed in ObjC format strings only.
796 if(ObjCFExpr != NULL)
797 CurrentState = state_OrdChr;
798 else {
799 // Issue a warning: invalid format conversion.
Chris Lattner60800082009-02-18 17:49:48 +0000800 SourceLocation Loc =
801 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000802
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000803 Diag(Loc, diag::warn_printf_invalid_conversion)
804 << std::string(Str+LastConversionIdx,
805 Str+std::min(LastConversionIdx+2, StrLen))
806 << OrigFormatExpr->getSourceRange();
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000807 }
808 ++numConversions;
809 break;
810
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000811 // Handle "%%"
812 case '%':
813 // Sanity check: Was the first "%" character the previous one?
814 // If not, we will assume that we have a malformed format
815 // conversion, and that the current "%" character is the start
816 // of a new conversion.
817 if (StrIdx - LastConversionIdx == 1)
818 CurrentState = state_OrdChr;
819 else {
820 // Issue a warning: invalid format conversion.
Chris Lattner60800082009-02-18 17:49:48 +0000821 SourceLocation Loc =
822 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000823
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000824 Diag(Loc, diag::warn_printf_invalid_conversion)
825 << std::string(Str+LastConversionIdx, Str+StrIdx)
826 << OrigFormatExpr->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000827
828 // This conversion is broken. Advance to the next format
829 // conversion.
830 LastConversionIdx = StrIdx;
831 ++numConversions;
Ted Kremenek71895b92007-08-14 17:39:48 +0000832 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000833 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000834
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000835 default:
836 // This case catches all other characters: flags, widths, etc.
837 // We should eventually process those as well.
838 break;
Ted Kremenek71895b92007-08-14 17:39:48 +0000839 }
840 }
841
842 if (CurrentState == state_Conversion) {
843 // Issue a warning: invalid format conversion.
Chris Lattner60800082009-02-18 17:49:48 +0000844 SourceLocation Loc =
845 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Ted Kremenek71895b92007-08-14 17:39:48 +0000846
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000847 Diag(Loc, diag::warn_printf_invalid_conversion)
848 << std::string(Str+LastConversionIdx,
849 Str+std::min(LastConversionIdx+2, StrLen))
850 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000851 return;
852 }
853
854 if (!HasVAListArg) {
855 // CHECK: Does the number of format conversions exceed the number
856 // of data arguments?
857 if (numConversions > numDataArgs) {
Chris Lattner60800082009-02-18 17:49:48 +0000858 SourceLocation Loc =
859 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Ted Kremenek71895b92007-08-14 17:39:48 +0000860
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000861 Diag(Loc, diag::warn_printf_insufficient_data_args)
862 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000863 }
864 // CHECK: Does the number of data arguments exceed the number of
865 // format conversions in the format string?
866 else if (numConversions < numDataArgs)
Chris Lattner925e60d2007-12-28 05:29:59 +0000867 Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000868 diag::warn_printf_too_many_data_args)
869 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000870 }
871}
Ted Kremenek06de2762007-08-17 16:46:58 +0000872
873//===--- CHECK: Return Address of Stack Variable --------------------------===//
874
875static DeclRefExpr* EvalVal(Expr *E);
876static DeclRefExpr* EvalAddr(Expr* E);
877
878/// CheckReturnStackAddr - Check if a return statement returns the address
879/// of a stack variable.
880void
881Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
882 SourceLocation ReturnLoc) {
Chris Lattner56f34942008-02-13 01:02:39 +0000883
Ted Kremenek06de2762007-08-17 16:46:58 +0000884 // Perform checking for returned stack addresses.
Steve Naroffdd972f22008-09-05 22:11:13 +0000885 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Ted Kremenek06de2762007-08-17 16:46:58 +0000886 if (DeclRefExpr *DR = EvalAddr(RetValExp))
Chris Lattner3c73c412008-11-19 08:23:25 +0000887 Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
Chris Lattner08631c52008-11-23 21:45:46 +0000888 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Steve Naroffc50a4a52008-09-16 22:25:10 +0000889
890 // Skip over implicit cast expressions when checking for block expressions.
891 if (ImplicitCastExpr *IcExpr =
892 dyn_cast_or_null<ImplicitCastExpr>(RetValExp))
893 RetValExp = IcExpr->getSubExpr();
894
Steve Naroff61f40a22008-09-10 19:17:48 +0000895 if (BlockExpr *C = dyn_cast_or_null<BlockExpr>(RetValExp))
Mike Stump397195b2009-04-17 00:09:41 +0000896 if (C->hasBlockDeclRefExprs())
897 Diag(C->getLocStart(), diag::err_ret_local_block)
898 << C->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +0000899 }
900 // Perform checking for stack values returned by reference.
901 else if (lhsType->isReferenceType()) {
Douglas Gregor49badde2008-10-27 19:41:14 +0000902 // Check for a reference to the stack
903 if (DeclRefExpr *DR = EvalVal(RetValExp))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000904 Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
Chris Lattner08631c52008-11-23 21:45:46 +0000905 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +0000906 }
907}
908
909/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
910/// check if the expression in a return statement evaluates to an address
911/// to a location on the stack. The recursion is used to traverse the
912/// AST of the return expression, with recursion backtracking when we
913/// encounter a subexpression that (1) clearly does not lead to the address
914/// of a stack variable or (2) is something we cannot determine leads to
915/// the address of a stack variable based on such local checking.
916///
Ted Kremeneke8c600f2007-08-28 17:02:55 +0000917/// EvalAddr processes expressions that are pointers that are used as
918/// references (and not L-values). EvalVal handles all other values.
Ted Kremenek06de2762007-08-17 16:46:58 +0000919/// At the base case of the recursion is a check for a DeclRefExpr* in
920/// the refers to a stack variable.
921///
922/// This implementation handles:
923///
924/// * pointer-to-pointer casts
925/// * implicit conversions from array references to pointers
926/// * taking the address of fields
927/// * arbitrary interplay between "&" and "*" operators
928/// * pointer arithmetic from an address of a stack variable
929/// * taking the address of an array element where the array is on the stack
930static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek06de2762007-08-17 16:46:58 +0000931 // We should only be called for evaluating pointer expressions.
Steve Naroffdd972f22008-09-05 22:11:13 +0000932 assert((E->getType()->isPointerType() ||
933 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000934 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000935 "EvalAddr only works on pointers");
Ted Kremenek06de2762007-08-17 16:46:58 +0000936
937 // Our "symbolic interpreter" is just a dispatch off the currently
938 // viewed AST node. We then recursively traverse the AST by calling
939 // EvalAddr and EvalVal appropriately.
940 switch (E->getStmtClass()) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000941 case Stmt::ParenExprClass:
942 // Ignore parentheses.
943 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek06de2762007-08-17 16:46:58 +0000944
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000945 case Stmt::UnaryOperatorClass: {
946 // The only unary operator that make sense to handle here
947 // is AddrOf. All others don't make sense as pointers.
948 UnaryOperator *U = cast<UnaryOperator>(E);
Ted Kremenek06de2762007-08-17 16:46:58 +0000949
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000950 if (U->getOpcode() == UnaryOperator::AddrOf)
951 return EvalVal(U->getSubExpr());
952 else
Ted Kremenek06de2762007-08-17 16:46:58 +0000953 return NULL;
954 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000955
956 case Stmt::BinaryOperatorClass: {
957 // Handle pointer arithmetic. All other binary operators are not valid
958 // in this context.
959 BinaryOperator *B = cast<BinaryOperator>(E);
960 BinaryOperator::Opcode op = B->getOpcode();
961
962 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
963 return NULL;
964
965 Expr *Base = B->getLHS();
966
967 // Determine which argument is the real pointer base. It could be
968 // the RHS argument instead of the LHS.
969 if (!Base->getType()->isPointerType()) Base = B->getRHS();
970
971 assert (Base->getType()->isPointerType());
972 return EvalAddr(Base);
973 }
Steve Naroff61f40a22008-09-10 19:17:48 +0000974
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000975 // For conditional operators we need to see if either the LHS or RHS are
976 // valid DeclRefExpr*s. If one of them is valid, we return it.
977 case Stmt::ConditionalOperatorClass: {
978 ConditionalOperator *C = cast<ConditionalOperator>(E);
979
980 // Handle the GNU extension for missing LHS.
981 if (Expr *lhsExpr = C->getLHS())
982 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
983 return LHS;
984
985 return EvalAddr(C->getRHS());
986 }
987
Ted Kremenek54b52742008-08-07 00:49:01 +0000988 // For casts, we need to handle conversions from arrays to
989 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +0000990 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +0000991 case Stmt::CStyleCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +0000992 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +0000993 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +0000994 QualType T = SubExpr->getType();
995
Steve Naroffdd972f22008-09-05 22:11:13 +0000996 if (SubExpr->getType()->isPointerType() ||
997 SubExpr->getType()->isBlockPointerType() ||
998 SubExpr->getType()->isObjCQualifiedIdType())
Ted Kremenek54b52742008-08-07 00:49:01 +0000999 return EvalAddr(SubExpr);
1000 else if (T->isArrayType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001001 return EvalVal(SubExpr);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001002 else
Ted Kremenek54b52742008-08-07 00:49:01 +00001003 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001004 }
1005
1006 // C++ casts. For dynamic casts, static casts, and const casts, we
1007 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00001008 // through the cast. In the case the dynamic cast doesn't fail (and
1009 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001010 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00001011 // FIXME: The comment about is wrong; we're not always converting
1012 // from pointer to pointer. I'm guessing that this code should also
1013 // handle references to objects.
1014 case Stmt::CXXStaticCastExprClass:
1015 case Stmt::CXXDynamicCastExprClass:
1016 case Stmt::CXXConstCastExprClass:
1017 case Stmt::CXXReinterpretCastExprClass: {
1018 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00001019 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001020 return EvalAddr(S);
1021 else
1022 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001023 }
1024
1025 // Everything else: we simply don't reason about them.
1026 default:
1027 return NULL;
1028 }
Ted Kremenek06de2762007-08-17 16:46:58 +00001029}
1030
1031
1032/// EvalVal - This function is complements EvalAddr in the mutual recursion.
1033/// See the comments for EvalAddr for more details.
1034static DeclRefExpr* EvalVal(Expr *E) {
1035
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001036 // We should only be called for evaluating non-pointer expressions, or
1037 // expressions with a pointer type that are not used as references but instead
1038 // are l-values (e.g., DeclRefExpr with a pointer type).
1039
Ted Kremenek06de2762007-08-17 16:46:58 +00001040 // Our "symbolic interpreter" is just a dispatch off the currently
1041 // viewed AST node. We then recursively traverse the AST by calling
1042 // EvalAddr and EvalVal appropriately.
1043 switch (E->getStmtClass()) {
Douglas Gregor1a49af92009-01-06 05:10:23 +00001044 case Stmt::DeclRefExprClass:
1045 case Stmt::QualifiedDeclRefExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00001046 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
1047 // at code that refers to a variable's name. We check if it has local
1048 // storage within the function, and if so, return the expression.
1049 DeclRefExpr *DR = cast<DeclRefExpr>(E);
1050
1051 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001052 if(V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
Ted Kremenek06de2762007-08-17 16:46:58 +00001053
1054 return NULL;
1055 }
1056
1057 case Stmt::ParenExprClass:
1058 // Ignore parentheses.
1059 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
1060
1061 case Stmt::UnaryOperatorClass: {
1062 // The only unary operator that make sense to handle here
1063 // is Deref. All others don't resolve to a "name." This includes
1064 // handling all sorts of rvalues passed to a unary operator.
1065 UnaryOperator *U = cast<UnaryOperator>(E);
1066
1067 if (U->getOpcode() == UnaryOperator::Deref)
1068 return EvalAddr(U->getSubExpr());
1069
1070 return NULL;
1071 }
1072
1073 case Stmt::ArraySubscriptExprClass: {
1074 // Array subscripts are potential references to data on the stack. We
1075 // retrieve the DeclRefExpr* for the array variable if it indeed
1076 // has local storage.
Ted Kremenek23245122007-08-20 16:18:38 +00001077 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek06de2762007-08-17 16:46:58 +00001078 }
1079
1080 case Stmt::ConditionalOperatorClass: {
1081 // For conditional operators we need to see if either the LHS or RHS are
1082 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
1083 ConditionalOperator *C = cast<ConditionalOperator>(E);
1084
Anders Carlsson39073232007-11-30 19:04:31 +00001085 // Handle the GNU extension for missing LHS.
1086 if (Expr *lhsExpr = C->getLHS())
1087 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
1088 return LHS;
1089
1090 return EvalVal(C->getRHS());
Ted Kremenek06de2762007-08-17 16:46:58 +00001091 }
1092
1093 // Accesses to members are potential references to data on the stack.
1094 case Stmt::MemberExprClass: {
1095 MemberExpr *M = cast<MemberExpr>(E);
1096
1097 // Check for indirect access. We only want direct field accesses.
1098 if (!M->isArrow())
1099 return EvalVal(M->getBase());
1100 else
1101 return NULL;
1102 }
1103
1104 // Everything else: we simply don't reason about them.
1105 default:
1106 return NULL;
1107 }
1108}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001109
1110//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
1111
1112/// Check for comparisons of floating point operands using != and ==.
1113/// Issue a warning if these are no self-comparisons, as they are not likely
1114/// to do what the programmer intended.
1115void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
1116 bool EmitWarning = true;
1117
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00001118 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek32e97b62008-01-17 17:55:13 +00001119 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001120
1121 // Special case: check for x == x (which is OK).
1122 // Do not emit warnings for such cases.
1123 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
1124 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
1125 if (DRL->getDecl() == DRR->getDecl())
1126 EmitWarning = false;
1127
Ted Kremenek1b500bb2007-11-29 00:59:04 +00001128
1129 // Special case: check for comparisons against literals that can be exactly
1130 // represented by APFloat. In such cases, do not emit a warning. This
1131 // is a heuristic: often comparison against such literals are used to
1132 // detect if a value in a variable has not changed. This clearly can
1133 // lead to false negatives.
1134 if (EmitWarning) {
1135 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
1136 if (FLL->isExact())
1137 EmitWarning = false;
1138 }
1139 else
1140 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
1141 if (FLR->isExact())
1142 EmitWarning = false;
1143 }
1144 }
1145
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001146 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001147 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001148 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001149 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001150 EmitWarning = false;
1151
Sebastian Redl0eb23302009-01-19 00:08:26 +00001152 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001153 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001154 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001155 EmitWarning = false;
1156
1157 // Emit the diagnostic.
1158 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001159 Diag(loc, diag::warn_floatingpoint_eq)
1160 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001161}