blob: 18a997998a599bfc88f061a2703c652050112234 [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//
Mike Stump1eb44332009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattner59907c42007-08-10 20:18:51 +000011// 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"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000022#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000023using namespace clang;
24
Chris Lattner60800082009-02-18 17:49:48 +000025/// getLocationOfStringLiteralByte - Return a source location that points to the
26/// specified byte of the specified string literal.
27///
28/// Strings are amazingly complex. They can be formed from multiple tokens and
29/// can have escape sequences in them in addition to the usual trigraph and
30/// escaped newline business. This routine handles this complexity.
31///
32SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
33 unsigned ByteNo) const {
34 assert(!SL->isWide() && "This doesn't work for wide strings yet");
Mike Stump1eb44332009-09-09 15:08:12 +000035
Chris Lattner60800082009-02-18 17:49:48 +000036 // Loop over all of the tokens in this string until we find the one that
37 // contains the byte we're looking for.
38 unsigned TokNo = 0;
39 while (1) {
40 assert(TokNo < SL->getNumConcatenated() && "Invalid byte number!");
41 SourceLocation StrTokLoc = SL->getStrTokenLoc(TokNo);
Mike Stump1eb44332009-09-09 15:08:12 +000042
Chris Lattner60800082009-02-18 17:49:48 +000043 // Get the spelling of the string so that we can get the data that makes up
44 // the string literal, not the identifier for the macro it is potentially
45 // expanded through.
46 SourceLocation StrTokSpellingLoc = SourceMgr.getSpellingLoc(StrTokLoc);
47
48 // Re-lex the token to get its length and original spelling.
49 std::pair<FileID, unsigned> LocInfo =
50 SourceMgr.getDecomposedLoc(StrTokSpellingLoc);
51 std::pair<const char *,const char *> Buffer =
52 SourceMgr.getBufferData(LocInfo.first);
53 const char *StrData = Buffer.first+LocInfo.second;
Mike Stump1eb44332009-09-09 15:08:12 +000054
Chris Lattner60800082009-02-18 17:49:48 +000055 // Create a langops struct and enable trigraphs. This is sufficient for
56 // relexing tokens.
57 LangOptions LangOpts;
58 LangOpts.Trigraphs = true;
Mike Stump1eb44332009-09-09 15:08:12 +000059
Chris Lattner60800082009-02-18 17:49:48 +000060 // Create a lexer starting at the beginning of this token.
61 Lexer TheLexer(StrTokSpellingLoc, LangOpts, Buffer.first, StrData,
62 Buffer.second);
63 Token TheTok;
64 TheLexer.LexFromRawLexer(TheTok);
Mike Stump1eb44332009-09-09 15:08:12 +000065
Chris Lattner443e53c2009-02-18 19:26:42 +000066 // Use the StringLiteralParser to compute the length of the string in bytes.
67 StringLiteralParser SLP(&TheTok, 1, PP);
68 unsigned TokNumBytes = SLP.GetStringLength();
Mike Stump1eb44332009-09-09 15:08:12 +000069
Chris Lattner2197c962009-02-18 18:52:52 +000070 // If the byte is in this token, return the location of the byte.
Chris Lattner60800082009-02-18 17:49:48 +000071 if (ByteNo < TokNumBytes ||
72 (ByteNo == TokNumBytes && TokNo == SL->getNumConcatenated())) {
Mike Stump1eb44332009-09-09 15:08:12 +000073 unsigned Offset =
Chris Lattner719e6152009-02-18 19:21:10 +000074 StringLiteralParser::getOffsetOfStringByte(TheTok, ByteNo, PP);
Mike Stump1eb44332009-09-09 15:08:12 +000075
Chris Lattner719e6152009-02-18 19:21:10 +000076 // Now that we know the offset of the token in the spelling, use the
77 // preprocessor to get the offset in the original source.
78 return PP.AdvanceToTokenCharacter(StrTokLoc, Offset);
Chris Lattner60800082009-02-18 17:49:48 +000079 }
Mike Stump1eb44332009-09-09 15:08:12 +000080
Chris Lattner60800082009-02-18 17:49:48 +000081 // Move to the next string token.
82 ++TokNo;
83 ByteNo -= TokNumBytes;
84 }
85}
86
Ryan Flynn4403a5e2009-08-06 03:00:50 +000087/// CheckablePrintfAttr - does a function call have a "printf" attribute
88/// and arguments that merit checking?
89bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) {
90 if (Format->getType() == "printf") return true;
91 if (Format->getType() == "printf0") {
92 // printf0 allows null "format" string; if so don't check format/args
93 unsigned format_idx = Format->getFormatIdx() - 1;
94 if (format_idx < TheCall->getNumArgs()) {
95 Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts();
96 if (!Format->isNullPointerConstant(Context))
97 return true;
98 }
99 }
100 return false;
101}
Chris Lattner60800082009-02-18 17:49:48 +0000102
Sebastian Redl0eb23302009-01-19 00:08:26 +0000103Action::OwningExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +0000104Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Sebastian Redl0eb23302009-01-19 00:08:26 +0000105 OwningExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +0000106
Anders Carlssond406bf02009-08-16 01:56:34 +0000107 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000108 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000109 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000110 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000111 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000112 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000113 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000114 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000115 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000116 if (SemaBuiltinVAStart(TheCall))
117 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000118 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000119 case Builtin::BI__builtin_isgreater:
120 case Builtin::BI__builtin_isgreaterequal:
121 case Builtin::BI__builtin_isless:
122 case Builtin::BI__builtin_islessequal:
123 case Builtin::BI__builtin_islessgreater:
124 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000125 if (SemaBuiltinUnorderedCompare(TheCall))
126 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000127 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000128 case Builtin::BI__builtin_isfinite:
129 case Builtin::BI__builtin_isinf:
130 case Builtin::BI__builtin_isinf_sign:
131 case Builtin::BI__builtin_isnan:
132 case Builtin::BI__builtin_isnormal:
133 if (SemaBuiltinUnaryFP(TheCall))
134 return ExprError();
135 break;
Eli Friedman6cfda232008-05-20 08:23:37 +0000136 case Builtin::BI__builtin_return_address:
137 case Builtin::BI__builtin_frame_address:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000138 if (SemaBuiltinStackAddress(TheCall))
139 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000140 break;
Chris Lattner21fb98e2009-09-23 06:06:36 +0000141 case Builtin::BI__builtin_eh_return_data_regno:
142 if (SemaBuiltinEHReturnDataRegNo(TheCall))
143 return ExprError();
144 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000145 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000146 return SemaBuiltinShuffleVector(TheCall);
147 // TheCall will be freed by the smart pointer here, but that's fine, since
148 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000149 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000150 if (SemaBuiltinPrefetch(TheCall))
151 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000152 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000153 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000154 if (SemaBuiltinObjectSize(TheCall))
155 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000156 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000157 case Builtin::BI__builtin_longjmp:
158 if (SemaBuiltinLongjmp(TheCall))
159 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000160 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000161 case Builtin::BI__sync_fetch_and_add:
162 case Builtin::BI__sync_fetch_and_sub:
163 case Builtin::BI__sync_fetch_and_or:
164 case Builtin::BI__sync_fetch_and_and:
165 case Builtin::BI__sync_fetch_and_xor:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000166 case Builtin::BI__sync_fetch_and_nand:
Chris Lattner5caa3702009-05-08 06:58:22 +0000167 case Builtin::BI__sync_add_and_fetch:
168 case Builtin::BI__sync_sub_and_fetch:
169 case Builtin::BI__sync_and_and_fetch:
170 case Builtin::BI__sync_or_and_fetch:
171 case Builtin::BI__sync_xor_and_fetch:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000172 case Builtin::BI__sync_nand_and_fetch:
Chris Lattner5caa3702009-05-08 06:58:22 +0000173 case Builtin::BI__sync_val_compare_and_swap:
174 case Builtin::BI__sync_bool_compare_and_swap:
175 case Builtin::BI__sync_lock_test_and_set:
176 case Builtin::BI__sync_lock_release:
177 if (SemaBuiltinAtomicOverloaded(TheCall))
178 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000179 break;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000180 }
Mike Stump1eb44332009-09-09 15:08:12 +0000181
Anders Carlssond406bf02009-08-16 01:56:34 +0000182 return move(TheCallResult);
183}
Daniel Dunbarde454282008-10-02 18:44:07 +0000184
Anders Carlssond406bf02009-08-16 01:56:34 +0000185/// CheckFunctionCall - Check a direct function call for various correctness
186/// and safety properties not strictly enforced by the C type system.
187bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
188 // Get the IdentifierInfo* for the called function.
189 IdentifierInfo *FnInfo = FDecl->getIdentifier();
190
191 // None of the checks below are needed for functions that don't have
192 // simple names (e.g., C++ conversion functions).
193 if (!FnInfo)
194 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000195
Daniel Dunbarde454282008-10-02 18:44:07 +0000196 // FIXME: This mechanism should be abstracted to be less fragile and
197 // more efficient. For example, just map function ids to custom
198 // handlers.
199
Chris Lattner59907c42007-08-10 20:18:51 +0000200 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000201 if (const FormatAttr *Format = FDecl->getAttr<FormatAttr>()) {
Ryan Flynn4403a5e2009-08-06 03:00:50 +0000202 if (CheckablePrintfAttr(Format, TheCall)) {
Ted Kremenek3d692df2009-02-27 17:58:43 +0000203 bool HasVAListArg = Format->getFirstArg() == 0;
204 if (!HasVAListArg) {
Mike Stump1eb44332009-09-09 15:08:12 +0000205 if (const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +0000206 = FDecl->getType()->getAs<FunctionProtoType>())
Douglas Gregor3c385e52009-02-14 18:57:46 +0000207 HasVAListArg = !Proto->isVariadic();
Ted Kremenek3d692df2009-02-27 17:58:43 +0000208 }
Douglas Gregor3c385e52009-02-14 18:57:46 +0000209 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
Ted Kremenek3d692df2009-02-27 17:58:43 +0000210 HasVAListArg ? 0 : Format->getFirstArg() - 1);
Douglas Gregor3c385e52009-02-14 18:57:46 +0000211 }
Chris Lattner59907c42007-08-10 20:18:51 +0000212 }
Mike Stump1eb44332009-09-09 15:08:12 +0000213
214 for (const NonNullAttr *NonNull = FDecl->getAttr<NonNullAttr>(); NonNull;
Anders Carlssond406bf02009-08-16 01:56:34 +0000215 NonNull = NonNull->getNext<NonNullAttr>())
216 CheckNonNullArguments(NonNull, TheCall);
Sebastian Redl0eb23302009-01-19 00:08:26 +0000217
Anders Carlssond406bf02009-08-16 01:56:34 +0000218 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000219}
220
Anders Carlssond406bf02009-08-16 01:56:34 +0000221bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000222 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000223 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000224 if (!Format)
Anders Carlssond406bf02009-08-16 01:56:34 +0000225 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000226
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000227 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
228 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000229 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000230
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000231 QualType Ty = V->getType();
232 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000233 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000234
Anders Carlssond406bf02009-08-16 01:56:34 +0000235 if (!CheckablePrintfAttr(Format, TheCall))
236 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000237
Anders Carlssond406bf02009-08-16 01:56:34 +0000238 bool HasVAListArg = Format->getFirstArg() == 0;
239 if (!HasVAListArg) {
Mike Stump1eb44332009-09-09 15:08:12 +0000240 const FunctionType *FT =
John McCall183700f2009-09-21 23:43:11 +0000241 Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Anders Carlssond406bf02009-08-16 01:56:34 +0000242 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
243 HasVAListArg = !Proto->isVariadic();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000244 }
Anders Carlssond406bf02009-08-16 01:56:34 +0000245 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
246 HasVAListArg ? 0 : Format->getFirstArg() - 1);
247
248 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000249}
250
Chris Lattner5caa3702009-05-08 06:58:22 +0000251/// SemaBuiltinAtomicOverloaded - We have a call to a function like
252/// __sync_fetch_and_add, which is an overloaded function based on the pointer
253/// type of its first argument. The main ActOnCallExpr routines have already
254/// promoted the types of arguments because all of these calls are prototyped as
255/// void(...).
256///
257/// This function goes through and does final semantic checking for these
258/// builtins,
259bool Sema::SemaBuiltinAtomicOverloaded(CallExpr *TheCall) {
260 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
261 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
262
263 // Ensure that we have at least one argument to do type inference from.
264 if (TheCall->getNumArgs() < 1)
265 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
266 << 0 << TheCall->getCallee()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000267
Chris Lattner5caa3702009-05-08 06:58:22 +0000268 // Inspect the first argument of the atomic builtin. This should always be
269 // a pointer type, whose element is an integral scalar or pointer type.
270 // Because it is a pointer type, we don't have to worry about any implicit
271 // casts here.
272 Expr *FirstArg = TheCall->getArg(0);
273 if (!FirstArg->getType()->isPointerType())
274 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
275 << FirstArg->getType() << FirstArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000276
Ted Kremenek6217b802009-07-29 21:53:49 +0000277 QualType ValType = FirstArg->getType()->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000278 if (!ValType->isIntegerType() && !ValType->isPointerType() &&
Chris Lattner5caa3702009-05-08 06:58:22 +0000279 !ValType->isBlockPointerType())
280 return Diag(DRE->getLocStart(),
281 diag::err_atomic_builtin_must_be_pointer_intptr)
282 << FirstArg->getType() << FirstArg->getSourceRange();
283
284 // We need to figure out which concrete builtin this maps onto. For example,
285 // __sync_fetch_and_add with a 2 byte object turns into
286 // __sync_fetch_and_add_2.
287#define BUILTIN_ROW(x) \
288 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
289 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000290
Chris Lattner5caa3702009-05-08 06:58:22 +0000291 static const unsigned BuiltinIndices[][5] = {
292 BUILTIN_ROW(__sync_fetch_and_add),
293 BUILTIN_ROW(__sync_fetch_and_sub),
294 BUILTIN_ROW(__sync_fetch_and_or),
295 BUILTIN_ROW(__sync_fetch_and_and),
296 BUILTIN_ROW(__sync_fetch_and_xor),
Chris Lattnereebd9d22009-05-13 04:37:52 +0000297 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump1eb44332009-09-09 15:08:12 +0000298
Chris Lattner5caa3702009-05-08 06:58:22 +0000299 BUILTIN_ROW(__sync_add_and_fetch),
300 BUILTIN_ROW(__sync_sub_and_fetch),
301 BUILTIN_ROW(__sync_and_and_fetch),
302 BUILTIN_ROW(__sync_or_and_fetch),
303 BUILTIN_ROW(__sync_xor_and_fetch),
Chris Lattnereebd9d22009-05-13 04:37:52 +0000304 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000305
Chris Lattner5caa3702009-05-08 06:58:22 +0000306 BUILTIN_ROW(__sync_val_compare_and_swap),
307 BUILTIN_ROW(__sync_bool_compare_and_swap),
308 BUILTIN_ROW(__sync_lock_test_and_set),
309 BUILTIN_ROW(__sync_lock_release)
310 };
Mike Stump1eb44332009-09-09 15:08:12 +0000311#undef BUILTIN_ROW
312
Chris Lattner5caa3702009-05-08 06:58:22 +0000313 // Determine the index of the size.
314 unsigned SizeIndex;
315 switch (Context.getTypeSize(ValType)/8) {
316 case 1: SizeIndex = 0; break;
317 case 2: SizeIndex = 1; break;
318 case 4: SizeIndex = 2; break;
319 case 8: SizeIndex = 3; break;
320 case 16: SizeIndex = 4; break;
321 default:
322 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
323 << FirstArg->getType() << FirstArg->getSourceRange();
324 }
Mike Stump1eb44332009-09-09 15:08:12 +0000325
Chris Lattner5caa3702009-05-08 06:58:22 +0000326 // Each of these builtins has one pointer argument, followed by some number of
327 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
328 // that we ignore. Find out which row of BuiltinIndices to read from as well
329 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000330 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000331 unsigned BuiltinIndex, NumFixed = 1;
332 switch (BuiltinID) {
333 default: assert(0 && "Unknown overloaded atomic builtin!");
334 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
335 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
336 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
337 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
338 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Chris Lattnereebd9d22009-05-13 04:37:52 +0000339 case Builtin::BI__sync_fetch_and_nand:BuiltinIndex = 5; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000340
Chris Lattnereebd9d22009-05-13 04:37:52 +0000341 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 6; break;
342 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 7; break;
343 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 8; break;
344 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 9; break;
345 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex =10; break;
346 case Builtin::BI__sync_nand_and_fetch:BuiltinIndex =11; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000347
Chris Lattner5caa3702009-05-08 06:58:22 +0000348 case Builtin::BI__sync_val_compare_and_swap:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000349 BuiltinIndex = 12;
Chris Lattner5caa3702009-05-08 06:58:22 +0000350 NumFixed = 2;
351 break;
352 case Builtin::BI__sync_bool_compare_and_swap:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000353 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000354 NumFixed = 2;
355 break;
Chris Lattnereebd9d22009-05-13 04:37:52 +0000356 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 14; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000357 case Builtin::BI__sync_lock_release:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000358 BuiltinIndex = 15;
Chris Lattner5caa3702009-05-08 06:58:22 +0000359 NumFixed = 0;
360 break;
361 }
Mike Stump1eb44332009-09-09 15:08:12 +0000362
Chris Lattner5caa3702009-05-08 06:58:22 +0000363 // Now that we know how many fixed arguments we expect, first check that we
364 // have at least that many.
365 if (TheCall->getNumArgs() < 1+NumFixed)
366 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
367 << 0 << TheCall->getCallee()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000368
369
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000370 // Get the decl for the concrete builtin from this, we can tell what the
371 // concrete integer type we should convert to is.
372 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
373 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
374 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +0000375 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000376 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
377 TUScope, false, DRE->getLocStart()));
378 const FunctionProtoType *BuiltinFT =
John McCall183700f2009-09-21 23:43:11 +0000379 NewBuiltinDecl->getType()->getAs<FunctionProtoType>();
Ted Kremenek6217b802009-07-29 21:53:49 +0000380 ValType = BuiltinFT->getArgType(0)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000381
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000382 // If the first type needs to be converted (e.g. void** -> int*), do it now.
383 if (BuiltinFT->getArgType(0) != FirstArg->getType()) {
Anders Carlsson3503d042009-07-31 01:23:52 +0000384 ImpCastExprToType(FirstArg, BuiltinFT->getArgType(0), CastExpr::CK_Unknown,
385 /*isLvalue=*/false);
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000386 TheCall->setArg(0, FirstArg);
387 }
Mike Stump1eb44332009-09-09 15:08:12 +0000388
Chris Lattner5caa3702009-05-08 06:58:22 +0000389 // Next, walk the valid ones promoting to the right type.
390 for (unsigned i = 0; i != NumFixed; ++i) {
391 Expr *Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +0000392
Chris Lattner5caa3702009-05-08 06:58:22 +0000393 // If the argument is an implicit cast, then there was a promotion due to
394 // "...", just remove it now.
395 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
396 Arg = ICE->getSubExpr();
397 ICE->setSubExpr(0);
398 ICE->Destroy(Context);
399 TheCall->setArg(i+1, Arg);
400 }
Mike Stump1eb44332009-09-09 15:08:12 +0000401
Chris Lattner5caa3702009-05-08 06:58:22 +0000402 // GCC does an implicit conversion to the pointer or integer ValType. This
403 // can fail in some cases (1i -> int**), check for this error case now.
Anders Carlssoncdb61972009-08-07 22:21:05 +0000404 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000405 CXXMethodDecl *ConversionDecl = 0;
406 if (CheckCastTypes(Arg->getSourceRange(), ValType, Arg, Kind,
407 ConversionDecl))
Chris Lattner5caa3702009-05-08 06:58:22 +0000408 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000409
Chris Lattner5caa3702009-05-08 06:58:22 +0000410 // Okay, we have something that *can* be converted to the right type. Check
411 // to see if there is a potentially weird extension going on here. This can
412 // happen when you do an atomic operation on something like an char* and
413 // pass in 42. The 42 gets converted to char. This is even more strange
414 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +0000415 // FIXME: Do this check.
Anders Carlssoncdb61972009-08-07 22:21:05 +0000416 ImpCastExprToType(Arg, ValType, Kind, /*isLvalue=*/false);
Chris Lattner5caa3702009-05-08 06:58:22 +0000417 TheCall->setArg(i+1, Arg);
418 }
Mike Stump1eb44332009-09-09 15:08:12 +0000419
Chris Lattner5caa3702009-05-08 06:58:22 +0000420 // Switch the DeclRefExpr to refer to the new decl.
421 DRE->setDecl(NewBuiltinDecl);
422 DRE->setType(NewBuiltinDecl->getType());
Mike Stump1eb44332009-09-09 15:08:12 +0000423
Chris Lattner5caa3702009-05-08 06:58:22 +0000424 // Set the callee in the CallExpr.
425 // FIXME: This leaks the original parens and implicit casts.
426 Expr *PromotedCall = DRE;
427 UsualUnaryConversions(PromotedCall);
428 TheCall->setCallee(PromotedCall);
Mike Stump1eb44332009-09-09 15:08:12 +0000429
Chris Lattner5caa3702009-05-08 06:58:22 +0000430
431 // Change the result type of the call to match the result type of the decl.
432 TheCall->setType(NewBuiltinDecl->getResultType());
433 return false;
434}
435
436
Chris Lattner69039812009-02-18 06:01:06 +0000437/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000438/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +0000439/// FIXME: GCC currently emits the following warning:
Mike Stump1eb44332009-09-09 15:08:12 +0000440/// "warning: input conversion stopped due to an input byte that does not
Steve Narofffd942622009-04-13 20:26:29 +0000441/// belong to the input codeset UTF-8"
442/// Note: It might also make sense to do the UTF-16 conversion here (would
443/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +0000444bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000445 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000446 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
447
448 if (!Literal || Literal->isWide()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000449 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
450 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000451 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000452 }
Mike Stump1eb44332009-09-09 15:08:12 +0000453
Daniel Dunbarf015b032009-09-22 10:03:52 +0000454 const char *Data = Literal->getStrData();
455 unsigned Length = Literal->getByteLength();
Mike Stump1eb44332009-09-09 15:08:12 +0000456
Daniel Dunbarf015b032009-09-22 10:03:52 +0000457 for (unsigned i = 0; i < Length; ++i) {
458 if (!Data[i]) {
459 Diag(getLocationOfStringLiteralByte(Literal, i),
460 diag::warn_cfstring_literal_contains_nul_character)
461 << Arg->getSourceRange();
462 break;
463 }
464 }
Mike Stump1eb44332009-09-09 15:08:12 +0000465
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000466 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000467}
468
Chris Lattnerc27c6652007-12-20 00:05:45 +0000469/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
470/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000471bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
472 Expr *Fn = TheCall->getCallee();
473 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000474 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000475 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000476 << 0 /*function call*/ << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +0000477 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000478 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000479 return true;
480 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000481
482 if (TheCall->getNumArgs() < 2) {
483 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
484 << 0 /*function call*/;
485 }
486
Chris Lattnerc27c6652007-12-20 00:05:45 +0000487 // Determine whether the current function is variadic or not.
488 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000489 if (CurBlock)
490 isVariadic = CurBlock->isVariadic;
491 else if (getCurFunctionDecl()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000492 if (FunctionProtoType* FTP =
493 dyn_cast<FunctionProtoType>(getCurFunctionDecl()->getType()))
Eli Friedman56f20ae2008-12-15 22:05:35 +0000494 isVariadic = FTP->isVariadic();
495 else
496 isVariadic = false;
497 } else {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000498 isVariadic = getCurMethodDecl()->isVariadic();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000499 }
Mike Stump1eb44332009-09-09 15:08:12 +0000500
Chris Lattnerc27c6652007-12-20 00:05:45 +0000501 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000502 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
503 return true;
504 }
Mike Stump1eb44332009-09-09 15:08:12 +0000505
Chris Lattner30ce3442007-12-19 23:59:04 +0000506 // Verify that the second argument to the builtin is the last argument of the
507 // current function or method.
508 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000509 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +0000510
Anders Carlsson88cf2262008-02-11 04:20:54 +0000511 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
512 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000513 // FIXME: This isn't correct for methods (results in bogus warning).
514 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000515 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000516 if (CurBlock)
517 LastArg = *(CurBlock->TheDecl->param_end()-1);
518 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +0000519 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000520 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000521 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000522 SecondArgIsLastNamedArgument = PV == LastArg;
523 }
524 }
Mike Stump1eb44332009-09-09 15:08:12 +0000525
Chris Lattner30ce3442007-12-19 23:59:04 +0000526 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +0000527 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000528 diag::warn_second_parameter_of_va_start_not_last_named_argument);
529 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000530}
Chris Lattner30ce3442007-12-19 23:59:04 +0000531
Chris Lattner1b9a0792007-12-20 00:26:33 +0000532/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
533/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000534bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
535 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000536 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
537 << 0 /*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000538 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +0000539 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000540 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000541 << 0 /*function call*/
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000542 << SourceRange(TheCall->getArg(2)->getLocStart(),
543 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000544
Chris Lattner925e60d2007-12-28 05:29:59 +0000545 Expr *OrigArg0 = TheCall->getArg(0);
546 Expr *OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000547
Chris Lattner1b9a0792007-12-20 00:26:33 +0000548 // Do standard promotions between the two arguments, returning their common
549 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000550 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Daniel Dunbar403bc2b2009-02-19 19:28:43 +0000551
552 // Make sure any conversions are pushed back into the call; this is
553 // type safe since unordered compare builtins are declared as "_Bool
554 // foo(...)".
555 TheCall->setArg(0, OrigArg0);
556 TheCall->setArg(1, OrigArg1);
Mike Stump1eb44332009-09-09 15:08:12 +0000557
Douglas Gregorcde01732009-05-19 22:10:17 +0000558 if (OrigArg0->isTypeDependent() || OrigArg1->isTypeDependent())
559 return false;
560
Chris Lattner1b9a0792007-12-20 00:26:33 +0000561 // If the common type isn't a real floating type, then the arguments were
562 // invalid for this operation.
563 if (!Res->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000564 return Diag(OrigArg0->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000565 diag::err_typecheck_call_invalid_ordered_compare)
Chris Lattnerd1625842008-11-24 06:25:27 +0000566 << OrigArg0->getType() << OrigArg1->getType()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000567 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000568
Chris Lattner1b9a0792007-12-20 00:26:33 +0000569 return false;
570}
571
Eli Friedman9ac6f622009-08-31 20:06:00 +0000572/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isnan and
573/// friends. This is declared to take (...), so we have to check everything.
574bool Sema::SemaBuiltinUnaryFP(CallExpr *TheCall) {
575 if (TheCall->getNumArgs() < 1)
576 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
577 << 0 /*function call*/;
578 if (TheCall->getNumArgs() > 1)
Mike Stump1eb44332009-09-09 15:08:12 +0000579 return Diag(TheCall->getArg(1)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000580 diag::err_typecheck_call_too_many_args)
581 << 0 /*function call*/
582 << SourceRange(TheCall->getArg(1)->getLocStart(),
583 (*(TheCall->arg_end()-1))->getLocEnd());
584
585 Expr *OrigArg = TheCall->getArg(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000586
Eli Friedman9ac6f622009-08-31 20:06:00 +0000587 if (OrigArg->isTypeDependent())
588 return false;
589
590 // This operation requires a floating-point number
591 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000592 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000593 diag::err_typecheck_call_invalid_unary_fp)
594 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000595
Eli Friedman9ac6f622009-08-31 20:06:00 +0000596 return false;
597}
598
Eli Friedman6cfda232008-05-20 08:23:37 +0000599bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) {
600 // The signature for these builtins is exact; the only thing we need
601 // to check is that the argument is a constant.
602 SourceLocation Loc;
Douglas Gregorcde01732009-05-19 22:10:17 +0000603 if (!TheCall->getArg(0)->isTypeDependent() &&
604 !TheCall->getArg(0)->isValueDependent() &&
605 !TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc))
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000606 return Diag(Loc, diag::err_stack_const_level) << TheCall->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000607
Eli Friedman6cfda232008-05-20 08:23:37 +0000608 return false;
609}
610
Eli Friedmand38617c2008-05-14 19:38:39 +0000611/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
612// This is declared to take (...), so we have to check everything.
Sebastian Redl0eb23302009-01-19 00:08:26 +0000613Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000614 if (TheCall->getNumArgs() < 3)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000615 return ExprError(Diag(TheCall->getLocEnd(),
616 diag::err_typecheck_call_too_few_args)
617 << 0 /*function call*/ << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000618
Douglas Gregorcde01732009-05-19 22:10:17 +0000619 unsigned numElements = std::numeric_limits<unsigned>::max();
620 if (!TheCall->getArg(0)->isTypeDependent() &&
621 !TheCall->getArg(1)->isTypeDependent()) {
622 QualType FAType = TheCall->getArg(0)->getType();
623 QualType SAType = TheCall->getArg(1)->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000624
Douglas Gregorcde01732009-05-19 22:10:17 +0000625 if (!FAType->isVectorType() || !SAType->isVectorType()) {
626 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000627 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000628 TheCall->getArg(1)->getLocEnd());
629 return ExprError();
630 }
Mike Stump1eb44332009-09-09 15:08:12 +0000631
Douglas Gregorcde01732009-05-19 22:10:17 +0000632 if (Context.getCanonicalType(FAType).getUnqualifiedType() !=
633 Context.getCanonicalType(SAType).getUnqualifiedType()) {
634 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000635 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000636 TheCall->getArg(1)->getLocEnd());
637 return ExprError();
638 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000639
John McCall183700f2009-09-21 23:43:11 +0000640 numElements = FAType->getAs<VectorType>()->getNumElements();
Douglas Gregorcde01732009-05-19 22:10:17 +0000641 if (TheCall->getNumArgs() != numElements+2) {
642 if (TheCall->getNumArgs() < numElements+2)
643 return ExprError(Diag(TheCall->getLocEnd(),
644 diag::err_typecheck_call_too_few_args)
645 << 0 /*function call*/ << TheCall->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000646 return ExprError(Diag(TheCall->getLocEnd(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000647 diag::err_typecheck_call_too_many_args)
648 << 0 /*function call*/ << TheCall->getSourceRange());
649 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000650 }
651
652 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000653 if (TheCall->getArg(i)->isTypeDependent() ||
654 TheCall->getArg(i)->isValueDependent())
655 continue;
656
Eli Friedmand38617c2008-05-14 19:38:39 +0000657 llvm::APSInt Result(32);
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000658 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000659 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000660 diag::err_shufflevector_nonconstant_argument)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000661 << TheCall->getArg(i)->getSourceRange());
662
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000663 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000664 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000665 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000666 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000667 }
668
669 llvm::SmallVector<Expr*, 32> exprs;
670
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000671 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000672 exprs.push_back(TheCall->getArg(i));
673 TheCall->setArg(i, 0);
674 }
675
Nate Begemana88dc302009-08-12 02:10:25 +0000676 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
677 exprs.size(), exprs[0]->getType(),
Ted Kremenek8189cde2009-02-07 01:47:29 +0000678 TheCall->getCallee()->getLocStart(),
679 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000680}
Chris Lattner30ce3442007-12-19 23:59:04 +0000681
Daniel Dunbar4493f792008-07-21 22:59:13 +0000682/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
683// This is declared to take (const void*, ...) and can take two
684// optional constant int args.
685bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000686 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000687
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000688 if (NumArgs > 3)
689 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000690 << 0 /*function call*/ << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000691
692 // Argument 0 is checked for us and the remaining arguments must be
693 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000694 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000695 Expr *Arg = TheCall->getArg(i);
Douglas Gregorcde01732009-05-19 22:10:17 +0000696 if (Arg->isTypeDependent())
697 continue;
698
Daniel Dunbar4493f792008-07-21 22:59:13 +0000699 QualType RWType = Arg->getType();
700
John McCall183700f2009-09-21 23:43:11 +0000701 const BuiltinType *BT = RWType->getAs<BuiltinType>();
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000702 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +0000703 if (!BT || BT->getKind() != BuiltinType::Int)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000704 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000705 << Arg->getSourceRange();
Douglas Gregorcde01732009-05-19 22:10:17 +0000706
707 if (Arg->isValueDependent())
708 continue;
709
710 if (!Arg->isIntegerConstantExpr(Result, Context))
711 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_argument)
712 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000713
Daniel Dunbar4493f792008-07-21 22:59:13 +0000714 // FIXME: gcc issues a warning and rewrites these to 0. These
715 // seems especially odd for the third argument since the default
716 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000717 if (i == 1) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000718 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000719 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000720 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000721 } else {
722 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000723 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000724 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000725 }
726 }
727
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000728 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000729}
730
Chris Lattner21fb98e2009-09-23 06:06:36 +0000731/// SemaBuiltinEHReturnDataRegNo - Handle __builtin_eh_return_data_regno, the
732/// operand must be an integer constant.
733bool Sema::SemaBuiltinEHReturnDataRegNo(CallExpr *TheCall) {
734 llvm::APSInt Result;
735 if (!TheCall->getArg(0)->isIntegerConstantExpr(Result, Context))
736 return Diag(TheCall->getLocStart(), diag::err_expr_not_ice)
737 << TheCall->getArg(0)->getSourceRange();
738
739 return false;
740}
741
742
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000743/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
744/// int type). This simply type checks that type is one of the defined
745/// constants (0-3).
746bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
747 Expr *Arg = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000748 if (Arg->isTypeDependent())
749 return false;
750
Mike Stump1eb44332009-09-09 15:08:12 +0000751 QualType ArgType = Arg->getType();
John McCall183700f2009-09-21 23:43:11 +0000752 const BuiltinType *BT = ArgType->getAs<BuiltinType>();
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000753 llvm::APSInt Result(32);
Douglas Gregorcde01732009-05-19 22:10:17 +0000754 if (!BT || BT->getKind() != BuiltinType::Int)
755 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
756 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
757
758 if (Arg->isValueDependent())
759 return false;
760
761 if (!Arg->isIntegerConstantExpr(Result, Context)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000762 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
763 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000764 }
765
766 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000767 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
768 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000769 }
770
771 return false;
772}
773
Eli Friedman586d6a82009-05-03 06:04:26 +0000774/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +0000775/// This checks that val is a constant 1.
776bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
777 Expr *Arg = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000778 if (Arg->isTypeDependent() || Arg->isValueDependent())
779 return false;
780
Eli Friedmand875fed2009-05-03 04:46:36 +0000781 llvm::APSInt Result(32);
782 if (!Arg->isIntegerConstantExpr(Result, Context) || Result != 1)
783 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
784 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
785
786 return false;
787}
788
Ted Kremenekd30ef872009-01-12 23:09:09 +0000789// Handle i > 1 ? "x" : "y", recursivelly
Ted Kremenek082d9362009-03-20 21:35:28 +0000790bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
791 bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000792 unsigned format_idx, unsigned firstDataArg) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000793 if (E->isTypeDependent() || E->isValueDependent())
794 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000795
796 switch (E->getStmtClass()) {
797 case Stmt::ConditionalOperatorClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000798 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000799 return SemaCheckStringLiteral(C->getLHS(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000800 HasVAListArg, format_idx, firstDataArg)
Ted Kremenekd30ef872009-01-12 23:09:09 +0000801 && SemaCheckStringLiteral(C->getRHS(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000802 HasVAListArg, format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000803 }
804
805 case Stmt::ImplicitCastExprClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000806 const ImplicitCastExpr *Expr = cast<ImplicitCastExpr>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000807 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000808 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000809 }
810
811 case Stmt::ParenExprClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000812 const ParenExpr *Expr = cast<ParenExpr>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000813 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000814 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000815 }
Mike Stump1eb44332009-09-09 15:08:12 +0000816
Ted Kremenek082d9362009-03-20 21:35:28 +0000817 case Stmt::DeclRefExprClass: {
818 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000819
Ted Kremenek082d9362009-03-20 21:35:28 +0000820 // As an exception, do not flag errors for variables binding to
821 // const string literals.
822 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
823 bool isConstant = false;
824 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +0000825
Ted Kremenek082d9362009-03-20 21:35:28 +0000826 if (const ArrayType *AT = Context.getAsArrayType(T)) {
827 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000828 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000829 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +0000830 PT->getPointeeType().isConstant(Context);
831 }
Mike Stump1eb44332009-09-09 15:08:12 +0000832
Ted Kremenek082d9362009-03-20 21:35:28 +0000833 if (isConstant) {
834 const VarDecl *Def = 0;
835 if (const Expr *Init = VD->getDefinition(Def))
836 return SemaCheckStringLiteral(Init, TheCall,
837 HasVAListArg, format_idx, firstDataArg);
838 }
Mike Stump1eb44332009-09-09 15:08:12 +0000839
Anders Carlssond966a552009-06-28 19:55:58 +0000840 // For vprintf* functions (i.e., HasVAListArg==true), we add a
841 // special check to see if the format string is a function parameter
842 // of the function calling the printf function. If the function
843 // has an attribute indicating it is a printf-like function, then we
844 // should suppress warnings concerning non-literals being used in a call
845 // to a vprintf function. For example:
846 //
847 // void
848 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
849 // va_list ap;
850 // va_start(ap, fmt);
851 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
852 // ...
853 //
854 //
855 // FIXME: We don't have full attribute support yet, so just check to see
856 // if the argument is a DeclRefExpr that references a parameter. We'll
857 // add proper support for checking the attribute later.
858 if (HasVAListArg)
859 if (isa<ParmVarDecl>(VD))
860 return true;
Ted Kremenek082d9362009-03-20 21:35:28 +0000861 }
Mike Stump1eb44332009-09-09 15:08:12 +0000862
Ted Kremenek082d9362009-03-20 21:35:28 +0000863 return false;
864 }
Ted Kremenekd30ef872009-01-12 23:09:09 +0000865
Anders Carlsson8f031b32009-06-27 04:05:33 +0000866 case Stmt::CallExprClass: {
867 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000868 if (const ImplicitCastExpr *ICE
Anders Carlsson8f031b32009-06-27 04:05:33 +0000869 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
870 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
871 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000872 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlsson8f031b32009-06-27 04:05:33 +0000873 unsigned ArgIndex = FA->getFormatIdx();
874 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +0000875
876 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Anders Carlsson8f031b32009-06-27 04:05:33 +0000877 format_idx, firstDataArg);
878 }
879 }
880 }
881 }
Mike Stump1eb44332009-09-09 15:08:12 +0000882
Anders Carlsson8f031b32009-06-27 04:05:33 +0000883 return false;
884 }
Ted Kremenek082d9362009-03-20 21:35:28 +0000885 case Stmt::ObjCStringLiteralClass:
886 case Stmt::StringLiteralClass: {
887 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +0000888
Ted Kremenek082d9362009-03-20 21:35:28 +0000889 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +0000890 StrE = ObjCFExpr->getString();
891 else
Ted Kremenek082d9362009-03-20 21:35:28 +0000892 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000893
Ted Kremenekd30ef872009-01-12 23:09:09 +0000894 if (StrE) {
Mike Stump1eb44332009-09-09 15:08:12 +0000895 CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000896 firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000897 return true;
898 }
Mike Stump1eb44332009-09-09 15:08:12 +0000899
Ted Kremenekd30ef872009-01-12 23:09:09 +0000900 return false;
901 }
Mike Stump1eb44332009-09-09 15:08:12 +0000902
Ted Kremenek082d9362009-03-20 21:35:28 +0000903 default:
904 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000905 }
906}
907
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +0000908void
Mike Stump1eb44332009-09-09 15:08:12 +0000909Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
910 const CallExpr *TheCall) {
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +0000911 for (NonNullAttr::iterator i = NonNull->begin(), e = NonNull->end();
912 i != e; ++i) {
Chris Lattner12b97ff2009-05-25 18:23:36 +0000913 const Expr *ArgExpr = TheCall->getArg(*i);
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +0000914 if (ArgExpr->isNullPointerConstant(Context))
Chris Lattner12b97ff2009-05-25 18:23:36 +0000915 Diag(TheCall->getCallee()->getLocStart(), diag::warn_null_arg)
916 << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +0000917 }
918}
Ted Kremenekd30ef872009-01-12 23:09:09 +0000919
Chris Lattner59907c42007-08-10 20:18:51 +0000920/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Mike Stump1eb44332009-09-09 15:08:12 +0000921/// correct use of format strings.
Ted Kremenek71895b92007-08-14 17:39:48 +0000922///
923/// HasVAListArg - A predicate indicating whether the printf-like
924/// function is passed an explicit va_arg argument (e.g., vprintf)
925///
926/// format_idx - The index into Args for the format string.
927///
928/// Improper format strings to functions in the printf family can be
929/// the source of bizarre bugs and very serious security holes. A
930/// good source of information is available in the following paper
931/// (which includes additional references):
Chris Lattner59907c42007-08-10 20:18:51 +0000932///
933/// FormatGuard: Automatic Protection From printf Format String
934/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremenek71895b92007-08-14 17:39:48 +0000935///
936/// Functionality implemented:
937///
938/// We can statically check the following properties for string
939/// literal format strings for non v.*printf functions (where the
940/// arguments are passed directly):
941//
942/// (1) Are the number of format conversions equal to the number of
943/// data arguments?
944///
945/// (2) Does each format conversion correctly match the type of the
946/// corresponding data argument? (TODO)
947///
948/// Moreover, for all printf functions we can:
949///
950/// (3) Check for a missing format string (when not caught by type checking).
951///
952/// (4) Check for no-operation flags; e.g. using "#" with format
953/// conversion 'c' (TODO)
954///
955/// (5) Check the use of '%n', a major source of security holes.
956///
957/// (6) Check for malformed format conversions that don't specify anything.
958///
959/// (7) Check for empty format strings. e.g: printf("");
960///
961/// (8) Check that the format string is a wide literal.
962///
Ted Kremenek6d439592008-03-03 16:50:00 +0000963/// (9) Also check the arguments of functions with the __format__ attribute.
964/// (TODO).
965///
Ted Kremenek71895b92007-08-14 17:39:48 +0000966/// All of these checks can be done by parsing the format string.
967///
968/// For now, we ONLY do (1), (3), (5), (6), (7), and (8).
Chris Lattner59907c42007-08-10 20:18:51 +0000969void
Mike Stump1eb44332009-09-09 15:08:12 +0000970Sema::CheckPrintfArguments(const CallExpr *TheCall, bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000971 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenek082d9362009-03-20 21:35:28 +0000972 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +0000973
Mike Stump1eb44332009-09-09 15:08:12 +0000974 // CHECK: printf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +0000975 if (format_idx >= TheCall->getNumArgs()) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000976 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string)
977 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000978 return;
979 }
Mike Stump1eb44332009-09-09 15:08:12 +0000980
Ted Kremenek082d9362009-03-20 21:35:28 +0000981 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +0000982
Chris Lattner59907c42007-08-10 20:18:51 +0000983 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +0000984 //
Ted Kremenek71895b92007-08-14 17:39:48 +0000985 // Dynamically generated format strings are difficult to
986 // automatically vet at compile time. Requiring that format strings
987 // are string literals: (1) permits the checking of format strings by
988 // the compiler and thereby (2) can practically remove the source of
989 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000990
Mike Stump1eb44332009-09-09 15:08:12 +0000991 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000992 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +0000993 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000994 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +0000995 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
996 firstDataArg))
997 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +0000998
Chris Lattner655f1412009-04-29 04:59:47 +0000999 // If there are no arguments specified, warn with -Wformat-security, otherwise
1000 // warn only with -Wformat-nonliteral.
1001 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump1eb44332009-09-09 15:08:12 +00001002 Diag(TheCall->getArg(format_idx)->getLocStart(),
Chris Lattner655f1412009-04-29 04:59:47 +00001003 diag::warn_printf_nonliteral_noargs)
1004 << OrigFormatExpr->getSourceRange();
1005 else
Mike Stump1eb44332009-09-09 15:08:12 +00001006 Diag(TheCall->getArg(format_idx)->getLocStart(),
Chris Lattner655f1412009-04-29 04:59:47 +00001007 diag::warn_printf_nonliteral)
1008 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001009}
Ted Kremenek71895b92007-08-14 17:39:48 +00001010
Ted Kremenek082d9362009-03-20 21:35:28 +00001011void Sema::CheckPrintfString(const StringLiteral *FExpr,
1012 const Expr *OrigFormatExpr,
1013 const CallExpr *TheCall, bool HasVAListArg,
1014 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenekd30ef872009-01-12 23:09:09 +00001015
Ted Kremenek082d9362009-03-20 21:35:28 +00001016 const ObjCStringLiteral *ObjCFExpr =
1017 dyn_cast<ObjCStringLiteral>(OrigFormatExpr);
1018
Ted Kremenek71895b92007-08-14 17:39:48 +00001019 // CHECK: is the format string a wide literal?
1020 if (FExpr->isWide()) {
Chris Lattner925e60d2007-12-28 05:29:59 +00001021 Diag(FExpr->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001022 diag::warn_printf_format_string_is_wide_literal)
1023 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001024 return;
1025 }
1026
1027 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattnerb9fc8562009-04-29 04:12:34 +00001028 const char *Str = FExpr->getStrData();
Ted Kremenek71895b92007-08-14 17:39:48 +00001029
1030 // CHECK: empty format string?
Chris Lattnerb9fc8562009-04-29 04:12:34 +00001031 unsigned StrLen = FExpr->getByteLength();
Mike Stump1eb44332009-09-09 15:08:12 +00001032
Ted Kremenek71895b92007-08-14 17:39:48 +00001033 if (StrLen == 0) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001034 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string)
1035 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001036 return;
1037 }
1038
1039 // We process the format string using a binary state machine. The
1040 // current state is stored in CurrentState.
1041 enum {
1042 state_OrdChr,
1043 state_Conversion
1044 } CurrentState = state_OrdChr;
Mike Stump1eb44332009-09-09 15:08:12 +00001045
Ted Kremenek71895b92007-08-14 17:39:48 +00001046 // numConversions - The number of conversions seen so far. This is
1047 // incremented as we traverse the format string.
1048 unsigned numConversions = 0;
1049
1050 // numDataArgs - The number of data arguments after the format
1051 // string. This can only be determined for non vprintf-like
1052 // functions. For those functions, this value is 1 (the sole
1053 // va_arg argument).
Douglas Gregor3c385e52009-02-14 18:57:46 +00001054 unsigned numDataArgs = TheCall->getNumArgs()-firstDataArg;
Ted Kremenek71895b92007-08-14 17:39:48 +00001055
1056 // Inspect the format string.
1057 unsigned StrIdx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001058
Ted Kremenek71895b92007-08-14 17:39:48 +00001059 // LastConversionIdx - Index within the format string where we last saw
1060 // a '%' character that starts a new format conversion.
1061 unsigned LastConversionIdx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001062
Chris Lattner925e60d2007-12-28 05:29:59 +00001063 for (; StrIdx < StrLen; ++StrIdx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001064
Ted Kremenek71895b92007-08-14 17:39:48 +00001065 // Is the number of detected conversion conversions greater than
1066 // the number of matching data arguments? If so, stop.
1067 if (!HasVAListArg && numConversions > numDataArgs) break;
Mike Stump1eb44332009-09-09 15:08:12 +00001068
Ted Kremenek71895b92007-08-14 17:39:48 +00001069 // Handle "\0"
Chris Lattner925e60d2007-12-28 05:29:59 +00001070 if (Str[StrIdx] == '\0') {
Ted Kremenek71895b92007-08-14 17:39:48 +00001071 // The string returned by getStrData() is not null-terminated,
1072 // so the presence of a null character is likely an error.
Chris Lattner60800082009-02-18 17:49:48 +00001073 Diag(getLocationOfStringLiteralByte(FExpr, StrIdx),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001074 diag::warn_printf_format_string_contains_null_char)
1075 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001076 return;
1077 }
Mike Stump1eb44332009-09-09 15:08:12 +00001078
Ted Kremenek71895b92007-08-14 17:39:48 +00001079 // Ordinary characters (not processing a format conversion).
1080 if (CurrentState == state_OrdChr) {
1081 if (Str[StrIdx] == '%') {
1082 CurrentState = state_Conversion;
1083 LastConversionIdx = StrIdx;
1084 }
1085 continue;
1086 }
1087
1088 // Seen '%'. Now processing a format conversion.
1089 switch (Str[StrIdx]) {
Mike Stump1eb44332009-09-09 15:08:12 +00001090 // Handle dynamic precision or width specifier.
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001091 case '*': {
1092 ++numConversions;
Mike Stump1eb44332009-09-09 15:08:12 +00001093
Ted Kremenek42ae3e82009-05-13 16:06:05 +00001094 if (!HasVAListArg) {
1095 if (numConversions > numDataArgs) {
1096 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx);
Ted Kremenek580b6642007-10-12 20:51:52 +00001097
Ted Kremenek42ae3e82009-05-13 16:06:05 +00001098 if (Str[StrIdx-1] == '.')
1099 Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg)
1100 << OrigFormatExpr->getSourceRange();
1101 else
1102 Diag(Loc, diag::warn_printf_asterisk_width_missing_arg)
1103 << OrigFormatExpr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001104
Ted Kremenek42ae3e82009-05-13 16:06:05 +00001105 // Don't do any more checking. We'll just emit spurious errors.
1106 return;
1107 }
Mike Stump1eb44332009-09-09 15:08:12 +00001108
Ted Kremenek42ae3e82009-05-13 16:06:05 +00001109 // Perform type checking on width/precision specifier.
1110 const Expr *E = TheCall->getArg(format_idx+numConversions);
John McCall183700f2009-09-21 23:43:11 +00001111 if (const BuiltinType *BT = E->getType()->getAs<BuiltinType>())
Ted Kremenek42ae3e82009-05-13 16:06:05 +00001112 if (BT->getKind() == BuiltinType::Int)
1113 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001114
Ted Kremenek42ae3e82009-05-13 16:06:05 +00001115 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00001116
Ted Kremenek42ae3e82009-05-13 16:06:05 +00001117 if (Str[StrIdx-1] == '.')
1118 Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type)
1119 << E->getType() << E->getSourceRange();
1120 else
1121 Diag(Loc, diag::warn_printf_asterisk_width_wrong_type)
1122 << E->getType() << E->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001123
1124 break;
Ted Kremenek580b6642007-10-12 20:51:52 +00001125 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001126 }
Mike Stump1eb44332009-09-09 15:08:12 +00001127
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001128 // Characters which can terminate a format conversion
1129 // (e.g. "%d"). Characters that specify length modifiers or
1130 // other flags are handled by the default case below.
1131 //
Mike Stump1eb44332009-09-09 15:08:12 +00001132 // FIXME: additional checks will go into the following cases.
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001133 case 'i':
1134 case 'd':
Mike Stump1eb44332009-09-09 15:08:12 +00001135 case 'o':
1136 case 'u':
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001137 case 'x':
1138 case 'X':
1139 case 'D':
1140 case 'O':
1141 case 'U':
1142 case 'e':
1143 case 'E':
1144 case 'f':
1145 case 'F':
1146 case 'g':
1147 case 'G':
1148 case 'a':
1149 case 'A':
1150 case 'c':
1151 case 'C':
1152 case 'S':
1153 case 's':
Mike Stump1eb44332009-09-09 15:08:12 +00001154 case 'p':
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001155 ++numConversions;
1156 CurrentState = state_OrdChr;
1157 break;
1158
Eli Friedmanb92abb42009-06-02 08:36:19 +00001159 case 'm':
1160 // FIXME: Warn in situations where this isn't supported!
1161 CurrentState = state_OrdChr;
1162 break;
1163
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001164 // CHECK: Are we using "%n"? Issue a warning.
1165 case 'n': {
1166 ++numConversions;
1167 CurrentState = state_OrdChr;
Chris Lattner60800082009-02-18 17:49:48 +00001168 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr,
1169 LastConversionIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00001170
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001171 Diag(Loc, diag::warn_printf_write_back)<<OrigFormatExpr->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001172 break;
1173 }
Mike Stump1eb44332009-09-09 15:08:12 +00001174
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001175 // Handle "%@"
1176 case '@':
1177 // %@ is allowed in ObjC format strings only.
Mike Stump1eb44332009-09-09 15:08:12 +00001178 if (ObjCFExpr != NULL)
1179 CurrentState = state_OrdChr;
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001180 else {
1181 // Issue a warning: invalid format conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00001182 SourceLocation Loc =
Chris Lattner60800082009-02-18 17:49:48 +00001183 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00001184
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001185 Diag(Loc, diag::warn_printf_invalid_conversion)
1186 << std::string(Str+LastConversionIdx,
1187 Str+std::min(LastConversionIdx+2, StrLen))
1188 << OrigFormatExpr->getSourceRange();
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001189 }
1190 ++numConversions;
1191 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001192
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001193 // Handle "%%"
1194 case '%':
1195 // Sanity check: Was the first "%" character the previous one?
1196 // If not, we will assume that we have a malformed format
1197 // conversion, and that the current "%" character is the start
1198 // of a new conversion.
1199 if (StrIdx - LastConversionIdx == 1)
Mike Stump1eb44332009-09-09 15:08:12 +00001200 CurrentState = state_OrdChr;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001201 else {
1202 // Issue a warning: invalid format conversion.
Chris Lattner60800082009-02-18 17:49:48 +00001203 SourceLocation Loc =
1204 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00001205
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001206 Diag(Loc, diag::warn_printf_invalid_conversion)
1207 << std::string(Str+LastConversionIdx, Str+StrIdx)
1208 << OrigFormatExpr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001209
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001210 // This conversion is broken. Advance to the next format
1211 // conversion.
1212 LastConversionIdx = StrIdx;
1213 ++numConversions;
Ted Kremenek71895b92007-08-14 17:39:48 +00001214 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001215 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001216
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001217 default:
1218 // This case catches all other characters: flags, widths, etc.
1219 // We should eventually process those as well.
1220 break;
Ted Kremenek71895b92007-08-14 17:39:48 +00001221 }
1222 }
1223
1224 if (CurrentState == state_Conversion) {
1225 // Issue a warning: invalid format conversion.
Chris Lattner60800082009-02-18 17:49:48 +00001226 SourceLocation Loc =
1227 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00001228
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001229 Diag(Loc, diag::warn_printf_invalid_conversion)
1230 << std::string(Str+LastConversionIdx,
1231 Str+std::min(LastConversionIdx+2, StrLen))
1232 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001233 return;
1234 }
Mike Stump1eb44332009-09-09 15:08:12 +00001235
Ted Kremenek71895b92007-08-14 17:39:48 +00001236 if (!HasVAListArg) {
1237 // CHECK: Does the number of format conversions exceed the number
1238 // of data arguments?
1239 if (numConversions > numDataArgs) {
Chris Lattner60800082009-02-18 17:49:48 +00001240 SourceLocation Loc =
1241 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00001242
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001243 Diag(Loc, diag::warn_printf_insufficient_data_args)
1244 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001245 }
1246 // CHECK: Does the number of data arguments exceed the number of
1247 // format conversions in the format string?
1248 else if (numConversions < numDataArgs)
Chris Lattner925e60d2007-12-28 05:29:59 +00001249 Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001250 diag::warn_printf_too_many_data_args)
1251 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001252 }
1253}
Ted Kremenek06de2762007-08-17 16:46:58 +00001254
1255//===--- CHECK: Return Address of Stack Variable --------------------------===//
1256
1257static DeclRefExpr* EvalVal(Expr *E);
1258static DeclRefExpr* EvalAddr(Expr* E);
1259
1260/// CheckReturnStackAddr - Check if a return statement returns the address
1261/// of a stack variable.
1262void
1263Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1264 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00001265
Ted Kremenek06de2762007-08-17 16:46:58 +00001266 // Perform checking for returned stack addresses.
Steve Naroffdd972f22008-09-05 22:11:13 +00001267 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Ted Kremenek06de2762007-08-17 16:46:58 +00001268 if (DeclRefExpr *DR = EvalAddr(RetValExp))
Chris Lattner3c73c412008-11-19 08:23:25 +00001269 Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
Chris Lattner08631c52008-11-23 21:45:46 +00001270 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001271
Steve Naroffc50a4a52008-09-16 22:25:10 +00001272 // Skip over implicit cast expressions when checking for block expressions.
Chris Lattner4ca606e2009-09-08 00:36:37 +00001273 RetValExp = RetValExp->IgnoreParenCasts();
Steve Naroffc50a4a52008-09-16 22:25:10 +00001274
Steve Naroff61f40a22008-09-10 19:17:48 +00001275 if (BlockExpr *C = dyn_cast_or_null<BlockExpr>(RetValExp))
Mike Stump397195b2009-04-17 00:09:41 +00001276 if (C->hasBlockDeclRefExprs())
1277 Diag(C->getLocStart(), diag::err_ret_local_block)
1278 << C->getSourceRange();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001279 } else if (lhsType->isReferenceType()) {
1280 // Perform checking for stack values returned by reference.
Douglas Gregor49badde2008-10-27 19:41:14 +00001281 // Check for a reference to the stack
1282 if (DeclRefExpr *DR = EvalVal(RetValExp))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001283 Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
Chris Lattner08631c52008-11-23 21:45:46 +00001284 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +00001285 }
1286}
1287
1288/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1289/// check if the expression in a return statement evaluates to an address
1290/// to a location on the stack. The recursion is used to traverse the
1291/// AST of the return expression, with recursion backtracking when we
1292/// encounter a subexpression that (1) clearly does not lead to the address
1293/// of a stack variable or (2) is something we cannot determine leads to
1294/// the address of a stack variable based on such local checking.
1295///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001296/// EvalAddr processes expressions that are pointers that are used as
1297/// references (and not L-values). EvalVal handles all other values.
Mike Stump1eb44332009-09-09 15:08:12 +00001298/// At the base case of the recursion is a check for a DeclRefExpr* in
Ted Kremenek06de2762007-08-17 16:46:58 +00001299/// the refers to a stack variable.
1300///
1301/// This implementation handles:
1302///
1303/// * pointer-to-pointer casts
1304/// * implicit conversions from array references to pointers
1305/// * taking the address of fields
1306/// * arbitrary interplay between "&" and "*" operators
1307/// * pointer arithmetic from an address of a stack variable
1308/// * taking the address of an array element where the array is on the stack
1309static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek06de2762007-08-17 16:46:58 +00001310 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00001311 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00001312 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001313 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001314 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00001315
Ted Kremenek06de2762007-08-17 16:46:58 +00001316 // Our "symbolic interpreter" is just a dispatch off the currently
1317 // viewed AST node. We then recursively traverse the AST by calling
1318 // EvalAddr and EvalVal appropriately.
1319 switch (E->getStmtClass()) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001320 case Stmt::ParenExprClass:
1321 // Ignore parentheses.
1322 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek06de2762007-08-17 16:46:58 +00001323
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001324 case Stmt::UnaryOperatorClass: {
1325 // The only unary operator that make sense to handle here
1326 // is AddrOf. All others don't make sense as pointers.
1327 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001328
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001329 if (U->getOpcode() == UnaryOperator::AddrOf)
1330 return EvalVal(U->getSubExpr());
1331 else
Ted Kremenek06de2762007-08-17 16:46:58 +00001332 return NULL;
1333 }
Mike Stump1eb44332009-09-09 15:08:12 +00001334
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001335 case Stmt::BinaryOperatorClass: {
1336 // Handle pointer arithmetic. All other binary operators are not valid
1337 // in this context.
1338 BinaryOperator *B = cast<BinaryOperator>(E);
1339 BinaryOperator::Opcode op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00001340
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001341 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
1342 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001343
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001344 Expr *Base = B->getLHS();
1345
1346 // Determine which argument is the real pointer base. It could be
1347 // the RHS argument instead of the LHS.
1348 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00001349
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001350 assert (Base->getType()->isPointerType());
1351 return EvalAddr(Base);
1352 }
Steve Naroff61f40a22008-09-10 19:17:48 +00001353
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001354 // For conditional operators we need to see if either the LHS or RHS are
1355 // valid DeclRefExpr*s. If one of them is valid, we return it.
1356 case Stmt::ConditionalOperatorClass: {
1357 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001358
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001359 // Handle the GNU extension for missing LHS.
1360 if (Expr *lhsExpr = C->getLHS())
1361 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
1362 return LHS;
1363
1364 return EvalAddr(C->getRHS());
1365 }
Mike Stump1eb44332009-09-09 15:08:12 +00001366
Ted Kremenek54b52742008-08-07 00:49:01 +00001367 // For casts, we need to handle conversions from arrays to
1368 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00001369 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001370 case Stmt::CStyleCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001371 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001372 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00001373 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001374
Steve Naroffdd972f22008-09-05 22:11:13 +00001375 if (SubExpr->getType()->isPointerType() ||
1376 SubExpr->getType()->isBlockPointerType() ||
1377 SubExpr->getType()->isObjCQualifiedIdType())
Ted Kremenek54b52742008-08-07 00:49:01 +00001378 return EvalAddr(SubExpr);
1379 else if (T->isArrayType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001380 return EvalVal(SubExpr);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001381 else
Ted Kremenek54b52742008-08-07 00:49:01 +00001382 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001383 }
Mike Stump1eb44332009-09-09 15:08:12 +00001384
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001385 // C++ casts. For dynamic casts, static casts, and const casts, we
1386 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00001387 // through the cast. In the case the dynamic cast doesn't fail (and
1388 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001389 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00001390 // FIXME: The comment about is wrong; we're not always converting
1391 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00001392 // handle references to objects.
1393 case Stmt::CXXStaticCastExprClass:
1394 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001395 case Stmt::CXXConstCastExprClass:
1396 case Stmt::CXXReinterpretCastExprClass: {
1397 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00001398 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001399 return EvalAddr(S);
1400 else
1401 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001402 }
Mike Stump1eb44332009-09-09 15:08:12 +00001403
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001404 // Everything else: we simply don't reason about them.
1405 default:
1406 return NULL;
1407 }
Ted Kremenek06de2762007-08-17 16:46:58 +00001408}
Mike Stump1eb44332009-09-09 15:08:12 +00001409
Ted Kremenek06de2762007-08-17 16:46:58 +00001410
1411/// EvalVal - This function is complements EvalAddr in the mutual recursion.
1412/// See the comments for EvalAddr for more details.
1413static DeclRefExpr* EvalVal(Expr *E) {
Mike Stump1eb44332009-09-09 15:08:12 +00001414
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001415 // We should only be called for evaluating non-pointer expressions, or
1416 // expressions with a pointer type that are not used as references but instead
1417 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00001418
Ted Kremenek06de2762007-08-17 16:46:58 +00001419 // Our "symbolic interpreter" is just a dispatch off the currently
1420 // viewed AST node. We then recursively traverse the AST by calling
1421 // EvalAddr and EvalVal appropriately.
1422 switch (E->getStmtClass()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001423 case Stmt::DeclRefExprClass:
Douglas Gregor1a49af92009-01-06 05:10:23 +00001424 case Stmt::QualifiedDeclRefExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00001425 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
1426 // at code that refers to a variable's name. We check if it has local
1427 // storage within the function, and if so, return the expression.
1428 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001429
Ted Kremenek06de2762007-08-17 16:46:58 +00001430 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Mike Stump1eb44332009-09-09 15:08:12 +00001431 if (V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
1432
Ted Kremenek06de2762007-08-17 16:46:58 +00001433 return NULL;
1434 }
Mike Stump1eb44332009-09-09 15:08:12 +00001435
Ted Kremenek06de2762007-08-17 16:46:58 +00001436 case Stmt::ParenExprClass:
1437 // Ignore parentheses.
1438 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
Mike Stump1eb44332009-09-09 15:08:12 +00001439
Ted Kremenek06de2762007-08-17 16:46:58 +00001440 case Stmt::UnaryOperatorClass: {
1441 // The only unary operator that make sense to handle here
1442 // is Deref. All others don't resolve to a "name." This includes
1443 // handling all sorts of rvalues passed to a unary operator.
1444 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001445
Ted Kremenek06de2762007-08-17 16:46:58 +00001446 if (U->getOpcode() == UnaryOperator::Deref)
1447 return EvalAddr(U->getSubExpr());
1448
1449 return NULL;
1450 }
Mike Stump1eb44332009-09-09 15:08:12 +00001451
Ted Kremenek06de2762007-08-17 16:46:58 +00001452 case Stmt::ArraySubscriptExprClass: {
1453 // Array subscripts are potential references to data on the stack. We
1454 // retrieve the DeclRefExpr* for the array variable if it indeed
1455 // has local storage.
Ted Kremenek23245122007-08-20 16:18:38 +00001456 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek06de2762007-08-17 16:46:58 +00001457 }
Mike Stump1eb44332009-09-09 15:08:12 +00001458
Ted Kremenek06de2762007-08-17 16:46:58 +00001459 case Stmt::ConditionalOperatorClass: {
1460 // For conditional operators we need to see if either the LHS or RHS are
1461 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
1462 ConditionalOperator *C = cast<ConditionalOperator>(E);
1463
Anders Carlsson39073232007-11-30 19:04:31 +00001464 // Handle the GNU extension for missing LHS.
1465 if (Expr *lhsExpr = C->getLHS())
1466 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
1467 return LHS;
1468
1469 return EvalVal(C->getRHS());
Ted Kremenek06de2762007-08-17 16:46:58 +00001470 }
Mike Stump1eb44332009-09-09 15:08:12 +00001471
Ted Kremenek06de2762007-08-17 16:46:58 +00001472 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00001473 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00001474 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001475
Ted Kremenek06de2762007-08-17 16:46:58 +00001476 // Check for indirect access. We only want direct field accesses.
1477 if (!M->isArrow())
1478 return EvalVal(M->getBase());
1479 else
1480 return NULL;
1481 }
Mike Stump1eb44332009-09-09 15:08:12 +00001482
Ted Kremenek06de2762007-08-17 16:46:58 +00001483 // Everything else: we simply don't reason about them.
1484 default:
1485 return NULL;
1486 }
1487}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001488
1489//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
1490
1491/// Check for comparisons of floating point operands using != and ==.
1492/// Issue a warning if these are no self-comparisons, as they are not likely
1493/// to do what the programmer intended.
1494void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
1495 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001496
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00001497 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek32e97b62008-01-17 17:55:13 +00001498 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001499
1500 // Special case: check for x == x (which is OK).
1501 // Do not emit warnings for such cases.
1502 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
1503 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
1504 if (DRL->getDecl() == DRR->getDecl())
1505 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001506
1507
Ted Kremenek1b500bb2007-11-29 00:59:04 +00001508 // Special case: check for comparisons against literals that can be exactly
1509 // represented by APFloat. In such cases, do not emit a warning. This
1510 // is a heuristic: often comparison against such literals are used to
1511 // detect if a value in a variable has not changed. This clearly can
1512 // lead to false negatives.
1513 if (EmitWarning) {
1514 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
1515 if (FLL->isExact())
1516 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001517 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00001518 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
1519 if (FLR->isExact())
1520 EmitWarning = false;
1521 }
1522 }
Mike Stump1eb44332009-09-09 15:08:12 +00001523
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001524 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001525 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001526 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001527 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001528 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001529
Sebastian Redl0eb23302009-01-19 00:08:26 +00001530 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001531 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001532 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001533 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001534
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001535 // Emit the diagnostic.
1536 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001537 Diag(loc, diag::warn_floatingpoint_eq)
1538 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001539}