blob: e8b908ed3f3680809424e83fca2ee0c2e4b2c786 [file] [log] [blame]
Chris Lattner2e64c072007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-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 Lattner2e64c072007-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 Dunbar64789f82008-08-11 05:35:13 +000017#include "clang/AST/DeclObjC.h"
Ted Kremenek1c1700f2007-08-20 16:18:38 +000018#include "clang/AST/ExprCXX.h"
Ted Kremenek225a14c2008-06-16 18:00:42 +000019#include "clang/AST/ExprObjC.h"
Chris Lattnerbe93e792009-02-18 19:21:10 +000020#include "clang/Lex/LiteralSupport.h"
Chris Lattner2e64c072007-08-10 20:18:51 +000021#include "clang/Lex/Preprocessor.h"
Chris Lattner2e64c072007-08-10 20:18:51 +000022using namespace clang;
23
Chris Lattnerf17cb362009-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 Lattnerf6d44722009-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 Lattner30183b02009-02-18 18:34:12 +000068
Chris Lattner81df8462009-02-18 18:52:52 +000069 // If the byte is in this token, return the location of the byte.
Chris Lattnerf17cb362009-02-18 17:49:48 +000070 if (ByteNo < TokNumBytes ||
71 (ByteNo == TokNumBytes && TokNo == SL->getNumConcatenated())) {
Chris Lattnerbe93e792009-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 Lattnerf17cb362009-02-18 17:49:48 +000078 }
79
80 // Move to the next string token.
81 ++TokNo;
82 ByteNo -= TokNumBytes;
83 }
84}
85
86
Chris Lattner2e64c072007-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 Redl8b769972009-01-19 00:08:26 +000089Action::OwningExprResult
90Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
91 OwningExprResult TheCallResult(Owned(TheCall));
Chris Lattner2e64c072007-08-10 20:18:51 +000092 // Get the IdentifierInfo* for the called function.
93 IdentifierInfo *FnInfo = FDecl->getIdentifier();
Douglas Gregorb0212bd2008-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 Redl8b769972009-01-19 00:08:26 +000098 return move(TheCallResult);
Douglas Gregorb0212bd2008-11-17 20:34:05 +000099
Douglas Gregorb5af7382009-02-14 18:57:46 +0000100 switch (FDecl->getBuiltinID(Context)) {
Chris Lattnerf22a8502007-12-19 23:59:04 +0000101 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000102 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000103 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner81f5be22009-02-18 06:01:06 +0000104 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl8b769972009-01-19 00:08:26 +0000105 return ExprError();
106 return move(TheCallResult);
Ted Kremenek7a0654c2008-07-09 17:58:53 +0000107 case Builtin::BI__builtin_stdarg_start:
Chris Lattnerf22a8502007-12-19 23:59:04 +0000108 case Builtin::BI__builtin_va_start:
Sebastian Redl8b769972009-01-19 00:08:26 +0000109 if (SemaBuiltinVAStart(TheCall))
110 return ExprError();
111 return move(TheCallResult);
Chris Lattner7c8d1af2007-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 Redl8b769972009-01-19 00:08:26 +0000118 if (SemaBuiltinUnorderedCompare(TheCall))
119 return ExprError();
120 return move(TheCallResult);
Eli Friedman8c50c622008-05-20 08:23:37 +0000121 case Builtin::BI__builtin_return_address:
122 case Builtin::BI__builtin_frame_address:
Sebastian Redl8b769972009-01-19 00:08:26 +0000123 if (SemaBuiltinStackAddress(TheCall))
124 return ExprError();
125 return move(TheCallResult);
Eli Friedmand0e9d092008-05-14 19:38:39 +0000126 case Builtin::BI__builtin_shufflevector:
Sebastian Redl8b769972009-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 Dunbar5b0de852008-07-21 22:59:13 +0000130 case Builtin::BI__builtin_prefetch:
Sebastian Redl8b769972009-01-19 00:08:26 +0000131 if (SemaBuiltinPrefetch(TheCall))
132 return ExprError();
133 return move(TheCallResult);
Daniel Dunbar30ad42d2008-09-03 21:13:56 +0000134 case Builtin::BI__builtin_object_size:
Sebastian Redl8b769972009-01-19 00:08:26 +0000135 if (SemaBuiltinObjectSize(TheCall))
136 return ExprError();
Eli Friedman5e0ae472009-05-03 06:04:26 +0000137 return move(TheCallResult);
Eli Friedman6277e402009-05-03 04:46:36 +0000138 case Builtin::BI__builtin_longjmp:
139 if (SemaBuiltinLongjmp(TheCall))
140 return ExprError();
Eli Friedman5e0ae472009-05-03 06:04:26 +0000141 return move(TheCallResult);
Chris Lattner822adfe2009-05-08 06:58:22 +0000142 case Builtin::BI__sync_fetch_and_add:
143 case Builtin::BI__sync_fetch_and_sub:
144 case Builtin::BI__sync_fetch_and_or:
145 case Builtin::BI__sync_fetch_and_and:
146 case Builtin::BI__sync_fetch_and_xor:
147 case Builtin::BI__sync_add_and_fetch:
148 case Builtin::BI__sync_sub_and_fetch:
149 case Builtin::BI__sync_and_and_fetch:
150 case Builtin::BI__sync_or_and_fetch:
151 case Builtin::BI__sync_xor_and_fetch:
152 case Builtin::BI__sync_val_compare_and_swap:
153 case Builtin::BI__sync_bool_compare_and_swap:
154 case Builtin::BI__sync_lock_test_and_set:
155 case Builtin::BI__sync_lock_release:
156 if (SemaBuiltinAtomicOverloaded(TheCall))
157 return ExprError();
158 return move(TheCallResult);
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000159 }
Daniel Dunbar0ab03e62008-10-02 18:44:07 +0000160
161 // FIXME: This mechanism should be abstracted to be less fragile and
162 // more efficient. For example, just map function ids to custom
163 // handlers.
164
Chris Lattner2e64c072007-08-10 20:18:51 +0000165 // Printf checking.
Douglas Gregorb5af7382009-02-14 18:57:46 +0000166 if (const FormatAttr *Format = FDecl->getAttr<FormatAttr>()) {
167 if (Format->getType() == "printf") {
Ted Kremenekfec9c152009-02-27 17:58:43 +0000168 bool HasVAListArg = Format->getFirstArg() == 0;
169 if (!HasVAListArg) {
170 if (const FunctionProtoType *Proto
171 = FDecl->getType()->getAsFunctionProtoType())
Douglas Gregorb5af7382009-02-14 18:57:46 +0000172 HasVAListArg = !Proto->isVariadic();
Ted Kremenekfec9c152009-02-27 17:58:43 +0000173 }
Douglas Gregorb5af7382009-02-14 18:57:46 +0000174 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
Ted Kremenekfec9c152009-02-27 17:58:43 +0000175 HasVAListArg ? 0 : Format->getFirstArg() - 1);
Douglas Gregorb5af7382009-02-14 18:57:46 +0000176 }
Chris Lattner2e64c072007-08-10 20:18:51 +0000177 }
Sebastian Redl8b769972009-01-19 00:08:26 +0000178
179 return move(TheCallResult);
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000180}
181
Chris Lattner822adfe2009-05-08 06:58:22 +0000182/// SemaBuiltinAtomicOverloaded - We have a call to a function like
183/// __sync_fetch_and_add, which is an overloaded function based on the pointer
184/// type of its first argument. The main ActOnCallExpr routines have already
185/// promoted the types of arguments because all of these calls are prototyped as
186/// void(...).
187///
188/// This function goes through and does final semantic checking for these
189/// builtins,
190bool Sema::SemaBuiltinAtomicOverloaded(CallExpr *TheCall) {
191 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
192 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
193
194 // Ensure that we have at least one argument to do type inference from.
195 if (TheCall->getNumArgs() < 1)
196 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
197 << 0 << TheCall->getCallee()->getSourceRange();
198
199 // Inspect the first argument of the atomic builtin. This should always be
200 // a pointer type, whose element is an integral scalar or pointer type.
201 // Because it is a pointer type, we don't have to worry about any implicit
202 // casts here.
203 Expr *FirstArg = TheCall->getArg(0);
204 if (!FirstArg->getType()->isPointerType())
205 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
206 << FirstArg->getType() << FirstArg->getSourceRange();
207
208 QualType ValType = FirstArg->getType()->getAsPointerType()->getPointeeType();
209 if (!ValType->isIntegerType() && !ValType->isPointerType() &&
210 !ValType->isBlockPointerType())
211 return Diag(DRE->getLocStart(),
212 diag::err_atomic_builtin_must_be_pointer_intptr)
213 << FirstArg->getType() << FirstArg->getSourceRange();
214
215 // We need to figure out which concrete builtin this maps onto. For example,
216 // __sync_fetch_and_add with a 2 byte object turns into
217 // __sync_fetch_and_add_2.
218#define BUILTIN_ROW(x) \
219 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
220 Builtin::BI##x##_8, Builtin::BI##x##_16 }
221
222 static const unsigned BuiltinIndices[][5] = {
223 BUILTIN_ROW(__sync_fetch_and_add),
224 BUILTIN_ROW(__sync_fetch_and_sub),
225 BUILTIN_ROW(__sync_fetch_and_or),
226 BUILTIN_ROW(__sync_fetch_and_and),
227 BUILTIN_ROW(__sync_fetch_and_xor),
228
229 BUILTIN_ROW(__sync_add_and_fetch),
230 BUILTIN_ROW(__sync_sub_and_fetch),
231 BUILTIN_ROW(__sync_and_and_fetch),
232 BUILTIN_ROW(__sync_or_and_fetch),
233 BUILTIN_ROW(__sync_xor_and_fetch),
234
235 BUILTIN_ROW(__sync_val_compare_and_swap),
236 BUILTIN_ROW(__sync_bool_compare_and_swap),
237 BUILTIN_ROW(__sync_lock_test_and_set),
238 BUILTIN_ROW(__sync_lock_release)
239 };
240#undef BUILTIN_ROW
241
242 // Determine the index of the size.
243 unsigned SizeIndex;
244 switch (Context.getTypeSize(ValType)/8) {
245 case 1: SizeIndex = 0; break;
246 case 2: SizeIndex = 1; break;
247 case 4: SizeIndex = 2; break;
248 case 8: SizeIndex = 3; break;
249 case 16: SizeIndex = 4; break;
250 default:
251 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
252 << FirstArg->getType() << FirstArg->getSourceRange();
253 }
254
255 // Each of these builtins has one pointer argument, followed by some number of
256 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
257 // that we ignore. Find out which row of BuiltinIndices to read from as well
258 // as the number of fixed args.
259 unsigned BuiltinID = FDecl->getBuiltinID(Context);
260 unsigned BuiltinIndex, NumFixed = 1;
261 switch (BuiltinID) {
262 default: assert(0 && "Unknown overloaded atomic builtin!");
263 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
264 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
265 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
266 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
267 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
268
269 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
270 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
271 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
272 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 8; break;
273 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
274
275 case Builtin::BI__sync_val_compare_and_swap:
276 BuiltinIndex = 10;
277 NumFixed = 2;
278 break;
279 case Builtin::BI__sync_bool_compare_and_swap:
280 BuiltinIndex = 11;
281 NumFixed = 2;
282 break;
283 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
284 case Builtin::BI__sync_lock_release:
285 BuiltinIndex = 13;
286 NumFixed = 0;
287 break;
288 }
289
290 // Now that we know how many fixed arguments we expect, first check that we
291 // have at least that many.
292 if (TheCall->getNumArgs() < 1+NumFixed)
293 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
294 << 0 << TheCall->getCallee()->getSourceRange();
295
296 // Next, walk the valid ones promoting to the right type.
297 for (unsigned i = 0; i != NumFixed; ++i) {
298 Expr *Arg = TheCall->getArg(i+1);
299
300 // If the argument is an implicit cast, then there was a promotion due to
301 // "...", just remove it now.
302 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
303 Arg = ICE->getSubExpr();
304 ICE->setSubExpr(0);
305 ICE->Destroy(Context);
306 TheCall->setArg(i+1, Arg);
307 }
308
309 // GCC does an implicit conversion to the pointer or integer ValType. This
310 // can fail in some cases (1i -> int**), check for this error case now.
311 if (CheckCastTypes(Arg->getSourceRange(), ValType, Arg))
312 return true;
313
314 // Okay, we have something that *can* be converted to the right type. Check
315 // to see if there is a potentially weird extension going on here. This can
316 // happen when you do an atomic operation on something like an char* and
317 // pass in 42. The 42 gets converted to char. This is even more strange
318 // for things like 45.123 -> char, etc.
319 // FIXME: Do this check.
320 ImpCastExprToType(Arg, ValType, false);
321 TheCall->setArg(i+1, Arg);
322 }
323
324 // Okay, if we get here, everything is good. Get the decl for the concrete
325 // builtin.
326 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
327 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
328 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
329 FunctionDecl *NewBuiltinDecl =
330 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
331 TUScope, false, DRE->getLocStart()));
332 // Switch the DeclRefExpr to refer to the new decl.
333 DRE->setDecl(NewBuiltinDecl);
334 DRE->setType(NewBuiltinDecl->getType());
335
336 // Set the callee in the CallExpr.
337 // FIXME: This leaks the original parens and implicit casts.
338 Expr *PromotedCall = DRE;
339 UsualUnaryConversions(PromotedCall);
340 TheCall->setCallee(PromotedCall);
341
342
343 // Change the result type of the call to match the result type of the decl.
344 TheCall->setType(NewBuiltinDecl->getResultType());
345 return false;
346}
347
348
Chris Lattner81f5be22009-02-18 06:01:06 +0000349/// CheckObjCString - Checks that the argument to the builtin
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000350/// CFString constructor is correct
Steve Naroff9c9dc522009-04-13 20:26:29 +0000351/// FIXME: GCC currently emits the following warning:
352/// "warning: input conversion stopped due to an input byte that does not
353/// belong to the input codeset UTF-8"
354/// Note: It might also make sense to do the UTF-16 conversion here (would
355/// simplify the backend).
Chris Lattner81f5be22009-02-18 06:01:06 +0000356bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner7a48d9c2008-02-13 01:02:39 +0000357 Arg = Arg->IgnoreParenCasts();
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000358 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
359
360 if (!Literal || Literal->isWide()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000361 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
362 << Arg->getSourceRange();
Anders Carlsson3e9b43b2007-08-17 15:44:17 +0000363 return true;
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000364 }
365
366 const char *Data = Literal->getStrData();
367 unsigned Length = Literal->getByteLength();
368
369 for (unsigned i = 0; i < Length; ++i) {
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000370 if (!Data[i]) {
Chris Lattnerf17cb362009-02-18 17:49:48 +0000371 Diag(getLocationOfStringLiteralByte(Literal, i),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000372 diag::warn_cfstring_literal_contains_nul_character)
373 << Arg->getSourceRange();
Anders Carlssone7e7aa22007-08-17 05:31:46 +0000374 break;
375 }
376 }
377
Anders Carlsson3e9b43b2007-08-17 15:44:17 +0000378 return false;
Chris Lattner2e64c072007-08-10 20:18:51 +0000379}
380
Chris Lattner3b933692007-12-20 00:05:45 +0000381/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
382/// Emit an error and return true on failure, return false on success.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000383bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
384 Expr *Fn = TheCall->getCallee();
385 if (TheCall->getNumArgs() > 2) {
Chris Lattner66beaba2008-11-21 18:44:24 +0000386 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000387 diag::err_typecheck_call_too_many_args)
Chris Lattner66beaba2008-11-21 18:44:24 +0000388 << 0 /*function call*/ << Fn->getSourceRange()
Chris Lattner8ba580c2008-11-19 05:08:23 +0000389 << SourceRange(TheCall->getArg(2)->getLocStart(),
390 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattnerf22a8502007-12-19 23:59:04 +0000391 return true;
392 }
Eli Friedman6422de62008-12-15 22:05:35 +0000393
394 if (TheCall->getNumArgs() < 2) {
395 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
396 << 0 /*function call*/;
397 }
398
Chris Lattner3b933692007-12-20 00:05:45 +0000399 // Determine whether the current function is variadic or not.
400 bool isVariadic;
Steve Naroffe06a81e2009-04-15 19:33:47 +0000401 if (CurBlock)
402 isVariadic = CurBlock->isVariadic;
403 else if (getCurFunctionDecl()) {
Douglas Gregor4fa58902009-02-26 23:50:07 +0000404 if (FunctionProtoType* FTP =
405 dyn_cast<FunctionProtoType>(getCurFunctionDecl()->getType()))
Eli Friedman6422de62008-12-15 22:05:35 +0000406 isVariadic = FTP->isVariadic();
407 else
408 isVariadic = false;
409 } else {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000410 isVariadic = getCurMethodDecl()->isVariadic();
Eli Friedman6422de62008-12-15 22:05:35 +0000411 }
Chris Lattnerf22a8502007-12-19 23:59:04 +0000412
Chris Lattner3b933692007-12-20 00:05:45 +0000413 if (!isVariadic) {
Chris Lattnerf22a8502007-12-19 23:59:04 +0000414 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
415 return true;
416 }
417
418 // Verify that the second argument to the builtin is the last argument of the
419 // current function or method.
420 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson924556e2008-02-13 01:22:59 +0000421 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Anders Carlssonc27156b2008-02-11 04:20:54 +0000422
423 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
424 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattnerf22a8502007-12-19 23:59:04 +0000425 // FIXME: This isn't correct for methods (results in bogus warning).
426 // Get the last formal in the current function.
Anders Carlssonc27156b2008-02-11 04:20:54 +0000427 const ParmVarDecl *LastArg;
Steve Naroffe06a81e2009-04-15 19:33:47 +0000428 if (CurBlock)
429 LastArg = *(CurBlock->TheDecl->param_end()-1);
430 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattnere5cb5862008-12-04 23:50:19 +0000431 LastArg = *(FD->param_end()-1);
Chris Lattnerf22a8502007-12-19 23:59:04 +0000432 else
Argiris Kirtzidis95256e62008-06-28 06:07:14 +0000433 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattnerf22a8502007-12-19 23:59:04 +0000434 SecondArgIsLastNamedArgument = PV == LastArg;
435 }
436 }
437
438 if (!SecondArgIsLastNamedArgument)
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000439 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattnerf22a8502007-12-19 23:59:04 +0000440 diag::warn_second_parameter_of_va_start_not_last_named_argument);
441 return false;
Eli Friedman8c50c622008-05-20 08:23:37 +0000442}
Chris Lattnerf22a8502007-12-19 23:59:04 +0000443
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000444/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
445/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000446bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
447 if (TheCall->getNumArgs() < 2)
Chris Lattner66beaba2008-11-21 18:44:24 +0000448 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
449 << 0 /*function call*/;
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000450 if (TheCall->getNumArgs() > 2)
451 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000452 diag::err_typecheck_call_too_many_args)
Chris Lattner66beaba2008-11-21 18:44:24 +0000453 << 0 /*function call*/
Chris Lattner8ba580c2008-11-19 05:08:23 +0000454 << SourceRange(TheCall->getArg(2)->getLocStart(),
455 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000456
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000457 Expr *OrigArg0 = TheCall->getArg(0);
458 Expr *OrigArg1 = TheCall->getArg(1);
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000459
460 // Do standard promotions between the two arguments, returning their common
461 // type.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000462 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Daniel Dunbar5ac4dff2009-02-19 19:28:43 +0000463
464 // Make sure any conversions are pushed back into the call; this is
465 // type safe since unordered compare builtins are declared as "_Bool
466 // foo(...)".
467 TheCall->setArg(0, OrigArg0);
468 TheCall->setArg(1, OrigArg1);
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000469
470 // If the common type isn't a real floating type, then the arguments were
471 // invalid for this operation.
472 if (!Res->isRealFloatingType())
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000473 return Diag(OrigArg0->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000474 diag::err_typecheck_call_invalid_ordered_compare)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000475 << OrigArg0->getType() << OrigArg1->getType()
Chris Lattner8ba580c2008-11-19 05:08:23 +0000476 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
Chris Lattner7c8d1af2007-12-20 00:26:33 +0000477
478 return false;
479}
480
Eli Friedman8c50c622008-05-20 08:23:37 +0000481bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) {
482 // The signature for these builtins is exact; the only thing we need
483 // to check is that the argument is a constant.
484 SourceLocation Loc;
Chris Lattner941c0102008-08-10 02:05:13 +0000485 if (!TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc))
Chris Lattner8ba580c2008-11-19 05:08:23 +0000486 return Diag(Loc, diag::err_stack_const_level) << TheCall->getSourceRange();
Chris Lattner941c0102008-08-10 02:05:13 +0000487
Eli Friedman8c50c622008-05-20 08:23:37 +0000488 return false;
489}
490
Eli Friedmand0e9d092008-05-14 19:38:39 +0000491/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
492// This is declared to take (...), so we have to check everything.
Sebastian Redl8b769972009-01-19 00:08:26 +0000493Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Eli Friedmand0e9d092008-05-14 19:38:39 +0000494 if (TheCall->getNumArgs() < 3)
Sebastian Redl8b769972009-01-19 00:08:26 +0000495 return ExprError(Diag(TheCall->getLocEnd(),
496 diag::err_typecheck_call_too_few_args)
497 << 0 /*function call*/ << TheCall->getSourceRange());
Eli Friedmand0e9d092008-05-14 19:38:39 +0000498
499 QualType FAType = TheCall->getArg(0)->getType();
500 QualType SAType = TheCall->getArg(1)->getType();
501
502 if (!FAType->isVectorType() || !SAType->isVectorType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000503 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
504 << SourceRange(TheCall->getArg(0)->getLocStart(),
505 TheCall->getArg(1)->getLocEnd());
Sebastian Redl8b769972009-01-19 00:08:26 +0000506 return ExprError();
Eli Friedmand0e9d092008-05-14 19:38:39 +0000507 }
508
Chris Lattnerd5a56aa2008-07-26 22:17:49 +0000509 if (Context.getCanonicalType(FAType).getUnqualifiedType() !=
510 Context.getCanonicalType(SAType).getUnqualifiedType()) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000511 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
512 << SourceRange(TheCall->getArg(0)->getLocStart(),
513 TheCall->getArg(1)->getLocEnd());
Sebastian Redl8b769972009-01-19 00:08:26 +0000514 return ExprError();
Eli Friedmand0e9d092008-05-14 19:38:39 +0000515 }
516
517 unsigned numElements = FAType->getAsVectorType()->getNumElements();
518 if (TheCall->getNumArgs() != numElements+2) {
519 if (TheCall->getNumArgs() < numElements+2)
Sebastian Redl8b769972009-01-19 00:08:26 +0000520 return ExprError(Diag(TheCall->getLocEnd(),
521 diag::err_typecheck_call_too_few_args)
522 << 0 /*function call*/ << TheCall->getSourceRange());
523 return ExprError(Diag(TheCall->getLocEnd(),
524 diag::err_typecheck_call_too_many_args)
525 << 0 /*function call*/ << TheCall->getSourceRange());
Eli Friedmand0e9d092008-05-14 19:38:39 +0000526 }
527
528 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
529 llvm::APSInt Result(32);
Chris Lattner941c0102008-08-10 02:05:13 +0000530 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
Sebastian Redl8b769972009-01-19 00:08:26 +0000531 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000532 diag::err_shufflevector_nonconstant_argument)
Sebastian Redl8b769972009-01-19 00:08:26 +0000533 << TheCall->getArg(i)->getSourceRange());
534
Chris Lattner941c0102008-08-10 02:05:13 +0000535 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl8b769972009-01-19 00:08:26 +0000536 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000537 diag::err_shufflevector_argument_too_large)
Sebastian Redl8b769972009-01-19 00:08:26 +0000538 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand0e9d092008-05-14 19:38:39 +0000539 }
540
541 llvm::SmallVector<Expr*, 32> exprs;
542
Chris Lattner941c0102008-08-10 02:05:13 +0000543 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand0e9d092008-05-14 19:38:39 +0000544 exprs.push_back(TheCall->getArg(i));
545 TheCall->setArg(i, 0);
546 }
547
Ted Kremenek0c97e042009-02-07 01:47:29 +0000548 return Owned(new (Context) ShuffleVectorExpr(exprs.begin(), numElements+2,
549 FAType,
550 TheCall->getCallee()->getLocStart(),
551 TheCall->getRParenLoc()));
Eli Friedmand0e9d092008-05-14 19:38:39 +0000552}
Chris Lattnerf22a8502007-12-19 23:59:04 +0000553
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000554/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
555// This is declared to take (const void*, ...) and can take two
556// optional constant int args.
557bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000558 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000559
Chris Lattner8ba580c2008-11-19 05:08:23 +0000560 if (NumArgs > 3)
561 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args)
Chris Lattner66beaba2008-11-21 18:44:24 +0000562 << 0 /*function call*/ << TheCall->getSourceRange();
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000563
564 // Argument 0 is checked for us and the remaining arguments must be
565 // constant integers.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000566 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000567 Expr *Arg = TheCall->getArg(i);
568 QualType RWType = Arg->getType();
569
570 const BuiltinType *BT = RWType->getAsBuiltinType();
Daniel Dunbar30ad42d2008-09-03 21:13:56 +0000571 llvm::APSInt Result;
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000572 if (!BT || BT->getKind() != BuiltinType::Int ||
Chris Lattner8ba580c2008-11-19 05:08:23 +0000573 !Arg->isIntegerConstantExpr(Result, Context))
574 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument)
575 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000576
577 // FIXME: gcc issues a warning and rewrites these to 0. These
578 // seems especially odd for the third argument since the default
579 // is 3.
Chris Lattner8ba580c2008-11-19 05:08:23 +0000580 if (i == 1) {
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000581 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 1)
Chris Lattner8ba580c2008-11-19 05:08:23 +0000582 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
583 << "0" << "1" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000584 } else {
585 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3)
Chris Lattner8ba580c2008-11-19 05:08:23 +0000586 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
587 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000588 }
589 }
590
Chris Lattner8ba580c2008-11-19 05:08:23 +0000591 return false;
Daniel Dunbar5b0de852008-07-21 22:59:13 +0000592}
593
Daniel Dunbar30ad42d2008-09-03 21:13:56 +0000594/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
595/// int type). This simply type checks that type is one of the defined
596/// constants (0-3).
597bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
598 Expr *Arg = TheCall->getArg(1);
599 QualType ArgType = Arg->getType();
600 const BuiltinType *BT = ArgType->getAsBuiltinType();
601 llvm::APSInt Result(32);
602 if (!BT || BT->getKind() != BuiltinType::Int ||
603 !Arg->isIntegerConstantExpr(Result, Context)) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000604 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
605 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar30ad42d2008-09-03 21:13:56 +0000606 }
607
608 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattner8ba580c2008-11-19 05:08:23 +0000609 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
610 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar30ad42d2008-09-03 21:13:56 +0000611 }
612
613 return false;
614}
615
Eli Friedman5e0ae472009-05-03 06:04:26 +0000616/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedman6277e402009-05-03 04:46:36 +0000617/// This checks that val is a constant 1.
618bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
619 Expr *Arg = TheCall->getArg(1);
620 llvm::APSInt Result(32);
621 if (!Arg->isIntegerConstantExpr(Result, Context) || Result != 1)
622 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
623 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
624
625 return false;
626}
627
Ted Kremenek8c797c02009-01-12 23:09:09 +0000628// Handle i > 1 ? "x" : "y", recursivelly
Ted Kremenek51787c72009-03-20 21:35:28 +0000629bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
630 bool HasVAListArg,
Douglas Gregorb5af7382009-02-14 18:57:46 +0000631 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenek8c797c02009-01-12 23:09:09 +0000632
633 switch (E->getStmtClass()) {
634 case Stmt::ConditionalOperatorClass: {
Ted Kremenek51787c72009-03-20 21:35:28 +0000635 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Ted Kremenek8c797c02009-01-12 23:09:09 +0000636 return SemaCheckStringLiteral(C->getLHS(), TheCall,
Douglas Gregorb5af7382009-02-14 18:57:46 +0000637 HasVAListArg, format_idx, firstDataArg)
Ted Kremenek8c797c02009-01-12 23:09:09 +0000638 && SemaCheckStringLiteral(C->getRHS(), TheCall,
Douglas Gregorb5af7382009-02-14 18:57:46 +0000639 HasVAListArg, format_idx, firstDataArg);
Ted Kremenek8c797c02009-01-12 23:09:09 +0000640 }
641
642 case Stmt::ImplicitCastExprClass: {
Ted Kremenek51787c72009-03-20 21:35:28 +0000643 const ImplicitCastExpr *Expr = cast<ImplicitCastExpr>(E);
Ted Kremenek8c797c02009-01-12 23:09:09 +0000644 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregorb5af7382009-02-14 18:57:46 +0000645 format_idx, firstDataArg);
Ted Kremenek8c797c02009-01-12 23:09:09 +0000646 }
647
648 case Stmt::ParenExprClass: {
Ted Kremenek51787c72009-03-20 21:35:28 +0000649 const ParenExpr *Expr = cast<ParenExpr>(E);
Ted Kremenek8c797c02009-01-12 23:09:09 +0000650 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregorb5af7382009-02-14 18:57:46 +0000651 format_idx, firstDataArg);
Ted Kremenek8c797c02009-01-12 23:09:09 +0000652 }
Ted Kremenek51787c72009-03-20 21:35:28 +0000653
654 case Stmt::DeclRefExprClass: {
655 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
656
657 // As an exception, do not flag errors for variables binding to
658 // const string literals.
659 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
660 bool isConstant = false;
661 QualType T = DR->getType();
Ted Kremenek8c797c02009-01-12 23:09:09 +0000662
Ted Kremenek51787c72009-03-20 21:35:28 +0000663 if (const ArrayType *AT = Context.getAsArrayType(T)) {
664 isConstant = AT->getElementType().isConstant(Context);
665 }
666 else if (const PointerType *PT = T->getAsPointerType()) {
667 isConstant = T.isConstant(Context) &&
668 PT->getPointeeType().isConstant(Context);
669 }
670
671 if (isConstant) {
672 const VarDecl *Def = 0;
673 if (const Expr *Init = VD->getDefinition(Def))
674 return SemaCheckStringLiteral(Init, TheCall,
675 HasVAListArg, format_idx, firstDataArg);
676 }
677 }
678
679 return false;
680 }
Ted Kremenek8c797c02009-01-12 23:09:09 +0000681
Ted Kremenek51787c72009-03-20 21:35:28 +0000682 case Stmt::ObjCStringLiteralClass:
683 case Stmt::StringLiteralClass: {
684 const StringLiteral *StrE = NULL;
685
686 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek8c797c02009-01-12 23:09:09 +0000687 StrE = ObjCFExpr->getString();
688 else
Ted Kremenek51787c72009-03-20 21:35:28 +0000689 StrE = cast<StringLiteral>(E);
690
Ted Kremenek8c797c02009-01-12 23:09:09 +0000691 if (StrE) {
Douglas Gregorb5af7382009-02-14 18:57:46 +0000692 CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx,
693 firstDataArg);
Ted Kremenek8c797c02009-01-12 23:09:09 +0000694 return true;
695 }
696
697 return false;
698 }
Ted Kremenek51787c72009-03-20 21:35:28 +0000699
700 default:
701 return false;
Ted Kremenek8c797c02009-01-12 23:09:09 +0000702 }
703}
704
705
Chris Lattner2e64c072007-08-10 20:18:51 +0000706/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Ted Kremenek081ed872007-08-14 17:39:48 +0000707/// correct use of format strings.
708///
709/// HasVAListArg - A predicate indicating whether the printf-like
710/// function is passed an explicit va_arg argument (e.g., vprintf)
711///
712/// format_idx - The index into Args for the format string.
713///
714/// Improper format strings to functions in the printf family can be
715/// the source of bizarre bugs and very serious security holes. A
716/// good source of information is available in the following paper
717/// (which includes additional references):
Chris Lattner2e64c072007-08-10 20:18:51 +0000718///
719/// FormatGuard: Automatic Protection From printf Format String
720/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremenek081ed872007-08-14 17:39:48 +0000721///
722/// Functionality implemented:
723///
724/// We can statically check the following properties for string
725/// literal format strings for non v.*printf functions (where the
726/// arguments are passed directly):
727//
728/// (1) Are the number of format conversions equal to the number of
729/// data arguments?
730///
731/// (2) Does each format conversion correctly match the type of the
732/// corresponding data argument? (TODO)
733///
734/// Moreover, for all printf functions we can:
735///
736/// (3) Check for a missing format string (when not caught by type checking).
737///
738/// (4) Check for no-operation flags; e.g. using "#" with format
739/// conversion 'c' (TODO)
740///
741/// (5) Check the use of '%n', a major source of security holes.
742///
743/// (6) Check for malformed format conversions that don't specify anything.
744///
745/// (7) Check for empty format strings. e.g: printf("");
746///
747/// (8) Check that the format string is a wide literal.
748///
Ted Kremenekc2804c22008-03-03 16:50:00 +0000749/// (9) Also check the arguments of functions with the __format__ attribute.
750/// (TODO).
751///
Ted Kremenek081ed872007-08-14 17:39:48 +0000752/// All of these checks can be done by parsing the format string.
753///
754/// For now, we ONLY do (1), (3), (5), (6), (7), and (8).
Chris Lattner2e64c072007-08-10 20:18:51 +0000755void
Ted Kremenek51787c72009-03-20 21:35:28 +0000756Sema::CheckPrintfArguments(const CallExpr *TheCall, bool HasVAListArg,
Douglas Gregorb5af7382009-02-14 18:57:46 +0000757 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenek51787c72009-03-20 21:35:28 +0000758 const Expr *Fn = TheCall->getCallee();
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000759
Ted Kremenek081ed872007-08-14 17:39:48 +0000760 // CHECK: printf-like function is called with no format string.
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000761 if (format_idx >= TheCall->getNumArgs()) {
Chris Lattner9d2cf082008-11-19 05:27:50 +0000762 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string)
763 << Fn->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +0000764 return;
765 }
766
Ted Kremenek51787c72009-03-20 21:35:28 +0000767 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Chris Lattnere65acc12007-08-25 05:36:18 +0000768
Chris Lattner2e64c072007-08-10 20:18:51 +0000769 // CHECK: format string is not a string literal.
770 //
Ted Kremenek081ed872007-08-14 17:39:48 +0000771 // Dynamically generated format strings are difficult to
772 // automatically vet at compile time. Requiring that format strings
773 // are string literals: (1) permits the checking of format strings by
774 // the compiler and thereby (2) can practically remove the source of
775 // many format string exploits.
Ted Kremenek225a14c2008-06-16 18:00:42 +0000776
777 // Format string can be either ObjC string (e.g. @"%d") or
778 // C string (e.g. "%d")
779 // ObjC string uses the same format specifiers as C string, so we can use
780 // the same format string checking logic for both ObjC and C strings.
Chris Lattner153b4eb2009-04-29 04:49:34 +0000781 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
782 firstDataArg))
783 return; // Literal format string found, check done!
Ted Kremenek225a14c2008-06-16 18:00:42 +0000784
Chris Lattner153b4eb2009-04-29 04:49:34 +0000785 // For vprintf* functions (i.e., HasVAListArg==true), we add a
786 // special check to see if the format string is a function parameter
787 // of the function calling the printf function. If the function
788 // has an attribute indicating it is a printf-like function, then we
789 // should suppress warnings concerning non-literals being used in a call
790 // to a vprintf function. For example:
791 //
792 // void
793 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...) {
794 // va_list ap;
795 // va_start(ap, fmt);
796 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
797 // ...
798 //
799 //
800 // FIXME: We don't have full attribute support yet, so just check to see
801 // if the argument is a DeclRefExpr that references a parameter. We'll
802 // add proper support for checking the attribute later.
803 if (HasVAListArg)
804 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OrigFormatExpr))
805 if (isa<ParmVarDecl>(DR->getDecl()))
806 return;
Ted Kremenek8c797c02009-01-12 23:09:09 +0000807
Chris Lattner8ba7cc72009-04-29 04:59:47 +0000808 // If there are no arguments specified, warn with -Wformat-security, otherwise
809 // warn only with -Wformat-nonliteral.
810 if (TheCall->getNumArgs() == format_idx+1)
811 Diag(TheCall->getArg(format_idx)->getLocStart(),
812 diag::warn_printf_nonliteral_noargs)
813 << OrigFormatExpr->getSourceRange();
814 else
815 Diag(TheCall->getArg(format_idx)->getLocStart(),
816 diag::warn_printf_nonliteral)
817 << OrigFormatExpr->getSourceRange();
Ted Kremenek8c797c02009-01-12 23:09:09 +0000818}
Ted Kremenek081ed872007-08-14 17:39:48 +0000819
Ted Kremenek51787c72009-03-20 21:35:28 +0000820void Sema::CheckPrintfString(const StringLiteral *FExpr,
821 const Expr *OrigFormatExpr,
822 const CallExpr *TheCall, bool HasVAListArg,
823 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenek8c797c02009-01-12 23:09:09 +0000824
Ted Kremenek51787c72009-03-20 21:35:28 +0000825 const ObjCStringLiteral *ObjCFExpr =
826 dyn_cast<ObjCStringLiteral>(OrigFormatExpr);
827
Ted Kremenek081ed872007-08-14 17:39:48 +0000828 // CHECK: is the format string a wide literal?
829 if (FExpr->isWide()) {
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000830 Diag(FExpr->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000831 diag::warn_printf_format_string_is_wide_literal)
832 << OrigFormatExpr->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +0000833 return;
834 }
835
836 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner44c5c012009-04-29 04:12:34 +0000837 const char *Str = FExpr->getStrData();
Ted Kremenek081ed872007-08-14 17:39:48 +0000838
839 // CHECK: empty format string?
Chris Lattner44c5c012009-04-29 04:12:34 +0000840 unsigned StrLen = FExpr->getByteLength();
Ted Kremenek081ed872007-08-14 17:39:48 +0000841
842 if (StrLen == 0) {
Chris Lattner9d2cf082008-11-19 05:27:50 +0000843 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string)
844 << OrigFormatExpr->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +0000845 return;
846 }
847
848 // We process the format string using a binary state machine. The
849 // current state is stored in CurrentState.
850 enum {
851 state_OrdChr,
852 state_Conversion
853 } CurrentState = state_OrdChr;
854
855 // numConversions - The number of conversions seen so far. This is
856 // incremented as we traverse the format string.
857 unsigned numConversions = 0;
858
859 // numDataArgs - The number of data arguments after the format
860 // string. This can only be determined for non vprintf-like
861 // functions. For those functions, this value is 1 (the sole
862 // va_arg argument).
Douglas Gregorb5af7382009-02-14 18:57:46 +0000863 unsigned numDataArgs = TheCall->getNumArgs()-firstDataArg;
Ted Kremenek081ed872007-08-14 17:39:48 +0000864
865 // Inspect the format string.
866 unsigned StrIdx = 0;
867
868 // LastConversionIdx - Index within the format string where we last saw
869 // a '%' character that starts a new format conversion.
870 unsigned LastConversionIdx = 0;
871
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000872 for (; StrIdx < StrLen; ++StrIdx) {
Chris Lattner3d5a8f32007-12-28 05:38:24 +0000873
Ted Kremenek081ed872007-08-14 17:39:48 +0000874 // Is the number of detected conversion conversions greater than
875 // the number of matching data arguments? If so, stop.
876 if (!HasVAListArg && numConversions > numDataArgs) break;
877
878 // Handle "\0"
Chris Lattner83bd5eb2007-12-28 05:29:59 +0000879 if (Str[StrIdx] == '\0') {
Ted Kremenek081ed872007-08-14 17:39:48 +0000880 // The string returned by getStrData() is not null-terminated,
881 // so the presence of a null character is likely an error.
Chris Lattnerf17cb362009-02-18 17:49:48 +0000882 Diag(getLocationOfStringLiteralByte(FExpr, StrIdx),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000883 diag::warn_printf_format_string_contains_null_char)
884 << OrigFormatExpr->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +0000885 return;
886 }
887
888 // Ordinary characters (not processing a format conversion).
889 if (CurrentState == state_OrdChr) {
890 if (Str[StrIdx] == '%') {
891 CurrentState = state_Conversion;
892 LastConversionIdx = StrIdx;
893 }
894 continue;
895 }
896
897 // Seen '%'. Now processing a format conversion.
898 switch (Str[StrIdx]) {
Chris Lattner68d88f02007-12-28 05:31:15 +0000899 // Handle dynamic precision or width specifier.
900 case '*': {
901 ++numConversions;
902
903 if (!HasVAListArg && numConversions > numDataArgs) {
Chris Lattnerf17cb362009-02-18 17:49:48 +0000904 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx);
Ted Kremenek035d8792007-10-12 20:51:52 +0000905
Ted Kremenek035d8792007-10-12 20:51:52 +0000906 if (Str[StrIdx-1] == '.')
Chris Lattner9d2cf082008-11-19 05:27:50 +0000907 Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg)
908 << OrigFormatExpr->getSourceRange();
Ted Kremenek035d8792007-10-12 20:51:52 +0000909 else
Chris Lattner9d2cf082008-11-19 05:27:50 +0000910 Diag(Loc, diag::warn_printf_asterisk_width_missing_arg)
911 << OrigFormatExpr->getSourceRange();
Ted Kremenek035d8792007-10-12 20:51:52 +0000912
Chris Lattner68d88f02007-12-28 05:31:15 +0000913 // Don't do any more checking. We'll just emit spurious errors.
914 return;
Ted Kremenek035d8792007-10-12 20:51:52 +0000915 }
Chris Lattner68d88f02007-12-28 05:31:15 +0000916
917 // Perform type checking on width/precision specifier.
Ted Kremenek51787c72009-03-20 21:35:28 +0000918 const Expr *E = TheCall->getArg(format_idx+numConversions);
Chris Lattner68d88f02007-12-28 05:31:15 +0000919 if (const BuiltinType *BT = E->getType()->getAsBuiltinType())
920 if (BT->getKind() == BuiltinType::Int)
921 break;
Ted Kremenek081ed872007-08-14 17:39:48 +0000922
Chris Lattnerf17cb362009-02-18 17:49:48 +0000923 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx);
Chris Lattner68d88f02007-12-28 05:31:15 +0000924
925 if (Str[StrIdx-1] == '.')
Chris Lattner9d2cf082008-11-19 05:27:50 +0000926 Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000927 << E->getType() << E->getSourceRange();
Chris Lattner68d88f02007-12-28 05:31:15 +0000928 else
Chris Lattner9d2cf082008-11-19 05:27:50 +0000929 Diag(Loc, diag::warn_printf_asterisk_width_wrong_type)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000930 << E->getType() << E->getSourceRange();
Chris Lattner68d88f02007-12-28 05:31:15 +0000931
932 break;
933 }
934
935 // Characters which can terminate a format conversion
936 // (e.g. "%d"). Characters that specify length modifiers or
937 // other flags are handled by the default case below.
938 //
939 // FIXME: additional checks will go into the following cases.
940 case 'i':
941 case 'd':
942 case 'o':
943 case 'u':
944 case 'x':
945 case 'X':
946 case 'D':
947 case 'O':
948 case 'U':
949 case 'e':
950 case 'E':
951 case 'f':
952 case 'F':
953 case 'g':
954 case 'G':
955 case 'a':
956 case 'A':
957 case 'c':
958 case 'C':
959 case 'S':
960 case 's':
961 case 'p':
962 ++numConversions;
963 CurrentState = state_OrdChr;
964 break;
965
966 // CHECK: Are we using "%n"? Issue a warning.
967 case 'n': {
968 ++numConversions;
969 CurrentState = state_OrdChr;
Chris Lattnerf17cb362009-02-18 17:49:48 +0000970 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr,
971 LastConversionIdx);
Chris Lattner68d88f02007-12-28 05:31:15 +0000972
Chris Lattner9d2cf082008-11-19 05:27:50 +0000973 Diag(Loc, diag::warn_printf_write_back)<<OrigFormatExpr->getSourceRange();
Chris Lattner68d88f02007-12-28 05:31:15 +0000974 break;
975 }
Ted Kremenek225a14c2008-06-16 18:00:42 +0000976
977 // Handle "%@"
978 case '@':
979 // %@ is allowed in ObjC format strings only.
980 if(ObjCFExpr != NULL)
981 CurrentState = state_OrdChr;
982 else {
983 // Issue a warning: invalid format conversion.
Chris Lattnerf17cb362009-02-18 17:49:48 +0000984 SourceLocation Loc =
985 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Ted Kremenek225a14c2008-06-16 18:00:42 +0000986
Chris Lattner77d52da2008-11-20 06:06:08 +0000987 Diag(Loc, diag::warn_printf_invalid_conversion)
988 << std::string(Str+LastConversionIdx,
989 Str+std::min(LastConversionIdx+2, StrLen))
990 << OrigFormatExpr->getSourceRange();
Ted Kremenek225a14c2008-06-16 18:00:42 +0000991 }
992 ++numConversions;
993 break;
994
Chris Lattner68d88f02007-12-28 05:31:15 +0000995 // Handle "%%"
996 case '%':
997 // Sanity check: Was the first "%" character the previous one?
998 // If not, we will assume that we have a malformed format
999 // conversion, and that the current "%" character is the start
1000 // of a new conversion.
1001 if (StrIdx - LastConversionIdx == 1)
1002 CurrentState = state_OrdChr;
1003 else {
1004 // Issue a warning: invalid format conversion.
Chris Lattnerf17cb362009-02-18 17:49:48 +00001005 SourceLocation Loc =
1006 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Chris Lattner68d88f02007-12-28 05:31:15 +00001007
Chris Lattner77d52da2008-11-20 06:06:08 +00001008 Diag(Loc, diag::warn_printf_invalid_conversion)
1009 << std::string(Str+LastConversionIdx, Str+StrIdx)
1010 << OrigFormatExpr->getSourceRange();
Chris Lattner68d88f02007-12-28 05:31:15 +00001011
1012 // This conversion is broken. Advance to the next format
1013 // conversion.
1014 LastConversionIdx = StrIdx;
1015 ++numConversions;
Ted Kremenek081ed872007-08-14 17:39:48 +00001016 }
Chris Lattner68d88f02007-12-28 05:31:15 +00001017 break;
Ted Kremenek081ed872007-08-14 17:39:48 +00001018
Chris Lattner68d88f02007-12-28 05:31:15 +00001019 default:
1020 // This case catches all other characters: flags, widths, etc.
1021 // We should eventually process those as well.
1022 break;
Ted Kremenek081ed872007-08-14 17:39:48 +00001023 }
1024 }
1025
1026 if (CurrentState == state_Conversion) {
1027 // Issue a warning: invalid format conversion.
Chris Lattnerf17cb362009-02-18 17:49:48 +00001028 SourceLocation Loc =
1029 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Ted Kremenek081ed872007-08-14 17:39:48 +00001030
Chris Lattner77d52da2008-11-20 06:06:08 +00001031 Diag(Loc, diag::warn_printf_invalid_conversion)
1032 << std::string(Str+LastConversionIdx,
1033 Str+std::min(LastConversionIdx+2, StrLen))
1034 << OrigFormatExpr->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +00001035 return;
1036 }
1037
1038 if (!HasVAListArg) {
1039 // CHECK: Does the number of format conversions exceed the number
1040 // of data arguments?
1041 if (numConversions > numDataArgs) {
Chris Lattnerf17cb362009-02-18 17:49:48 +00001042 SourceLocation Loc =
1043 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Ted Kremenek081ed872007-08-14 17:39:48 +00001044
Chris Lattner9d2cf082008-11-19 05:27:50 +00001045 Diag(Loc, diag::warn_printf_insufficient_data_args)
1046 << OrigFormatExpr->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +00001047 }
1048 // CHECK: Does the number of data arguments exceed the number of
1049 // format conversions in the format string?
1050 else if (numConversions < numDataArgs)
Chris Lattner83bd5eb2007-12-28 05:29:59 +00001051 Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(),
Chris Lattner9d2cf082008-11-19 05:27:50 +00001052 diag::warn_printf_too_many_data_args)
1053 << OrigFormatExpr->getSourceRange();
Ted Kremenek081ed872007-08-14 17:39:48 +00001054 }
1055}
Ted Kremenek45925ab2007-08-17 16:46:58 +00001056
1057//===--- CHECK: Return Address of Stack Variable --------------------------===//
1058
1059static DeclRefExpr* EvalVal(Expr *E);
1060static DeclRefExpr* EvalAddr(Expr* E);
1061
1062/// CheckReturnStackAddr - Check if a return statement returns the address
1063/// of a stack variable.
1064void
1065Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1066 SourceLocation ReturnLoc) {
Chris Lattner7a48d9c2008-02-13 01:02:39 +00001067
Ted Kremenek45925ab2007-08-17 16:46:58 +00001068 // Perform checking for returned stack addresses.
Steve Naroffd6163f32008-09-05 22:11:13 +00001069 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Ted Kremenek45925ab2007-08-17 16:46:58 +00001070 if (DeclRefExpr *DR = EvalAddr(RetValExp))
Chris Lattner65cae292008-11-19 08:23:25 +00001071 Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
Chris Lattnerb1753422008-11-23 21:45:46 +00001072 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Steve Naroff503996b2008-09-16 22:25:10 +00001073
1074 // Skip over implicit cast expressions when checking for block expressions.
1075 if (ImplicitCastExpr *IcExpr =
1076 dyn_cast_or_null<ImplicitCastExpr>(RetValExp))
1077 RetValExp = IcExpr->getSubExpr();
1078
Steve Naroff3eac7692008-09-10 19:17:48 +00001079 if (BlockExpr *C = dyn_cast_or_null<BlockExpr>(RetValExp))
Mike Stumpb1a2aab2009-04-17 00:09:41 +00001080 if (C->hasBlockDeclRefExprs())
1081 Diag(C->getLocStart(), diag::err_ret_local_block)
1082 << C->getSourceRange();
Ted Kremenek45925ab2007-08-17 16:46:58 +00001083 }
1084 // Perform checking for stack values returned by reference.
1085 else if (lhsType->isReferenceType()) {
Douglas Gregor21a04f32008-10-27 19:41:14 +00001086 // Check for a reference to the stack
1087 if (DeclRefExpr *DR = EvalVal(RetValExp))
Chris Lattner9d2cf082008-11-19 05:27:50 +00001088 Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
Chris Lattnerb1753422008-11-23 21:45:46 +00001089 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Ted Kremenek45925ab2007-08-17 16:46:58 +00001090 }
1091}
1092
1093/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1094/// check if the expression in a return statement evaluates to an address
1095/// to a location on the stack. The recursion is used to traverse the
1096/// AST of the return expression, with recursion backtracking when we
1097/// encounter a subexpression that (1) clearly does not lead to the address
1098/// of a stack variable or (2) is something we cannot determine leads to
1099/// the address of a stack variable based on such local checking.
1100///
Ted Kremenekda1300a2007-08-28 17:02:55 +00001101/// EvalAddr processes expressions that are pointers that are used as
1102/// references (and not L-values). EvalVal handles all other values.
Ted Kremenek45925ab2007-08-17 16:46:58 +00001103/// At the base case of the recursion is a check for a DeclRefExpr* in
1104/// the refers to a stack variable.
1105///
1106/// This implementation handles:
1107///
1108/// * pointer-to-pointer casts
1109/// * implicit conversions from array references to pointers
1110/// * taking the address of fields
1111/// * arbitrary interplay between "&" and "*" operators
1112/// * pointer arithmetic from an address of a stack variable
1113/// * taking the address of an array element where the array is on the stack
1114static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek45925ab2007-08-17 16:46:58 +00001115 // We should only be called for evaluating pointer expressions.
Steve Naroffd6163f32008-09-05 22:11:13 +00001116 assert((E->getType()->isPointerType() ||
1117 E->getType()->isBlockPointerType() ||
Ted Kremenek42730c52008-01-07 19:49:32 +00001118 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner68d88f02007-12-28 05:31:15 +00001119 "EvalAddr only works on pointers");
Ted Kremenek45925ab2007-08-17 16:46:58 +00001120
1121 // Our "symbolic interpreter" is just a dispatch off the currently
1122 // viewed AST node. We then recursively traverse the AST by calling
1123 // EvalAddr and EvalVal appropriately.
1124 switch (E->getStmtClass()) {
Chris Lattner68d88f02007-12-28 05:31:15 +00001125 case Stmt::ParenExprClass:
1126 // Ignore parentheses.
1127 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek45925ab2007-08-17 16:46:58 +00001128
Chris Lattner68d88f02007-12-28 05:31:15 +00001129 case Stmt::UnaryOperatorClass: {
1130 // The only unary operator that make sense to handle here
1131 // is AddrOf. All others don't make sense as pointers.
1132 UnaryOperator *U = cast<UnaryOperator>(E);
Ted Kremenek45925ab2007-08-17 16:46:58 +00001133
Chris Lattner68d88f02007-12-28 05:31:15 +00001134 if (U->getOpcode() == UnaryOperator::AddrOf)
1135 return EvalVal(U->getSubExpr());
1136 else
Ted Kremenek45925ab2007-08-17 16:46:58 +00001137 return NULL;
1138 }
Chris Lattner68d88f02007-12-28 05:31:15 +00001139
1140 case Stmt::BinaryOperatorClass: {
1141 // Handle pointer arithmetic. All other binary operators are not valid
1142 // in this context.
1143 BinaryOperator *B = cast<BinaryOperator>(E);
1144 BinaryOperator::Opcode op = B->getOpcode();
1145
1146 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
1147 return NULL;
1148
1149 Expr *Base = B->getLHS();
1150
1151 // Determine which argument is the real pointer base. It could be
1152 // the RHS argument instead of the LHS.
1153 if (!Base->getType()->isPointerType()) Base = B->getRHS();
1154
1155 assert (Base->getType()->isPointerType());
1156 return EvalAddr(Base);
1157 }
Steve Naroff3eac7692008-09-10 19:17:48 +00001158
Chris Lattner68d88f02007-12-28 05:31:15 +00001159 // For conditional operators we need to see if either the LHS or RHS are
1160 // valid DeclRefExpr*s. If one of them is valid, we return it.
1161 case Stmt::ConditionalOperatorClass: {
1162 ConditionalOperator *C = cast<ConditionalOperator>(E);
1163
1164 // Handle the GNU extension for missing LHS.
1165 if (Expr *lhsExpr = C->getLHS())
1166 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
1167 return LHS;
1168
1169 return EvalAddr(C->getRHS());
1170 }
1171
Ted Kremenekea19edd2008-08-07 00:49:01 +00001172 // For casts, we need to handle conversions from arrays to
1173 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor21a04f32008-10-27 19:41:14 +00001174 case Stmt::ImplicitCastExprClass:
Douglas Gregor035d0882008-10-28 15:36:24 +00001175 case Stmt::CStyleCastExprClass:
Douglas Gregor21a04f32008-10-27 19:41:14 +00001176 case Stmt::CXXFunctionalCastExprClass: {
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001177 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenekea19edd2008-08-07 00:49:01 +00001178 QualType T = SubExpr->getType();
1179
Steve Naroffd6163f32008-09-05 22:11:13 +00001180 if (SubExpr->getType()->isPointerType() ||
1181 SubExpr->getType()->isBlockPointerType() ||
1182 SubExpr->getType()->isObjCQualifiedIdType())
Ted Kremenekea19edd2008-08-07 00:49:01 +00001183 return EvalAddr(SubExpr);
1184 else if (T->isArrayType())
Chris Lattner68d88f02007-12-28 05:31:15 +00001185 return EvalVal(SubExpr);
Chris Lattner68d88f02007-12-28 05:31:15 +00001186 else
Ted Kremenekea19edd2008-08-07 00:49:01 +00001187 return 0;
Chris Lattner68d88f02007-12-28 05:31:15 +00001188 }
1189
1190 // C++ casts. For dynamic casts, static casts, and const casts, we
1191 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor21a04f32008-10-27 19:41:14 +00001192 // through the cast. In the case the dynamic cast doesn't fail (and
1193 // return NULL), we take the conservative route and report cases
Chris Lattner68d88f02007-12-28 05:31:15 +00001194 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor21a04f32008-10-27 19:41:14 +00001195 // FIXME: The comment about is wrong; we're not always converting
1196 // from pointer to pointer. I'm guessing that this code should also
1197 // handle references to objects.
1198 case Stmt::CXXStaticCastExprClass:
1199 case Stmt::CXXDynamicCastExprClass:
1200 case Stmt::CXXConstCastExprClass:
1201 case Stmt::CXXReinterpretCastExprClass: {
1202 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffd6163f32008-09-05 22:11:13 +00001203 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Chris Lattner68d88f02007-12-28 05:31:15 +00001204 return EvalAddr(S);
1205 else
1206 return NULL;
Chris Lattner68d88f02007-12-28 05:31:15 +00001207 }
1208
1209 // Everything else: we simply don't reason about them.
1210 default:
1211 return NULL;
1212 }
Ted Kremenek45925ab2007-08-17 16:46:58 +00001213}
1214
1215
1216/// EvalVal - This function is complements EvalAddr in the mutual recursion.
1217/// See the comments for EvalAddr for more details.
1218static DeclRefExpr* EvalVal(Expr *E) {
1219
Ted Kremenekda1300a2007-08-28 17:02:55 +00001220 // We should only be called for evaluating non-pointer expressions, or
1221 // expressions with a pointer type that are not used as references but instead
1222 // are l-values (e.g., DeclRefExpr with a pointer type).
1223
Ted Kremenek45925ab2007-08-17 16:46:58 +00001224 // Our "symbolic interpreter" is just a dispatch off the currently
1225 // viewed AST node. We then recursively traverse the AST by calling
1226 // EvalAddr and EvalVal appropriately.
1227 switch (E->getStmtClass()) {
Douglas Gregor566782a2009-01-06 05:10:23 +00001228 case Stmt::DeclRefExprClass:
1229 case Stmt::QualifiedDeclRefExprClass: {
Ted Kremenek45925ab2007-08-17 16:46:58 +00001230 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
1231 // at code that refers to a variable's name. We check if it has local
1232 // storage within the function, and if so, return the expression.
1233 DeclRefExpr *DR = cast<DeclRefExpr>(E);
1234
1235 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Douglas Gregor81c29152008-10-29 00:13:59 +00001236 if(V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
Ted Kremenek45925ab2007-08-17 16:46:58 +00001237
1238 return NULL;
1239 }
1240
1241 case Stmt::ParenExprClass:
1242 // Ignore parentheses.
1243 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
1244
1245 case Stmt::UnaryOperatorClass: {
1246 // The only unary operator that make sense to handle here
1247 // is Deref. All others don't resolve to a "name." This includes
1248 // handling all sorts of rvalues passed to a unary operator.
1249 UnaryOperator *U = cast<UnaryOperator>(E);
1250
1251 if (U->getOpcode() == UnaryOperator::Deref)
1252 return EvalAddr(U->getSubExpr());
1253
1254 return NULL;
1255 }
1256
1257 case Stmt::ArraySubscriptExprClass: {
1258 // Array subscripts are potential references to data on the stack. We
1259 // retrieve the DeclRefExpr* for the array variable if it indeed
1260 // has local storage.
Ted Kremenek1c1700f2007-08-20 16:18:38 +00001261 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek45925ab2007-08-17 16:46:58 +00001262 }
1263
1264 case Stmt::ConditionalOperatorClass: {
1265 // For conditional operators we need to see if either the LHS or RHS are
1266 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
1267 ConditionalOperator *C = cast<ConditionalOperator>(E);
1268
Anders Carlsson37365fc2007-11-30 19:04:31 +00001269 // Handle the GNU extension for missing LHS.
1270 if (Expr *lhsExpr = C->getLHS())
1271 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
1272 return LHS;
1273
1274 return EvalVal(C->getRHS());
Ted Kremenek45925ab2007-08-17 16:46:58 +00001275 }
1276
1277 // Accesses to members are potential references to data on the stack.
1278 case Stmt::MemberExprClass: {
1279 MemberExpr *M = cast<MemberExpr>(E);
1280
1281 // Check for indirect access. We only want direct field accesses.
1282 if (!M->isArrow())
1283 return EvalVal(M->getBase());
1284 else
1285 return NULL;
1286 }
1287
1288 // Everything else: we simply don't reason about them.
1289 default:
1290 return NULL;
1291 }
1292}
Ted Kremenek30c66752007-11-25 00:58:00 +00001293
1294//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
1295
1296/// Check for comparisons of floating point operands using != and ==.
1297/// Issue a warning if these are no self-comparisons, as they are not likely
1298/// to do what the programmer intended.
1299void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
1300 bool EmitWarning = true;
1301
Ted Kremenek87e30c52008-01-17 16:57:34 +00001302 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek24c61682008-01-17 17:55:13 +00001303 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek30c66752007-11-25 00:58:00 +00001304
1305 // Special case: check for x == x (which is OK).
1306 // Do not emit warnings for such cases.
1307 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
1308 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
1309 if (DRL->getDecl() == DRR->getDecl())
1310 EmitWarning = false;
1311
Ted Kremenek33159832007-11-29 00:59:04 +00001312
1313 // Special case: check for comparisons against literals that can be exactly
1314 // represented by APFloat. In such cases, do not emit a warning. This
1315 // is a heuristic: often comparison against such literals are used to
1316 // detect if a value in a variable has not changed. This clearly can
1317 // lead to false negatives.
1318 if (EmitWarning) {
1319 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
1320 if (FLL->isExact())
1321 EmitWarning = false;
1322 }
1323 else
1324 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
1325 if (FLR->isExact())
1326 EmitWarning = false;
1327 }
1328 }
1329
Ted Kremenek30c66752007-11-25 00:58:00 +00001330 // Check for comparisons with builtin types.
Sebastian Redl8b769972009-01-19 00:08:26 +00001331 if (EmitWarning)
Ted Kremenek30c66752007-11-25 00:58:00 +00001332 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregorb5af7382009-02-14 18:57:46 +00001333 if (CL->isBuiltinCall(Context))
Ted Kremenek30c66752007-11-25 00:58:00 +00001334 EmitWarning = false;
1335
Sebastian Redl8b769972009-01-19 00:08:26 +00001336 if (EmitWarning)
Ted Kremenek30c66752007-11-25 00:58:00 +00001337 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregorb5af7382009-02-14 18:57:46 +00001338 if (CR->isBuiltinCall(Context))
Ted Kremenek30c66752007-11-25 00:58:00 +00001339 EmitWarning = false;
1340
1341 // Emit the diagnostic.
1342 if (EmitWarning)
Chris Lattner8ba580c2008-11-19 05:08:23 +00001343 Diag(loc, diag::warn_floatingpoint_eq)
1344 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek30c66752007-11-25 00:58:00 +00001345}