blob: 22dcc49b55458556ff350fb0eb04f686cf33d9ac [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);
Chris Lattner5caa3702009-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:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000147 case Builtin::BI__sync_fetch_and_nand:
Chris Lattner5caa3702009-05-08 06:58:22 +0000148 case Builtin::BI__sync_add_and_fetch:
149 case Builtin::BI__sync_sub_and_fetch:
150 case Builtin::BI__sync_and_and_fetch:
151 case Builtin::BI__sync_or_and_fetch:
152 case Builtin::BI__sync_xor_and_fetch:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000153 case Builtin::BI__sync_nand_and_fetch:
Chris Lattner5caa3702009-05-08 06:58:22 +0000154 case Builtin::BI__sync_val_compare_and_swap:
155 case Builtin::BI__sync_bool_compare_and_swap:
156 case Builtin::BI__sync_lock_test_and_set:
157 case Builtin::BI__sync_lock_release:
158 if (SemaBuiltinAtomicOverloaded(TheCall))
159 return ExprError();
160 return move(TheCallResult);
Anders Carlsson71993dd2007-08-17 05:31:46 +0000161 }
Daniel Dunbarde454282008-10-02 18:44:07 +0000162
163 // FIXME: This mechanism should be abstracted to be less fragile and
164 // more efficient. For example, just map function ids to custom
165 // handlers.
166
Chris Lattner59907c42007-08-10 20:18:51 +0000167 // Printf checking.
Douglas Gregor3c385e52009-02-14 18:57:46 +0000168 if (const FormatAttr *Format = FDecl->getAttr<FormatAttr>()) {
169 if (Format->getType() == "printf") {
Ted Kremenek3d692df2009-02-27 17:58:43 +0000170 bool HasVAListArg = Format->getFirstArg() == 0;
171 if (!HasVAListArg) {
172 if (const FunctionProtoType *Proto
173 = FDecl->getType()->getAsFunctionProtoType())
Douglas Gregor3c385e52009-02-14 18:57:46 +0000174 HasVAListArg = !Proto->isVariadic();
Ted Kremenek3d692df2009-02-27 17:58:43 +0000175 }
Douglas Gregor3c385e52009-02-14 18:57:46 +0000176 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
Ted Kremenek3d692df2009-02-27 17:58:43 +0000177 HasVAListArg ? 0 : Format->getFirstArg() - 1);
Douglas Gregor3c385e52009-02-14 18:57:46 +0000178 }
Chris Lattner59907c42007-08-10 20:18:51 +0000179 }
Sebastian Redl0eb23302009-01-19 00:08:26 +0000180
181 return move(TheCallResult);
Anders Carlsson71993dd2007-08-17 05:31:46 +0000182}
183
Chris Lattner5caa3702009-05-08 06:58:22 +0000184/// SemaBuiltinAtomicOverloaded - We have a call to a function like
185/// __sync_fetch_and_add, which is an overloaded function based on the pointer
186/// type of its first argument. The main ActOnCallExpr routines have already
187/// promoted the types of arguments because all of these calls are prototyped as
188/// void(...).
189///
190/// This function goes through and does final semantic checking for these
191/// builtins,
192bool Sema::SemaBuiltinAtomicOverloaded(CallExpr *TheCall) {
193 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
194 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
195
196 // Ensure that we have at least one argument to do type inference from.
197 if (TheCall->getNumArgs() < 1)
198 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
199 << 0 << TheCall->getCallee()->getSourceRange();
200
201 // Inspect the first argument of the atomic builtin. This should always be
202 // a pointer type, whose element is an integral scalar or pointer type.
203 // Because it is a pointer type, we don't have to worry about any implicit
204 // casts here.
205 Expr *FirstArg = TheCall->getArg(0);
206 if (!FirstArg->getType()->isPointerType())
207 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
208 << FirstArg->getType() << FirstArg->getSourceRange();
209
210 QualType ValType = FirstArg->getType()->getAsPointerType()->getPointeeType();
211 if (!ValType->isIntegerType() && !ValType->isPointerType() &&
212 !ValType->isBlockPointerType())
213 return Diag(DRE->getLocStart(),
214 diag::err_atomic_builtin_must_be_pointer_intptr)
215 << FirstArg->getType() << FirstArg->getSourceRange();
216
217 // We need to figure out which concrete builtin this maps onto. For example,
218 // __sync_fetch_and_add with a 2 byte object turns into
219 // __sync_fetch_and_add_2.
220#define BUILTIN_ROW(x) \
221 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
222 Builtin::BI##x##_8, Builtin::BI##x##_16 }
223
224 static const unsigned BuiltinIndices[][5] = {
225 BUILTIN_ROW(__sync_fetch_and_add),
226 BUILTIN_ROW(__sync_fetch_and_sub),
227 BUILTIN_ROW(__sync_fetch_and_or),
228 BUILTIN_ROW(__sync_fetch_and_and),
229 BUILTIN_ROW(__sync_fetch_and_xor),
Chris Lattnereebd9d22009-05-13 04:37:52 +0000230 BUILTIN_ROW(__sync_fetch_and_nand),
Chris Lattner5caa3702009-05-08 06:58:22 +0000231
232 BUILTIN_ROW(__sync_add_and_fetch),
233 BUILTIN_ROW(__sync_sub_and_fetch),
234 BUILTIN_ROW(__sync_and_and_fetch),
235 BUILTIN_ROW(__sync_or_and_fetch),
236 BUILTIN_ROW(__sync_xor_and_fetch),
Chris Lattnereebd9d22009-05-13 04:37:52 +0000237 BUILTIN_ROW(__sync_nand_and_fetch),
Chris Lattner5caa3702009-05-08 06:58:22 +0000238
239 BUILTIN_ROW(__sync_val_compare_and_swap),
240 BUILTIN_ROW(__sync_bool_compare_and_swap),
241 BUILTIN_ROW(__sync_lock_test_and_set),
242 BUILTIN_ROW(__sync_lock_release)
243 };
244#undef BUILTIN_ROW
245
246 // Determine the index of the size.
247 unsigned SizeIndex;
248 switch (Context.getTypeSize(ValType)/8) {
249 case 1: SizeIndex = 0; break;
250 case 2: SizeIndex = 1; break;
251 case 4: SizeIndex = 2; break;
252 case 8: SizeIndex = 3; break;
253 case 16: SizeIndex = 4; break;
254 default:
255 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
256 << FirstArg->getType() << FirstArg->getSourceRange();
257 }
258
259 // Each of these builtins has one pointer argument, followed by some number of
260 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
261 // that we ignore. Find out which row of BuiltinIndices to read from as well
262 // as the number of fixed args.
263 unsigned BuiltinID = FDecl->getBuiltinID(Context);
264 unsigned BuiltinIndex, NumFixed = 1;
265 switch (BuiltinID) {
266 default: assert(0 && "Unknown overloaded atomic builtin!");
267 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
268 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
269 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
270 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
271 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Chris Lattnereebd9d22009-05-13 04:37:52 +0000272 case Builtin::BI__sync_fetch_and_nand:BuiltinIndex = 5; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000273
Chris Lattnereebd9d22009-05-13 04:37:52 +0000274 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 6; break;
275 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 7; break;
276 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 8; break;
277 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 9; break;
278 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex =10; break;
279 case Builtin::BI__sync_nand_and_fetch:BuiltinIndex =11; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000280
281 case Builtin::BI__sync_val_compare_and_swap:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000282 BuiltinIndex = 12;
Chris Lattner5caa3702009-05-08 06:58:22 +0000283 NumFixed = 2;
284 break;
285 case Builtin::BI__sync_bool_compare_and_swap:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000286 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000287 NumFixed = 2;
288 break;
Chris Lattnereebd9d22009-05-13 04:37:52 +0000289 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 14; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000290 case Builtin::BI__sync_lock_release:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000291 BuiltinIndex = 15;
Chris Lattner5caa3702009-05-08 06:58:22 +0000292 NumFixed = 0;
293 break;
294 }
295
296 // Now that we know how many fixed arguments we expect, first check that we
297 // have at least that many.
298 if (TheCall->getNumArgs() < 1+NumFixed)
299 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
300 << 0 << TheCall->getCallee()->getSourceRange();
301
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000302
303 // Get the decl for the concrete builtin from this, we can tell what the
304 // concrete integer type we should convert to is.
305 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
306 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
307 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
308 FunctionDecl *NewBuiltinDecl =
309 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
310 TUScope, false, DRE->getLocStart()));
311 const FunctionProtoType *BuiltinFT =
312 NewBuiltinDecl->getType()->getAsFunctionProtoType();
313 ValType = BuiltinFT->getArgType(0)->getAsPointerType()->getPointeeType();
314
315 // If the first type needs to be converted (e.g. void** -> int*), do it now.
316 if (BuiltinFT->getArgType(0) != FirstArg->getType()) {
317 ImpCastExprToType(FirstArg, BuiltinFT->getArgType(0), false);
318 TheCall->setArg(0, FirstArg);
319 }
320
Chris Lattner5caa3702009-05-08 06:58:22 +0000321 // Next, walk the valid ones promoting to the right type.
322 for (unsigned i = 0; i != NumFixed; ++i) {
323 Expr *Arg = TheCall->getArg(i+1);
324
325 // If the argument is an implicit cast, then there was a promotion due to
326 // "...", just remove it now.
327 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
328 Arg = ICE->getSubExpr();
329 ICE->setSubExpr(0);
330 ICE->Destroy(Context);
331 TheCall->setArg(i+1, Arg);
332 }
333
334 // GCC does an implicit conversion to the pointer or integer ValType. This
335 // can fail in some cases (1i -> int**), check for this error case now.
336 if (CheckCastTypes(Arg->getSourceRange(), ValType, Arg))
337 return true;
338
339 // Okay, we have something that *can* be converted to the right type. Check
340 // to see if there is a potentially weird extension going on here. This can
341 // happen when you do an atomic operation on something like an char* and
342 // pass in 42. The 42 gets converted to char. This is even more strange
343 // for things like 45.123 -> char, etc.
344 // FIXME: Do this check.
345 ImpCastExprToType(Arg, ValType, false);
346 TheCall->setArg(i+1, Arg);
347 }
348
Chris Lattner5caa3702009-05-08 06:58:22 +0000349 // Switch the DeclRefExpr to refer to the new decl.
350 DRE->setDecl(NewBuiltinDecl);
351 DRE->setType(NewBuiltinDecl->getType());
352
353 // Set the callee in the CallExpr.
354 // FIXME: This leaks the original parens and implicit casts.
355 Expr *PromotedCall = DRE;
356 UsualUnaryConversions(PromotedCall);
357 TheCall->setCallee(PromotedCall);
358
359
360 // Change the result type of the call to match the result type of the decl.
361 TheCall->setType(NewBuiltinDecl->getResultType());
362 return false;
363}
364
365
Chris Lattner69039812009-02-18 06:01:06 +0000366/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000367/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +0000368/// FIXME: GCC currently emits the following warning:
369/// "warning: input conversion stopped due to an input byte that does not
370/// belong to the input codeset UTF-8"
371/// Note: It might also make sense to do the UTF-16 conversion here (would
372/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +0000373bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000374 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000375 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
376
377 if (!Literal || Literal->isWide()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000378 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
379 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000380 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000381 }
382
383 const char *Data = Literal->getStrData();
384 unsigned Length = Literal->getByteLength();
385
386 for (unsigned i = 0; i < Length; ++i) {
Anders Carlsson71993dd2007-08-17 05:31:46 +0000387 if (!Data[i]) {
Chris Lattner60800082009-02-18 17:49:48 +0000388 Diag(getLocationOfStringLiteralByte(Literal, i),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000389 diag::warn_cfstring_literal_contains_nul_character)
390 << Arg->getSourceRange();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000391 break;
392 }
393 }
394
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000395 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000396}
397
Chris Lattnerc27c6652007-12-20 00:05:45 +0000398/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
399/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000400bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
401 Expr *Fn = TheCall->getCallee();
402 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000403 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000404 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000405 << 0 /*function call*/ << Fn->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000406 << SourceRange(TheCall->getArg(2)->getLocStart(),
407 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000408 return true;
409 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000410
411 if (TheCall->getNumArgs() < 2) {
412 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
413 << 0 /*function call*/;
414 }
415
Chris Lattnerc27c6652007-12-20 00:05:45 +0000416 // Determine whether the current function is variadic or not.
417 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000418 if (CurBlock)
419 isVariadic = CurBlock->isVariadic;
420 else if (getCurFunctionDecl()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000421 if (FunctionProtoType* FTP =
422 dyn_cast<FunctionProtoType>(getCurFunctionDecl()->getType()))
Eli Friedman56f20ae2008-12-15 22:05:35 +0000423 isVariadic = FTP->isVariadic();
424 else
425 isVariadic = false;
426 } else {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000427 isVariadic = getCurMethodDecl()->isVariadic();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000428 }
Chris Lattner30ce3442007-12-19 23:59:04 +0000429
Chris Lattnerc27c6652007-12-20 00:05:45 +0000430 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000431 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
432 return true;
433 }
434
435 // Verify that the second argument to the builtin is the last argument of the
436 // current function or method.
437 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000438 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Anders Carlsson88cf2262008-02-11 04:20:54 +0000439
440 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
441 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000442 // FIXME: This isn't correct for methods (results in bogus warning).
443 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000444 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000445 if (CurBlock)
446 LastArg = *(CurBlock->TheDecl->param_end()-1);
447 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +0000448 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000449 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000450 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000451 SecondArgIsLastNamedArgument = PV == LastArg;
452 }
453 }
454
455 if (!SecondArgIsLastNamedArgument)
Chris Lattner925e60d2007-12-28 05:29:59 +0000456 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000457 diag::warn_second_parameter_of_va_start_not_last_named_argument);
458 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000459}
Chris Lattner30ce3442007-12-19 23:59:04 +0000460
Chris Lattner1b9a0792007-12-20 00:26:33 +0000461/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
462/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000463bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
464 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000465 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
466 << 0 /*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000467 if (TheCall->getNumArgs() > 2)
468 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000469 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000470 << 0 /*function call*/
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000471 << SourceRange(TheCall->getArg(2)->getLocStart(),
472 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner1b9a0792007-12-20 00:26:33 +0000473
Chris Lattner925e60d2007-12-28 05:29:59 +0000474 Expr *OrigArg0 = TheCall->getArg(0);
475 Expr *OrigArg1 = TheCall->getArg(1);
Chris Lattner1b9a0792007-12-20 00:26:33 +0000476
477 // Do standard promotions between the two arguments, returning their common
478 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000479 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Daniel Dunbar403bc2b2009-02-19 19:28:43 +0000480
481 // Make sure any conversions are pushed back into the call; this is
482 // type safe since unordered compare builtins are declared as "_Bool
483 // foo(...)".
484 TheCall->setArg(0, OrigArg0);
485 TheCall->setArg(1, OrigArg1);
Chris Lattner1b9a0792007-12-20 00:26:33 +0000486
487 // If the common type isn't a real floating type, then the arguments were
488 // invalid for this operation.
489 if (!Res->isRealFloatingType())
Chris Lattner925e60d2007-12-28 05:29:59 +0000490 return Diag(OrigArg0->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000491 diag::err_typecheck_call_invalid_ordered_compare)
Chris Lattnerd1625842008-11-24 06:25:27 +0000492 << OrigArg0->getType() << OrigArg1->getType()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000493 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
Chris Lattner1b9a0792007-12-20 00:26:33 +0000494
495 return false;
496}
497
Eli Friedman6cfda232008-05-20 08:23:37 +0000498bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) {
499 // The signature for these builtins is exact; the only thing we need
500 // to check is that the argument is a constant.
501 SourceLocation Loc;
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000502 if (!TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc))
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000503 return Diag(Loc, diag::err_stack_const_level) << TheCall->getSourceRange();
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000504
Eli Friedman6cfda232008-05-20 08:23:37 +0000505 return false;
506}
507
Eli Friedmand38617c2008-05-14 19:38:39 +0000508/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
509// This is declared to take (...), so we have to check everything.
Sebastian Redl0eb23302009-01-19 00:08:26 +0000510Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000511 if (TheCall->getNumArgs() < 3)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000512 return ExprError(Diag(TheCall->getLocEnd(),
513 diag::err_typecheck_call_too_few_args)
514 << 0 /*function call*/ << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000515
516 QualType FAType = TheCall->getArg(0)->getType();
517 QualType SAType = TheCall->getArg(1)->getType();
518
519 if (!FAType->isVectorType() || !SAType->isVectorType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000520 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
521 << SourceRange(TheCall->getArg(0)->getLocStart(),
522 TheCall->getArg(1)->getLocEnd());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000523 return ExprError();
Eli Friedmand38617c2008-05-14 19:38:39 +0000524 }
525
Chris Lattnerb77792e2008-07-26 22:17:49 +0000526 if (Context.getCanonicalType(FAType).getUnqualifiedType() !=
527 Context.getCanonicalType(SAType).getUnqualifiedType()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000528 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
529 << SourceRange(TheCall->getArg(0)->getLocStart(),
530 TheCall->getArg(1)->getLocEnd());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000531 return ExprError();
Eli Friedmand38617c2008-05-14 19:38:39 +0000532 }
533
534 unsigned numElements = FAType->getAsVectorType()->getNumElements();
535 if (TheCall->getNumArgs() != numElements+2) {
536 if (TheCall->getNumArgs() < numElements+2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000537 return ExprError(Diag(TheCall->getLocEnd(),
538 diag::err_typecheck_call_too_few_args)
539 << 0 /*function call*/ << TheCall->getSourceRange());
540 return ExprError(Diag(TheCall->getLocEnd(),
541 diag::err_typecheck_call_too_many_args)
542 << 0 /*function call*/ << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000543 }
544
545 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
546 llvm::APSInt Result(32);
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000547 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000548 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000549 diag::err_shufflevector_nonconstant_argument)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000550 << TheCall->getArg(i)->getSourceRange());
551
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000552 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000553 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000554 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000555 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000556 }
557
558 llvm::SmallVector<Expr*, 32> exprs;
559
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000560 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000561 exprs.push_back(TheCall->getArg(i));
562 TheCall->setArg(i, 0);
563 }
564
Ted Kremenek8189cde2009-02-07 01:47:29 +0000565 return Owned(new (Context) ShuffleVectorExpr(exprs.begin(), numElements+2,
566 FAType,
567 TheCall->getCallee()->getLocStart(),
568 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000569}
Chris Lattner30ce3442007-12-19 23:59:04 +0000570
Daniel Dunbar4493f792008-07-21 22:59:13 +0000571/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
572// This is declared to take (const void*, ...) and can take two
573// optional constant int args.
574bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000575 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000576
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000577 if (NumArgs > 3)
578 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000579 << 0 /*function call*/ << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000580
581 // Argument 0 is checked for us and the remaining arguments must be
582 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000583 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000584 Expr *Arg = TheCall->getArg(i);
585 QualType RWType = Arg->getType();
586
587 const BuiltinType *BT = RWType->getAsBuiltinType();
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000588 llvm::APSInt Result;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000589 if (!BT || BT->getKind() != BuiltinType::Int ||
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000590 !Arg->isIntegerConstantExpr(Result, Context))
591 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument)
592 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar4493f792008-07-21 22:59:13 +0000593
594 // FIXME: gcc issues a warning and rewrites these to 0. These
595 // seems especially odd for the third argument since the default
596 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000597 if (i == 1) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000598 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000599 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
600 << "0" << "1" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar4493f792008-07-21 22:59:13 +0000601 } else {
602 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000603 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
604 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbar4493f792008-07-21 22:59:13 +0000605 }
606 }
607
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000608 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000609}
610
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000611/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
612/// int type). This simply type checks that type is one of the defined
613/// constants (0-3).
614bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
615 Expr *Arg = TheCall->getArg(1);
616 QualType ArgType = Arg->getType();
617 const BuiltinType *BT = ArgType->getAsBuiltinType();
618 llvm::APSInt Result(32);
619 if (!BT || BT->getKind() != BuiltinType::Int ||
620 !Arg->isIntegerConstantExpr(Result, Context)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000621 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
622 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000623 }
624
625 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000626 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
627 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000628 }
629
630 return false;
631}
632
Eli Friedman586d6a82009-05-03 06:04:26 +0000633/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +0000634/// This checks that val is a constant 1.
635bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
636 Expr *Arg = TheCall->getArg(1);
637 llvm::APSInt Result(32);
638 if (!Arg->isIntegerConstantExpr(Result, Context) || Result != 1)
639 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
640 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
641
642 return false;
643}
644
Ted Kremenekd30ef872009-01-12 23:09:09 +0000645// Handle i > 1 ? "x" : "y", recursivelly
Ted Kremenek082d9362009-03-20 21:35:28 +0000646bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
647 bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000648 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenekd30ef872009-01-12 23:09:09 +0000649
650 switch (E->getStmtClass()) {
651 case Stmt::ConditionalOperatorClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000652 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000653 return SemaCheckStringLiteral(C->getLHS(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000654 HasVAListArg, format_idx, firstDataArg)
Ted Kremenekd30ef872009-01-12 23:09:09 +0000655 && SemaCheckStringLiteral(C->getRHS(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000656 HasVAListArg, format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000657 }
658
659 case Stmt::ImplicitCastExprClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000660 const ImplicitCastExpr *Expr = cast<ImplicitCastExpr>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000661 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000662 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000663 }
664
665 case Stmt::ParenExprClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000666 const ParenExpr *Expr = cast<ParenExpr>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000667 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000668 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000669 }
Ted Kremenek082d9362009-03-20 21:35:28 +0000670
671 case Stmt::DeclRefExprClass: {
672 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
673
674 // As an exception, do not flag errors for variables binding to
675 // const string literals.
676 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
677 bool isConstant = false;
678 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +0000679
Ted Kremenek082d9362009-03-20 21:35:28 +0000680 if (const ArrayType *AT = Context.getAsArrayType(T)) {
681 isConstant = AT->getElementType().isConstant(Context);
682 }
683 else if (const PointerType *PT = T->getAsPointerType()) {
684 isConstant = T.isConstant(Context) &&
685 PT->getPointeeType().isConstant(Context);
686 }
687
688 if (isConstant) {
689 const VarDecl *Def = 0;
690 if (const Expr *Init = VD->getDefinition(Def))
691 return SemaCheckStringLiteral(Init, TheCall,
692 HasVAListArg, format_idx, firstDataArg);
693 }
694 }
695
696 return false;
697 }
Ted Kremenekd30ef872009-01-12 23:09:09 +0000698
Ted Kremenek082d9362009-03-20 21:35:28 +0000699 case Stmt::ObjCStringLiteralClass:
700 case Stmt::StringLiteralClass: {
701 const StringLiteral *StrE = NULL;
702
703 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +0000704 StrE = ObjCFExpr->getString();
705 else
Ted Kremenek082d9362009-03-20 21:35:28 +0000706 StrE = cast<StringLiteral>(E);
707
Ted Kremenekd30ef872009-01-12 23:09:09 +0000708 if (StrE) {
Douglas Gregor3c385e52009-02-14 18:57:46 +0000709 CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx,
710 firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000711 return true;
712 }
713
714 return false;
715 }
Ted Kremenek082d9362009-03-20 21:35:28 +0000716
717 default:
718 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000719 }
720}
721
722
Chris Lattner59907c42007-08-10 20:18:51 +0000723/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Ted Kremenek71895b92007-08-14 17:39:48 +0000724/// correct use of format strings.
725///
726/// HasVAListArg - A predicate indicating whether the printf-like
727/// function is passed an explicit va_arg argument (e.g., vprintf)
728///
729/// format_idx - The index into Args for the format string.
730///
731/// Improper format strings to functions in the printf family can be
732/// the source of bizarre bugs and very serious security holes. A
733/// good source of information is available in the following paper
734/// (which includes additional references):
Chris Lattner59907c42007-08-10 20:18:51 +0000735///
736/// FormatGuard: Automatic Protection From printf Format String
737/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremenek71895b92007-08-14 17:39:48 +0000738///
739/// Functionality implemented:
740///
741/// We can statically check the following properties for string
742/// literal format strings for non v.*printf functions (where the
743/// arguments are passed directly):
744//
745/// (1) Are the number of format conversions equal to the number of
746/// data arguments?
747///
748/// (2) Does each format conversion correctly match the type of the
749/// corresponding data argument? (TODO)
750///
751/// Moreover, for all printf functions we can:
752///
753/// (3) Check for a missing format string (when not caught by type checking).
754///
755/// (4) Check for no-operation flags; e.g. using "#" with format
756/// conversion 'c' (TODO)
757///
758/// (5) Check the use of '%n', a major source of security holes.
759///
760/// (6) Check for malformed format conversions that don't specify anything.
761///
762/// (7) Check for empty format strings. e.g: printf("");
763///
764/// (8) Check that the format string is a wide literal.
765///
Ted Kremenek6d439592008-03-03 16:50:00 +0000766/// (9) Also check the arguments of functions with the __format__ attribute.
767/// (TODO).
768///
Ted Kremenek71895b92007-08-14 17:39:48 +0000769/// All of these checks can be done by parsing the format string.
770///
771/// For now, we ONLY do (1), (3), (5), (6), (7), and (8).
Chris Lattner59907c42007-08-10 20:18:51 +0000772void
Ted Kremenek082d9362009-03-20 21:35:28 +0000773Sema::CheckPrintfArguments(const CallExpr *TheCall, bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000774 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenek082d9362009-03-20 21:35:28 +0000775 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +0000776
Ted Kremenek71895b92007-08-14 17:39:48 +0000777 // CHECK: printf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +0000778 if (format_idx >= TheCall->getNumArgs()) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000779 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string)
780 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000781 return;
782 }
783
Ted Kremenek082d9362009-03-20 21:35:28 +0000784 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Chris Lattner459e8482007-08-25 05:36:18 +0000785
Chris Lattner59907c42007-08-10 20:18:51 +0000786 // CHECK: format string is not a string literal.
787 //
Ted Kremenek71895b92007-08-14 17:39:48 +0000788 // Dynamically generated format strings are difficult to
789 // automatically vet at compile time. Requiring that format strings
790 // are string literals: (1) permits the checking of format strings by
791 // the compiler and thereby (2) can practically remove the source of
792 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000793
794 // Format string can be either ObjC string (e.g. @"%d") or
795 // C string (e.g. "%d")
796 // ObjC string uses the same format specifiers as C string, so we can use
797 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +0000798 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
799 firstDataArg))
800 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000801
Chris Lattner1cd3e1f2009-04-29 04:49:34 +0000802 // For vprintf* functions (i.e., HasVAListArg==true), we add a
803 // special check to see if the format string is a function parameter
804 // of the function calling the printf function. If the function
805 // has an attribute indicating it is a printf-like function, then we
806 // should suppress warnings concerning non-literals being used in a call
807 // to a vprintf function. For example:
808 //
809 // void
810 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...) {
811 // va_list ap;
812 // va_start(ap, fmt);
813 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
814 // ...
815 //
816 //
817 // FIXME: We don't have full attribute support yet, so just check to see
818 // if the argument is a DeclRefExpr that references a parameter. We'll
819 // add proper support for checking the attribute later.
820 if (HasVAListArg)
821 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OrigFormatExpr))
822 if (isa<ParmVarDecl>(DR->getDecl()))
823 return;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000824
Chris Lattner655f1412009-04-29 04:59:47 +0000825 // If there are no arguments specified, warn with -Wformat-security, otherwise
826 // warn only with -Wformat-nonliteral.
827 if (TheCall->getNumArgs() == format_idx+1)
828 Diag(TheCall->getArg(format_idx)->getLocStart(),
829 diag::warn_printf_nonliteral_noargs)
830 << OrigFormatExpr->getSourceRange();
831 else
832 Diag(TheCall->getArg(format_idx)->getLocStart(),
833 diag::warn_printf_nonliteral)
834 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +0000835}
Ted Kremenek71895b92007-08-14 17:39:48 +0000836
Ted Kremenek082d9362009-03-20 21:35:28 +0000837void Sema::CheckPrintfString(const StringLiteral *FExpr,
838 const Expr *OrigFormatExpr,
839 const CallExpr *TheCall, bool HasVAListArg,
840 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenekd30ef872009-01-12 23:09:09 +0000841
Ted Kremenek082d9362009-03-20 21:35:28 +0000842 const ObjCStringLiteral *ObjCFExpr =
843 dyn_cast<ObjCStringLiteral>(OrigFormatExpr);
844
Ted Kremenek71895b92007-08-14 17:39:48 +0000845 // CHECK: is the format string a wide literal?
846 if (FExpr->isWide()) {
Chris Lattner925e60d2007-12-28 05:29:59 +0000847 Diag(FExpr->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000848 diag::warn_printf_format_string_is_wide_literal)
849 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000850 return;
851 }
852
853 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattnerb9fc8562009-04-29 04:12:34 +0000854 const char *Str = FExpr->getStrData();
Ted Kremenek71895b92007-08-14 17:39:48 +0000855
856 // CHECK: empty format string?
Chris Lattnerb9fc8562009-04-29 04:12:34 +0000857 unsigned StrLen = FExpr->getByteLength();
Ted Kremenek71895b92007-08-14 17:39:48 +0000858
859 if (StrLen == 0) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000860 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string)
861 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000862 return;
863 }
864
865 // We process the format string using a binary state machine. The
866 // current state is stored in CurrentState.
867 enum {
868 state_OrdChr,
869 state_Conversion
870 } CurrentState = state_OrdChr;
871
872 // numConversions - The number of conversions seen so far. This is
873 // incremented as we traverse the format string.
874 unsigned numConversions = 0;
875
876 // numDataArgs - The number of data arguments after the format
877 // string. This can only be determined for non vprintf-like
878 // functions. For those functions, this value is 1 (the sole
879 // va_arg argument).
Douglas Gregor3c385e52009-02-14 18:57:46 +0000880 unsigned numDataArgs = TheCall->getNumArgs()-firstDataArg;
Ted Kremenek71895b92007-08-14 17:39:48 +0000881
882 // Inspect the format string.
883 unsigned StrIdx = 0;
884
885 // LastConversionIdx - Index within the format string where we last saw
886 // a '%' character that starts a new format conversion.
887 unsigned LastConversionIdx = 0;
888
Chris Lattner925e60d2007-12-28 05:29:59 +0000889 for (; StrIdx < StrLen; ++StrIdx) {
Chris Lattner998568f2007-12-28 05:38:24 +0000890
Ted Kremenek71895b92007-08-14 17:39:48 +0000891 // Is the number of detected conversion conversions greater than
892 // the number of matching data arguments? If so, stop.
893 if (!HasVAListArg && numConversions > numDataArgs) break;
894
895 // Handle "\0"
Chris Lattner925e60d2007-12-28 05:29:59 +0000896 if (Str[StrIdx] == '\0') {
Ted Kremenek71895b92007-08-14 17:39:48 +0000897 // The string returned by getStrData() is not null-terminated,
898 // so the presence of a null character is likely an error.
Chris Lattner60800082009-02-18 17:49:48 +0000899 Diag(getLocationOfStringLiteralByte(FExpr, StrIdx),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000900 diag::warn_printf_format_string_contains_null_char)
901 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000902 return;
903 }
904
905 // Ordinary characters (not processing a format conversion).
906 if (CurrentState == state_OrdChr) {
907 if (Str[StrIdx] == '%') {
908 CurrentState = state_Conversion;
909 LastConversionIdx = StrIdx;
910 }
911 continue;
912 }
913
914 // Seen '%'. Now processing a format conversion.
915 switch (Str[StrIdx]) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000916 // Handle dynamic precision or width specifier.
917 case '*': {
918 ++numConversions;
919
Ted Kremenek42ae3e82009-05-13 16:06:05 +0000920 if (!HasVAListArg) {
921 if (numConversions > numDataArgs) {
922 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx);
Ted Kremenek580b6642007-10-12 20:51:52 +0000923
Ted Kremenek42ae3e82009-05-13 16:06:05 +0000924 if (Str[StrIdx-1] == '.')
925 Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg)
926 << OrigFormatExpr->getSourceRange();
927 else
928 Diag(Loc, diag::warn_printf_asterisk_width_missing_arg)
929 << OrigFormatExpr->getSourceRange();
930
931 // Don't do any more checking. We'll just emit spurious errors.
932 return;
933 }
934
935 // Perform type checking on width/precision specifier.
936 const Expr *E = TheCall->getArg(format_idx+numConversions);
937 if (const BuiltinType *BT = E->getType()->getAsBuiltinType())
938 if (BT->getKind() == BuiltinType::Int)
939 break;
Ted Kremenek580b6642007-10-12 20:51:52 +0000940
Ted Kremenek42ae3e82009-05-13 16:06:05 +0000941 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx);
942
943 if (Str[StrIdx-1] == '.')
944 Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type)
945 << E->getType() << E->getSourceRange();
946 else
947 Diag(Loc, diag::warn_printf_asterisk_width_wrong_type)
948 << E->getType() << E->getSourceRange();
949
950 break;
Ted Kremenek580b6642007-10-12 20:51:52 +0000951 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000952 }
953
954 // Characters which can terminate a format conversion
955 // (e.g. "%d"). Characters that specify length modifiers or
956 // other flags are handled by the default case below.
957 //
958 // FIXME: additional checks will go into the following cases.
959 case 'i':
960 case 'd':
961 case 'o':
962 case 'u':
963 case 'x':
964 case 'X':
965 case 'D':
966 case 'O':
967 case 'U':
968 case 'e':
969 case 'E':
970 case 'f':
971 case 'F':
972 case 'g':
973 case 'G':
974 case 'a':
975 case 'A':
976 case 'c':
977 case 'C':
978 case 'S':
979 case 's':
980 case 'p':
981 ++numConversions;
982 CurrentState = state_OrdChr;
983 break;
984
985 // CHECK: Are we using "%n"? Issue a warning.
986 case 'n': {
987 ++numConversions;
988 CurrentState = state_OrdChr;
Chris Lattner60800082009-02-18 17:49:48 +0000989 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr,
990 LastConversionIdx);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000991
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000992 Diag(Loc, diag::warn_printf_write_back)<<OrigFormatExpr->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +0000993 break;
994 }
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000995
996 // Handle "%@"
997 case '@':
998 // %@ is allowed in ObjC format strings only.
999 if(ObjCFExpr != NULL)
1000 CurrentState = state_OrdChr;
1001 else {
1002 // Issue a warning: invalid format conversion.
Chris Lattner60800082009-02-18 17:49:48 +00001003 SourceLocation Loc =
1004 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001005
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001006 Diag(Loc, diag::warn_printf_invalid_conversion)
1007 << std::string(Str+LastConversionIdx,
1008 Str+std::min(LastConversionIdx+2, StrLen))
1009 << OrigFormatExpr->getSourceRange();
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001010 }
1011 ++numConversions;
1012 break;
1013
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001014 // Handle "%%"
1015 case '%':
1016 // Sanity check: Was the first "%" character the previous one?
1017 // If not, we will assume that we have a malformed format
1018 // conversion, and that the current "%" character is the start
1019 // of a new conversion.
1020 if (StrIdx - LastConversionIdx == 1)
1021 CurrentState = state_OrdChr;
1022 else {
1023 // Issue a warning: invalid format conversion.
Chris Lattner60800082009-02-18 17:49:48 +00001024 SourceLocation Loc =
1025 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001026
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001027 Diag(Loc, diag::warn_printf_invalid_conversion)
1028 << std::string(Str+LastConversionIdx, Str+StrIdx)
1029 << OrigFormatExpr->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001030
1031 // This conversion is broken. Advance to the next format
1032 // conversion.
1033 LastConversionIdx = StrIdx;
1034 ++numConversions;
Ted Kremenek71895b92007-08-14 17:39:48 +00001035 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001036 break;
Ted Kremenek71895b92007-08-14 17:39:48 +00001037
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001038 default:
1039 // This case catches all other characters: flags, widths, etc.
1040 // We should eventually process those as well.
1041 break;
Ted Kremenek71895b92007-08-14 17:39:48 +00001042 }
1043 }
1044
1045 if (CurrentState == state_Conversion) {
1046 // Issue a warning: invalid format conversion.
Chris Lattner60800082009-02-18 17:49:48 +00001047 SourceLocation Loc =
1048 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Ted Kremenek71895b92007-08-14 17:39:48 +00001049
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001050 Diag(Loc, diag::warn_printf_invalid_conversion)
1051 << std::string(Str+LastConversionIdx,
1052 Str+std::min(LastConversionIdx+2, StrLen))
1053 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001054 return;
1055 }
1056
1057 if (!HasVAListArg) {
1058 // CHECK: Does the number of format conversions exceed the number
1059 // of data arguments?
1060 if (numConversions > numDataArgs) {
Chris Lattner60800082009-02-18 17:49:48 +00001061 SourceLocation Loc =
1062 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Ted Kremenek71895b92007-08-14 17:39:48 +00001063
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001064 Diag(Loc, diag::warn_printf_insufficient_data_args)
1065 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001066 }
1067 // CHECK: Does the number of data arguments exceed the number of
1068 // format conversions in the format string?
1069 else if (numConversions < numDataArgs)
Chris Lattner925e60d2007-12-28 05:29:59 +00001070 Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001071 diag::warn_printf_too_many_data_args)
1072 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001073 }
1074}
Ted Kremenek06de2762007-08-17 16:46:58 +00001075
1076//===--- CHECK: Return Address of Stack Variable --------------------------===//
1077
1078static DeclRefExpr* EvalVal(Expr *E);
1079static DeclRefExpr* EvalAddr(Expr* E);
1080
1081/// CheckReturnStackAddr - Check if a return statement returns the address
1082/// of a stack variable.
1083void
1084Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1085 SourceLocation ReturnLoc) {
Chris Lattner56f34942008-02-13 01:02:39 +00001086
Ted Kremenek06de2762007-08-17 16:46:58 +00001087 // Perform checking for returned stack addresses.
Steve Naroffdd972f22008-09-05 22:11:13 +00001088 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Ted Kremenek06de2762007-08-17 16:46:58 +00001089 if (DeclRefExpr *DR = EvalAddr(RetValExp))
Chris Lattner3c73c412008-11-19 08:23:25 +00001090 Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
Chris Lattner08631c52008-11-23 21:45:46 +00001091 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Steve Naroffc50a4a52008-09-16 22:25:10 +00001092
1093 // Skip over implicit cast expressions when checking for block expressions.
1094 if (ImplicitCastExpr *IcExpr =
1095 dyn_cast_or_null<ImplicitCastExpr>(RetValExp))
1096 RetValExp = IcExpr->getSubExpr();
1097
Steve Naroff61f40a22008-09-10 19:17:48 +00001098 if (BlockExpr *C = dyn_cast_or_null<BlockExpr>(RetValExp))
Mike Stump397195b2009-04-17 00:09:41 +00001099 if (C->hasBlockDeclRefExprs())
1100 Diag(C->getLocStart(), diag::err_ret_local_block)
1101 << C->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +00001102 }
1103 // Perform checking for stack values returned by reference.
1104 else if (lhsType->isReferenceType()) {
Douglas Gregor49badde2008-10-27 19:41:14 +00001105 // Check for a reference to the stack
1106 if (DeclRefExpr *DR = EvalVal(RetValExp))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001107 Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
Chris Lattner08631c52008-11-23 21:45:46 +00001108 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +00001109 }
1110}
1111
1112/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1113/// check if the expression in a return statement evaluates to an address
1114/// to a location on the stack. The recursion is used to traverse the
1115/// AST of the return expression, with recursion backtracking when we
1116/// encounter a subexpression that (1) clearly does not lead to the address
1117/// of a stack variable or (2) is something we cannot determine leads to
1118/// the address of a stack variable based on such local checking.
1119///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001120/// EvalAddr processes expressions that are pointers that are used as
1121/// references (and not L-values). EvalVal handles all other values.
Ted Kremenek06de2762007-08-17 16:46:58 +00001122/// At the base case of the recursion is a check for a DeclRefExpr* in
1123/// the refers to a stack variable.
1124///
1125/// This implementation handles:
1126///
1127/// * pointer-to-pointer casts
1128/// * implicit conversions from array references to pointers
1129/// * taking the address of fields
1130/// * arbitrary interplay between "&" and "*" operators
1131/// * pointer arithmetic from an address of a stack variable
1132/// * taking the address of an array element where the array is on the stack
1133static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek06de2762007-08-17 16:46:58 +00001134 // We should only be called for evaluating pointer expressions.
Steve Naroffdd972f22008-09-05 22:11:13 +00001135 assert((E->getType()->isPointerType() ||
1136 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001137 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001138 "EvalAddr only works on pointers");
Ted Kremenek06de2762007-08-17 16:46:58 +00001139
1140 // Our "symbolic interpreter" is just a dispatch off the currently
1141 // viewed AST node. We then recursively traverse the AST by calling
1142 // EvalAddr and EvalVal appropriately.
1143 switch (E->getStmtClass()) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001144 case Stmt::ParenExprClass:
1145 // Ignore parentheses.
1146 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek06de2762007-08-17 16:46:58 +00001147
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001148 case Stmt::UnaryOperatorClass: {
1149 // The only unary operator that make sense to handle here
1150 // is AddrOf. All others don't make sense as pointers.
1151 UnaryOperator *U = cast<UnaryOperator>(E);
Ted Kremenek06de2762007-08-17 16:46:58 +00001152
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001153 if (U->getOpcode() == UnaryOperator::AddrOf)
1154 return EvalVal(U->getSubExpr());
1155 else
Ted Kremenek06de2762007-08-17 16:46:58 +00001156 return NULL;
1157 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001158
1159 case Stmt::BinaryOperatorClass: {
1160 // Handle pointer arithmetic. All other binary operators are not valid
1161 // in this context.
1162 BinaryOperator *B = cast<BinaryOperator>(E);
1163 BinaryOperator::Opcode op = B->getOpcode();
1164
1165 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
1166 return NULL;
1167
1168 Expr *Base = B->getLHS();
1169
1170 // Determine which argument is the real pointer base. It could be
1171 // the RHS argument instead of the LHS.
1172 if (!Base->getType()->isPointerType()) Base = B->getRHS();
1173
1174 assert (Base->getType()->isPointerType());
1175 return EvalAddr(Base);
1176 }
Steve Naroff61f40a22008-09-10 19:17:48 +00001177
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001178 // For conditional operators we need to see if either the LHS or RHS are
1179 // valid DeclRefExpr*s. If one of them is valid, we return it.
1180 case Stmt::ConditionalOperatorClass: {
1181 ConditionalOperator *C = cast<ConditionalOperator>(E);
1182
1183 // Handle the GNU extension for missing LHS.
1184 if (Expr *lhsExpr = C->getLHS())
1185 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
1186 return LHS;
1187
1188 return EvalAddr(C->getRHS());
1189 }
1190
Ted Kremenek54b52742008-08-07 00:49:01 +00001191 // For casts, we need to handle conversions from arrays to
1192 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00001193 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001194 case Stmt::CStyleCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001195 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001196 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00001197 QualType T = SubExpr->getType();
1198
Steve Naroffdd972f22008-09-05 22:11:13 +00001199 if (SubExpr->getType()->isPointerType() ||
1200 SubExpr->getType()->isBlockPointerType() ||
1201 SubExpr->getType()->isObjCQualifiedIdType())
Ted Kremenek54b52742008-08-07 00:49:01 +00001202 return EvalAddr(SubExpr);
1203 else if (T->isArrayType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001204 return EvalVal(SubExpr);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001205 else
Ted Kremenek54b52742008-08-07 00:49:01 +00001206 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001207 }
1208
1209 // C++ casts. For dynamic casts, static casts, and const casts, we
1210 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00001211 // through the cast. In the case the dynamic cast doesn't fail (and
1212 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001213 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00001214 // FIXME: The comment about is wrong; we're not always converting
1215 // from pointer to pointer. I'm guessing that this code should also
1216 // handle references to objects.
1217 case Stmt::CXXStaticCastExprClass:
1218 case Stmt::CXXDynamicCastExprClass:
1219 case Stmt::CXXConstCastExprClass:
1220 case Stmt::CXXReinterpretCastExprClass: {
1221 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00001222 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001223 return EvalAddr(S);
1224 else
1225 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001226 }
1227
1228 // Everything else: we simply don't reason about them.
1229 default:
1230 return NULL;
1231 }
Ted Kremenek06de2762007-08-17 16:46:58 +00001232}
1233
1234
1235/// EvalVal - This function is complements EvalAddr in the mutual recursion.
1236/// See the comments for EvalAddr for more details.
1237static DeclRefExpr* EvalVal(Expr *E) {
1238
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001239 // We should only be called for evaluating non-pointer expressions, or
1240 // expressions with a pointer type that are not used as references but instead
1241 // are l-values (e.g., DeclRefExpr with a pointer type).
1242
Ted Kremenek06de2762007-08-17 16:46:58 +00001243 // Our "symbolic interpreter" is just a dispatch off the currently
1244 // viewed AST node. We then recursively traverse the AST by calling
1245 // EvalAddr and EvalVal appropriately.
1246 switch (E->getStmtClass()) {
Douglas Gregor1a49af92009-01-06 05:10:23 +00001247 case Stmt::DeclRefExprClass:
1248 case Stmt::QualifiedDeclRefExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00001249 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
1250 // at code that refers to a variable's name. We check if it has local
1251 // storage within the function, and if so, return the expression.
1252 DeclRefExpr *DR = cast<DeclRefExpr>(E);
1253
1254 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001255 if(V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
Ted Kremenek06de2762007-08-17 16:46:58 +00001256
1257 return NULL;
1258 }
1259
1260 case Stmt::ParenExprClass:
1261 // Ignore parentheses.
1262 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
1263
1264 case Stmt::UnaryOperatorClass: {
1265 // The only unary operator that make sense to handle here
1266 // is Deref. All others don't resolve to a "name." This includes
1267 // handling all sorts of rvalues passed to a unary operator.
1268 UnaryOperator *U = cast<UnaryOperator>(E);
1269
1270 if (U->getOpcode() == UnaryOperator::Deref)
1271 return EvalAddr(U->getSubExpr());
1272
1273 return NULL;
1274 }
1275
1276 case Stmt::ArraySubscriptExprClass: {
1277 // Array subscripts are potential references to data on the stack. We
1278 // retrieve the DeclRefExpr* for the array variable if it indeed
1279 // has local storage.
Ted Kremenek23245122007-08-20 16:18:38 +00001280 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek06de2762007-08-17 16:46:58 +00001281 }
1282
1283 case Stmt::ConditionalOperatorClass: {
1284 // For conditional operators we need to see if either the LHS or RHS are
1285 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
1286 ConditionalOperator *C = cast<ConditionalOperator>(E);
1287
Anders Carlsson39073232007-11-30 19:04:31 +00001288 // Handle the GNU extension for missing LHS.
1289 if (Expr *lhsExpr = C->getLHS())
1290 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
1291 return LHS;
1292
1293 return EvalVal(C->getRHS());
Ted Kremenek06de2762007-08-17 16:46:58 +00001294 }
1295
1296 // Accesses to members are potential references to data on the stack.
1297 case Stmt::MemberExprClass: {
1298 MemberExpr *M = cast<MemberExpr>(E);
1299
1300 // Check for indirect access. We only want direct field accesses.
1301 if (!M->isArrow())
1302 return EvalVal(M->getBase());
1303 else
1304 return NULL;
1305 }
1306
1307 // Everything else: we simply don't reason about them.
1308 default:
1309 return NULL;
1310 }
1311}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001312
1313//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
1314
1315/// Check for comparisons of floating point operands using != and ==.
1316/// Issue a warning if these are no self-comparisons, as they are not likely
1317/// to do what the programmer intended.
1318void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
1319 bool EmitWarning = true;
1320
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00001321 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek32e97b62008-01-17 17:55:13 +00001322 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001323
1324 // Special case: check for x == x (which is OK).
1325 // Do not emit warnings for such cases.
1326 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
1327 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
1328 if (DRL->getDecl() == DRR->getDecl())
1329 EmitWarning = false;
1330
Ted Kremenek1b500bb2007-11-29 00:59:04 +00001331
1332 // Special case: check for comparisons against literals that can be exactly
1333 // represented by APFloat. In such cases, do not emit a warning. This
1334 // is a heuristic: often comparison against such literals are used to
1335 // detect if a value in a variable has not changed. This clearly can
1336 // lead to false negatives.
1337 if (EmitWarning) {
1338 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
1339 if (FLL->isExact())
1340 EmitWarning = false;
1341 }
1342 else
1343 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
1344 if (FLR->isExact())
1345 EmitWarning = false;
1346 }
1347 }
1348
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001349 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001350 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001351 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001352 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001353 EmitWarning = false;
1354
Sebastian Redl0eb23302009-01-19 00:08:26 +00001355 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001356 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001357 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001358 EmitWarning = false;
1359
1360 // Emit the diagnostic.
1361 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001362 Diag(loc, diag::warn_floatingpoint_eq)
1363 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001364}