blob: 4812a64093286b8cbea7c81137256d9017381d91 [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;
Sebastian Redl4a2614e2009-11-17 18:02:24 +000094 // Does the index refer to the implicit object argument?
95 if (isa<CXXMemberCallExpr>(TheCall)) {
96 if (format_idx == 0)
97 return false;
98 --format_idx;
99 }
Ryan Flynn4403a5e2009-08-06 03:00:50 +0000100 if (format_idx < TheCall->getNumArgs()) {
101 Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts();
Douglas Gregorce940492009-09-25 04:25:58 +0000102 if (!Format->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
Ryan Flynn4403a5e2009-08-06 03:00:50 +0000103 return true;
104 }
105 }
106 return false;
107}
Chris Lattner60800082009-02-18 17:49:48 +0000108
Sebastian Redl0eb23302009-01-19 00:08:26 +0000109Action::OwningExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +0000110Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Sebastian Redl0eb23302009-01-19 00:08:26 +0000111 OwningExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +0000112
Anders Carlssond406bf02009-08-16 01:56:34 +0000113 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000114 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000115 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000116 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000117 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000118 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000119 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000120 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000121 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000122 if (SemaBuiltinVAStart(TheCall))
123 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000124 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000125 case Builtin::BI__builtin_isgreater:
126 case Builtin::BI__builtin_isgreaterequal:
127 case Builtin::BI__builtin_isless:
128 case Builtin::BI__builtin_islessequal:
129 case Builtin::BI__builtin_islessgreater:
130 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000131 if (SemaBuiltinUnorderedCompare(TheCall))
132 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000133 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000134 case Builtin::BI__builtin_isfinite:
135 case Builtin::BI__builtin_isinf:
136 case Builtin::BI__builtin_isinf_sign:
137 case Builtin::BI__builtin_isnan:
138 case Builtin::BI__builtin_isnormal:
139 if (SemaBuiltinUnaryFP(TheCall))
140 return ExprError();
141 break;
Eli Friedman6cfda232008-05-20 08:23:37 +0000142 case Builtin::BI__builtin_return_address:
143 case Builtin::BI__builtin_frame_address:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000144 if (SemaBuiltinStackAddress(TheCall))
145 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000146 break;
Chris Lattner21fb98e2009-09-23 06:06:36 +0000147 case Builtin::BI__builtin_eh_return_data_regno:
148 if (SemaBuiltinEHReturnDataRegNo(TheCall))
149 return ExprError();
150 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000151 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000152 return SemaBuiltinShuffleVector(TheCall);
153 // TheCall will be freed by the smart pointer here, but that's fine, since
154 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000155 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000156 if (SemaBuiltinPrefetch(TheCall))
157 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000158 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000159 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000160 if (SemaBuiltinObjectSize(TheCall))
161 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000162 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000163 case Builtin::BI__builtin_longjmp:
164 if (SemaBuiltinLongjmp(TheCall))
165 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000166 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000167 case Builtin::BI__sync_fetch_and_add:
168 case Builtin::BI__sync_fetch_and_sub:
169 case Builtin::BI__sync_fetch_and_or:
170 case Builtin::BI__sync_fetch_and_and:
171 case Builtin::BI__sync_fetch_and_xor:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000172 case Builtin::BI__sync_fetch_and_nand:
Chris Lattner5caa3702009-05-08 06:58:22 +0000173 case Builtin::BI__sync_add_and_fetch:
174 case Builtin::BI__sync_sub_and_fetch:
175 case Builtin::BI__sync_and_and_fetch:
176 case Builtin::BI__sync_or_and_fetch:
177 case Builtin::BI__sync_xor_and_fetch:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000178 case Builtin::BI__sync_nand_and_fetch:
Chris Lattner5caa3702009-05-08 06:58:22 +0000179 case Builtin::BI__sync_val_compare_and_swap:
180 case Builtin::BI__sync_bool_compare_and_swap:
181 case Builtin::BI__sync_lock_test_and_set:
182 case Builtin::BI__sync_lock_release:
183 if (SemaBuiltinAtomicOverloaded(TheCall))
184 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000185 break;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000186 }
Mike Stump1eb44332009-09-09 15:08:12 +0000187
Anders Carlssond406bf02009-08-16 01:56:34 +0000188 return move(TheCallResult);
189}
Daniel Dunbarde454282008-10-02 18:44:07 +0000190
Anders Carlssond406bf02009-08-16 01:56:34 +0000191/// CheckFunctionCall - Check a direct function call for various correctness
192/// and safety properties not strictly enforced by the C type system.
193bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
194 // Get the IdentifierInfo* for the called function.
195 IdentifierInfo *FnInfo = FDecl->getIdentifier();
196
197 // None of the checks below are needed for functions that don't have
198 // simple names (e.g., C++ conversion functions).
199 if (!FnInfo)
200 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000201
Daniel Dunbarde454282008-10-02 18:44:07 +0000202 // FIXME: This mechanism should be abstracted to be less fragile and
203 // more efficient. For example, just map function ids to custom
204 // handlers.
205
Chris Lattner59907c42007-08-10 20:18:51 +0000206 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000207 if (const FormatAttr *Format = FDecl->getAttr<FormatAttr>()) {
Ryan Flynn4403a5e2009-08-06 03:00:50 +0000208 if (CheckablePrintfAttr(Format, TheCall)) {
Ted Kremenek3d692df2009-02-27 17:58:43 +0000209 bool HasVAListArg = Format->getFirstArg() == 0;
210 if (!HasVAListArg) {
Mike Stump1eb44332009-09-09 15:08:12 +0000211 if (const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +0000212 = FDecl->getType()->getAs<FunctionProtoType>())
Sebastian Redl4a2614e2009-11-17 18:02:24 +0000213 HasVAListArg = !Proto->isVariadic();
Ted Kremenek3d692df2009-02-27 17:58:43 +0000214 }
Douglas Gregor3c385e52009-02-14 18:57:46 +0000215 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
Ted Kremenek3d692df2009-02-27 17:58:43 +0000216 HasVAListArg ? 0 : Format->getFirstArg() - 1);
Douglas Gregor3c385e52009-02-14 18:57:46 +0000217 }
Chris Lattner59907c42007-08-10 20:18:51 +0000218 }
Mike Stump1eb44332009-09-09 15:08:12 +0000219
220 for (const NonNullAttr *NonNull = FDecl->getAttr<NonNullAttr>(); NonNull;
Anders Carlssond406bf02009-08-16 01:56:34 +0000221 NonNull = NonNull->getNext<NonNullAttr>())
222 CheckNonNullArguments(NonNull, TheCall);
Sebastian Redl0eb23302009-01-19 00:08:26 +0000223
Anders Carlssond406bf02009-08-16 01:56:34 +0000224 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000225}
226
Anders Carlssond406bf02009-08-16 01:56:34 +0000227bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000228 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000229 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000230 if (!Format)
Anders Carlssond406bf02009-08-16 01:56:34 +0000231 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000232
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000233 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
234 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000235 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000236
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000237 QualType Ty = V->getType();
238 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000239 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000240
Anders Carlssond406bf02009-08-16 01:56:34 +0000241 if (!CheckablePrintfAttr(Format, TheCall))
242 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000243
Anders Carlssond406bf02009-08-16 01:56:34 +0000244 bool HasVAListArg = Format->getFirstArg() == 0;
245 if (!HasVAListArg) {
Mike Stump1eb44332009-09-09 15:08:12 +0000246 const FunctionType *FT =
John McCall183700f2009-09-21 23:43:11 +0000247 Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Anders Carlssond406bf02009-08-16 01:56:34 +0000248 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
249 HasVAListArg = !Proto->isVariadic();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000250 }
Anders Carlssond406bf02009-08-16 01:56:34 +0000251 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
252 HasVAListArg ? 0 : Format->getFirstArg() - 1);
253
254 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000255}
256
Chris Lattner5caa3702009-05-08 06:58:22 +0000257/// SemaBuiltinAtomicOverloaded - We have a call to a function like
258/// __sync_fetch_and_add, which is an overloaded function based on the pointer
259/// type of its first argument. The main ActOnCallExpr routines have already
260/// promoted the types of arguments because all of these calls are prototyped as
261/// void(...).
262///
263/// This function goes through and does final semantic checking for these
264/// builtins,
265bool Sema::SemaBuiltinAtomicOverloaded(CallExpr *TheCall) {
266 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
267 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
268
269 // Ensure that we have at least one argument to do type inference from.
270 if (TheCall->getNumArgs() < 1)
271 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
272 << 0 << TheCall->getCallee()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000273
Chris Lattner5caa3702009-05-08 06:58:22 +0000274 // Inspect the first argument of the atomic builtin. This should always be
275 // a pointer type, whose element is an integral scalar or pointer type.
276 // Because it is a pointer type, we don't have to worry about any implicit
277 // casts here.
278 Expr *FirstArg = TheCall->getArg(0);
279 if (!FirstArg->getType()->isPointerType())
280 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
281 << FirstArg->getType() << FirstArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000282
Ted Kremenek6217b802009-07-29 21:53:49 +0000283 QualType ValType = FirstArg->getType()->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000284 if (!ValType->isIntegerType() && !ValType->isPointerType() &&
Chris Lattner5caa3702009-05-08 06:58:22 +0000285 !ValType->isBlockPointerType())
286 return Diag(DRE->getLocStart(),
287 diag::err_atomic_builtin_must_be_pointer_intptr)
288 << FirstArg->getType() << FirstArg->getSourceRange();
289
290 // We need to figure out which concrete builtin this maps onto. For example,
291 // __sync_fetch_and_add with a 2 byte object turns into
292 // __sync_fetch_and_add_2.
293#define BUILTIN_ROW(x) \
294 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
295 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000296
Chris Lattner5caa3702009-05-08 06:58:22 +0000297 static const unsigned BuiltinIndices[][5] = {
298 BUILTIN_ROW(__sync_fetch_and_add),
299 BUILTIN_ROW(__sync_fetch_and_sub),
300 BUILTIN_ROW(__sync_fetch_and_or),
301 BUILTIN_ROW(__sync_fetch_and_and),
302 BUILTIN_ROW(__sync_fetch_and_xor),
Chris Lattnereebd9d22009-05-13 04:37:52 +0000303 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump1eb44332009-09-09 15:08:12 +0000304
Chris Lattner5caa3702009-05-08 06:58:22 +0000305 BUILTIN_ROW(__sync_add_and_fetch),
306 BUILTIN_ROW(__sync_sub_and_fetch),
307 BUILTIN_ROW(__sync_and_and_fetch),
308 BUILTIN_ROW(__sync_or_and_fetch),
309 BUILTIN_ROW(__sync_xor_and_fetch),
Chris Lattnereebd9d22009-05-13 04:37:52 +0000310 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000311
Chris Lattner5caa3702009-05-08 06:58:22 +0000312 BUILTIN_ROW(__sync_val_compare_and_swap),
313 BUILTIN_ROW(__sync_bool_compare_and_swap),
314 BUILTIN_ROW(__sync_lock_test_and_set),
315 BUILTIN_ROW(__sync_lock_release)
316 };
Mike Stump1eb44332009-09-09 15:08:12 +0000317#undef BUILTIN_ROW
318
Chris Lattner5caa3702009-05-08 06:58:22 +0000319 // Determine the index of the size.
320 unsigned SizeIndex;
321 switch (Context.getTypeSize(ValType)/8) {
322 case 1: SizeIndex = 0; break;
323 case 2: SizeIndex = 1; break;
324 case 4: SizeIndex = 2; break;
325 case 8: SizeIndex = 3; break;
326 case 16: SizeIndex = 4; break;
327 default:
328 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
329 << FirstArg->getType() << FirstArg->getSourceRange();
330 }
Mike Stump1eb44332009-09-09 15:08:12 +0000331
Chris Lattner5caa3702009-05-08 06:58:22 +0000332 // Each of these builtins has one pointer argument, followed by some number of
333 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
334 // that we ignore. Find out which row of BuiltinIndices to read from as well
335 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000336 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000337 unsigned BuiltinIndex, NumFixed = 1;
338 switch (BuiltinID) {
339 default: assert(0 && "Unknown overloaded atomic builtin!");
340 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
341 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
342 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
343 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
344 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Chris Lattnereebd9d22009-05-13 04:37:52 +0000345 case Builtin::BI__sync_fetch_and_nand:BuiltinIndex = 5; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000346
Chris Lattnereebd9d22009-05-13 04:37:52 +0000347 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 6; break;
348 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 7; break;
349 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 8; break;
350 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 9; break;
351 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex =10; break;
352 case Builtin::BI__sync_nand_and_fetch:BuiltinIndex =11; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000353
Chris Lattner5caa3702009-05-08 06:58:22 +0000354 case Builtin::BI__sync_val_compare_and_swap:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000355 BuiltinIndex = 12;
Chris Lattner5caa3702009-05-08 06:58:22 +0000356 NumFixed = 2;
357 break;
358 case Builtin::BI__sync_bool_compare_and_swap:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000359 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000360 NumFixed = 2;
361 break;
Chris Lattnereebd9d22009-05-13 04:37:52 +0000362 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 14; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000363 case Builtin::BI__sync_lock_release:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000364 BuiltinIndex = 15;
Chris Lattner5caa3702009-05-08 06:58:22 +0000365 NumFixed = 0;
366 break;
367 }
Mike Stump1eb44332009-09-09 15:08:12 +0000368
Chris Lattner5caa3702009-05-08 06:58:22 +0000369 // Now that we know how many fixed arguments we expect, first check that we
370 // have at least that many.
371 if (TheCall->getNumArgs() < 1+NumFixed)
372 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
373 << 0 << TheCall->getCallee()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000374
375
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000376 // Get the decl for the concrete builtin from this, we can tell what the
377 // concrete integer type we should convert to is.
378 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
379 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
380 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +0000381 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000382 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
383 TUScope, false, DRE->getLocStart()));
384 const FunctionProtoType *BuiltinFT =
John McCall183700f2009-09-21 23:43:11 +0000385 NewBuiltinDecl->getType()->getAs<FunctionProtoType>();
Ted Kremenek6217b802009-07-29 21:53:49 +0000386 ValType = BuiltinFT->getArgType(0)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000387
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000388 // If the first type needs to be converted (e.g. void** -> int*), do it now.
389 if (BuiltinFT->getArgType(0) != FirstArg->getType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +0000390 ImpCastExprToType(FirstArg, BuiltinFT->getArgType(0), CastExpr::CK_BitCast);
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000391 TheCall->setArg(0, FirstArg);
392 }
Mike Stump1eb44332009-09-09 15:08:12 +0000393
Chris Lattner5caa3702009-05-08 06:58:22 +0000394 // Next, walk the valid ones promoting to the right type.
395 for (unsigned i = 0; i != NumFixed; ++i) {
396 Expr *Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +0000397
Chris Lattner5caa3702009-05-08 06:58:22 +0000398 // If the argument is an implicit cast, then there was a promotion due to
399 // "...", just remove it now.
400 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
401 Arg = ICE->getSubExpr();
402 ICE->setSubExpr(0);
403 ICE->Destroy(Context);
404 TheCall->setArg(i+1, Arg);
405 }
Mike Stump1eb44332009-09-09 15:08:12 +0000406
Chris Lattner5caa3702009-05-08 06:58:22 +0000407 // GCC does an implicit conversion to the pointer or integer ValType. This
408 // can fail in some cases (1i -> int**), check for this error case now.
Anders Carlssoncdb61972009-08-07 22:21:05 +0000409 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000410 CXXMethodDecl *ConversionDecl = 0;
411 if (CheckCastTypes(Arg->getSourceRange(), ValType, Arg, Kind,
412 ConversionDecl))
Chris Lattner5caa3702009-05-08 06:58:22 +0000413 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000414
Chris Lattner5caa3702009-05-08 06:58:22 +0000415 // Okay, we have something that *can* be converted to the right type. Check
416 // to see if there is a potentially weird extension going on here. This can
417 // happen when you do an atomic operation on something like an char* and
418 // pass in 42. The 42 gets converted to char. This is even more strange
419 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +0000420 // FIXME: Do this check.
Anders Carlssoncdb61972009-08-07 22:21:05 +0000421 ImpCastExprToType(Arg, ValType, Kind, /*isLvalue=*/false);
Chris Lattner5caa3702009-05-08 06:58:22 +0000422 TheCall->setArg(i+1, Arg);
423 }
Mike Stump1eb44332009-09-09 15:08:12 +0000424
Chris Lattner5caa3702009-05-08 06:58:22 +0000425 // Switch the DeclRefExpr to refer to the new decl.
426 DRE->setDecl(NewBuiltinDecl);
427 DRE->setType(NewBuiltinDecl->getType());
Mike Stump1eb44332009-09-09 15:08:12 +0000428
Chris Lattner5caa3702009-05-08 06:58:22 +0000429 // Set the callee in the CallExpr.
430 // FIXME: This leaks the original parens and implicit casts.
431 Expr *PromotedCall = DRE;
432 UsualUnaryConversions(PromotedCall);
433 TheCall->setCallee(PromotedCall);
Mike Stump1eb44332009-09-09 15:08:12 +0000434
Chris Lattner5caa3702009-05-08 06:58:22 +0000435
436 // Change the result type of the call to match the result type of the decl.
437 TheCall->setType(NewBuiltinDecl->getResultType());
438 return false;
439}
440
441
Chris Lattner69039812009-02-18 06:01:06 +0000442/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000443/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +0000444/// FIXME: GCC currently emits the following warning:
Mike Stump1eb44332009-09-09 15:08:12 +0000445/// "warning: input conversion stopped due to an input byte that does not
Steve Narofffd942622009-04-13 20:26:29 +0000446/// belong to the input codeset UTF-8"
447/// Note: It might also make sense to do the UTF-16 conversion here (would
448/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +0000449bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000450 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000451 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
452
453 if (!Literal || Literal->isWide()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000454 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
455 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000456 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000457 }
Mike Stump1eb44332009-09-09 15:08:12 +0000458
Daniel Dunbarf015b032009-09-22 10:03:52 +0000459 const char *Data = Literal->getStrData();
460 unsigned Length = Literal->getByteLength();
Mike Stump1eb44332009-09-09 15:08:12 +0000461
Daniel Dunbarf015b032009-09-22 10:03:52 +0000462 for (unsigned i = 0; i < Length; ++i) {
463 if (!Data[i]) {
464 Diag(getLocationOfStringLiteralByte(Literal, i),
465 diag::warn_cfstring_literal_contains_nul_character)
466 << Arg->getSourceRange();
467 break;
468 }
469 }
Mike Stump1eb44332009-09-09 15:08:12 +0000470
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000471 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000472}
473
Chris Lattnerc27c6652007-12-20 00:05:45 +0000474/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
475/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000476bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
477 Expr *Fn = TheCall->getCallee();
478 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000479 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000480 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000481 << 0 /*function call*/ << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +0000482 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000483 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000484 return true;
485 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000486
487 if (TheCall->getNumArgs() < 2) {
488 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
489 << 0 /*function call*/;
490 }
491
Chris Lattnerc27c6652007-12-20 00:05:45 +0000492 // Determine whether the current function is variadic or not.
493 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000494 if (CurBlock)
495 isVariadic = CurBlock->isVariadic;
496 else if (getCurFunctionDecl()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000497 if (FunctionProtoType* FTP =
498 dyn_cast<FunctionProtoType>(getCurFunctionDecl()->getType()))
Eli Friedman56f20ae2008-12-15 22:05:35 +0000499 isVariadic = FTP->isVariadic();
500 else
501 isVariadic = false;
502 } else {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000503 isVariadic = getCurMethodDecl()->isVariadic();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000504 }
Mike Stump1eb44332009-09-09 15:08:12 +0000505
Chris Lattnerc27c6652007-12-20 00:05:45 +0000506 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000507 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
508 return true;
509 }
Mike Stump1eb44332009-09-09 15:08:12 +0000510
Chris Lattner30ce3442007-12-19 23:59:04 +0000511 // Verify that the second argument to the builtin is the last argument of the
512 // current function or method.
513 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000514 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +0000515
Anders Carlsson88cf2262008-02-11 04:20:54 +0000516 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
517 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000518 // FIXME: This isn't correct for methods (results in bogus warning).
519 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000520 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000521 if (CurBlock)
522 LastArg = *(CurBlock->TheDecl->param_end()-1);
523 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +0000524 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000525 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000526 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000527 SecondArgIsLastNamedArgument = PV == LastArg;
528 }
529 }
Mike Stump1eb44332009-09-09 15:08:12 +0000530
Chris Lattner30ce3442007-12-19 23:59:04 +0000531 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +0000532 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000533 diag::warn_second_parameter_of_va_start_not_last_named_argument);
534 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000535}
Chris Lattner30ce3442007-12-19 23:59:04 +0000536
Chris Lattner1b9a0792007-12-20 00:26:33 +0000537/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
538/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000539bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
540 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000541 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
542 << 0 /*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000543 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +0000544 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000545 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000546 << 0 /*function call*/
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000547 << SourceRange(TheCall->getArg(2)->getLocStart(),
548 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000549
Chris Lattner925e60d2007-12-28 05:29:59 +0000550 Expr *OrigArg0 = TheCall->getArg(0);
551 Expr *OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000552
Chris Lattner1b9a0792007-12-20 00:26:33 +0000553 // Do standard promotions between the two arguments, returning their common
554 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000555 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Daniel Dunbar403bc2b2009-02-19 19:28:43 +0000556
557 // Make sure any conversions are pushed back into the call; this is
558 // type safe since unordered compare builtins are declared as "_Bool
559 // foo(...)".
560 TheCall->setArg(0, OrigArg0);
561 TheCall->setArg(1, OrigArg1);
Mike Stump1eb44332009-09-09 15:08:12 +0000562
Douglas Gregorcde01732009-05-19 22:10:17 +0000563 if (OrigArg0->isTypeDependent() || OrigArg1->isTypeDependent())
564 return false;
565
Chris Lattner1b9a0792007-12-20 00:26:33 +0000566 // If the common type isn't a real floating type, then the arguments were
567 // invalid for this operation.
568 if (!Res->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000569 return Diag(OrigArg0->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000570 diag::err_typecheck_call_invalid_ordered_compare)
Chris Lattnerd1625842008-11-24 06:25:27 +0000571 << OrigArg0->getType() << OrigArg1->getType()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000572 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000573
Chris Lattner1b9a0792007-12-20 00:26:33 +0000574 return false;
575}
576
Eli Friedman9ac6f622009-08-31 20:06:00 +0000577/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isnan and
578/// friends. This is declared to take (...), so we have to check everything.
579bool Sema::SemaBuiltinUnaryFP(CallExpr *TheCall) {
580 if (TheCall->getNumArgs() < 1)
581 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
582 << 0 /*function call*/;
583 if (TheCall->getNumArgs() > 1)
Mike Stump1eb44332009-09-09 15:08:12 +0000584 return Diag(TheCall->getArg(1)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000585 diag::err_typecheck_call_too_many_args)
586 << 0 /*function call*/
587 << SourceRange(TheCall->getArg(1)->getLocStart(),
588 (*(TheCall->arg_end()-1))->getLocEnd());
589
590 Expr *OrigArg = TheCall->getArg(0);
Mike Stump1eb44332009-09-09 15:08:12 +0000591
Eli Friedman9ac6f622009-08-31 20:06:00 +0000592 if (OrigArg->isTypeDependent())
593 return false;
594
595 // This operation requires a floating-point number
596 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000597 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000598 diag::err_typecheck_call_invalid_unary_fp)
599 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000600
Eli Friedman9ac6f622009-08-31 20:06:00 +0000601 return false;
602}
603
Eli Friedman6cfda232008-05-20 08:23:37 +0000604bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) {
605 // The signature for these builtins is exact; the only thing we need
606 // to check is that the argument is a constant.
607 SourceLocation Loc;
Douglas Gregorcde01732009-05-19 22:10:17 +0000608 if (!TheCall->getArg(0)->isTypeDependent() &&
609 !TheCall->getArg(0)->isValueDependent() &&
610 !TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc))
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000611 return Diag(Loc, diag::err_stack_const_level) << TheCall->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000612
Eli Friedman6cfda232008-05-20 08:23:37 +0000613 return false;
614}
615
Eli Friedmand38617c2008-05-14 19:38:39 +0000616/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
617// This is declared to take (...), so we have to check everything.
Sebastian Redl0eb23302009-01-19 00:08:26 +0000618Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000619 if (TheCall->getNumArgs() < 3)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000620 return ExprError(Diag(TheCall->getLocEnd(),
621 diag::err_typecheck_call_too_few_args)
622 << 0 /*function call*/ << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000623
Douglas Gregorcde01732009-05-19 22:10:17 +0000624 unsigned numElements = std::numeric_limits<unsigned>::max();
625 if (!TheCall->getArg(0)->isTypeDependent() &&
626 !TheCall->getArg(1)->isTypeDependent()) {
627 QualType FAType = TheCall->getArg(0)->getType();
628 QualType SAType = TheCall->getArg(1)->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000629
Douglas Gregorcde01732009-05-19 22:10:17 +0000630 if (!FAType->isVectorType() || !SAType->isVectorType()) {
631 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000632 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000633 TheCall->getArg(1)->getLocEnd());
634 return ExprError();
635 }
Mike Stump1eb44332009-09-09 15:08:12 +0000636
Douglas Gregora4923eb2009-11-16 21:35:15 +0000637 if (!Context.hasSameUnqualifiedType(FAType, SAType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000638 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000639 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000640 TheCall->getArg(1)->getLocEnd());
641 return ExprError();
642 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000643
John McCall183700f2009-09-21 23:43:11 +0000644 numElements = FAType->getAs<VectorType>()->getNumElements();
Douglas Gregorcde01732009-05-19 22:10:17 +0000645 if (TheCall->getNumArgs() != numElements+2) {
646 if (TheCall->getNumArgs() < numElements+2)
647 return ExprError(Diag(TheCall->getLocEnd(),
648 diag::err_typecheck_call_too_few_args)
649 << 0 /*function call*/ << TheCall->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000650 return ExprError(Diag(TheCall->getLocEnd(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000651 diag::err_typecheck_call_too_many_args)
652 << 0 /*function call*/ << TheCall->getSourceRange());
653 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000654 }
655
656 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000657 if (TheCall->getArg(i)->isTypeDependent() ||
658 TheCall->getArg(i)->isValueDependent())
659 continue;
660
Eli Friedmand38617c2008-05-14 19:38:39 +0000661 llvm::APSInt Result(32);
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000662 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000663 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000664 diag::err_shufflevector_nonconstant_argument)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000665 << TheCall->getArg(i)->getSourceRange());
666
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000667 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000668 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000669 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000670 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000671 }
672
673 llvm::SmallVector<Expr*, 32> exprs;
674
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000675 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000676 exprs.push_back(TheCall->getArg(i));
677 TheCall->setArg(i, 0);
678 }
679
Nate Begemana88dc302009-08-12 02:10:25 +0000680 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
681 exprs.size(), exprs[0]->getType(),
Ted Kremenek8189cde2009-02-07 01:47:29 +0000682 TheCall->getCallee()->getLocStart(),
683 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000684}
Chris Lattner30ce3442007-12-19 23:59:04 +0000685
Daniel Dunbar4493f792008-07-21 22:59:13 +0000686/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
687// This is declared to take (const void*, ...) and can take two
688// optional constant int args.
689bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000690 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000691
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000692 if (NumArgs > 3)
693 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000694 << 0 /*function call*/ << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000695
696 // Argument 0 is checked for us and the remaining arguments must be
697 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000698 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000699 Expr *Arg = TheCall->getArg(i);
Douglas Gregorcde01732009-05-19 22:10:17 +0000700 if (Arg->isTypeDependent())
701 continue;
702
Eli Friedman9aef7262009-12-04 00:30:06 +0000703 if (!Arg->getType()->isIntegralType())
704 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_arg_type)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000705 << Arg->getSourceRange();
Douglas Gregorcde01732009-05-19 22:10:17 +0000706
Eli Friedman9aef7262009-12-04 00:30:06 +0000707 ImpCastExprToType(Arg, Context.IntTy, CastExpr::CK_IntegralCast);
708 TheCall->setArg(i, Arg);
709
Douglas Gregorcde01732009-05-19 22:10:17 +0000710 if (Arg->isValueDependent())
711 continue;
712
Eli Friedman9aef7262009-12-04 00:30:06 +0000713 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +0000714 if (!Arg->isIntegerConstantExpr(Result, Context))
Eli Friedman9aef7262009-12-04 00:30:06 +0000715 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_arg_ice)
Douglas Gregorcde01732009-05-19 22:10:17 +0000716 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000717
Daniel Dunbar4493f792008-07-21 22:59:13 +0000718 // FIXME: gcc issues a warning and rewrites these to 0. These
719 // seems especially odd for the third argument since the default
720 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000721 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +0000722 if (Result.getLimitedValue() > 1)
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" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000725 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +0000726 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000727 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000728 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000729 }
730 }
731
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000732 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000733}
734
Chris Lattner21fb98e2009-09-23 06:06:36 +0000735/// SemaBuiltinEHReturnDataRegNo - Handle __builtin_eh_return_data_regno, the
736/// operand must be an integer constant.
737bool Sema::SemaBuiltinEHReturnDataRegNo(CallExpr *TheCall) {
738 llvm::APSInt Result;
739 if (!TheCall->getArg(0)->isIntegerConstantExpr(Result, Context))
740 return Diag(TheCall->getLocStart(), diag::err_expr_not_ice)
741 << TheCall->getArg(0)->getSourceRange();
742
743 return false;
744}
745
746
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000747/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
748/// int type). This simply type checks that type is one of the defined
749/// constants (0-3).
Eric Christopherfee667f2009-12-23 03:49:37 +0000750// For compatability check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000751bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
752 Expr *Arg = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000753 if (Arg->isTypeDependent())
754 return false;
755
Mike Stump1eb44332009-09-09 15:08:12 +0000756 QualType ArgType = Arg->getType();
John McCall183700f2009-09-21 23:43:11 +0000757 const BuiltinType *BT = ArgType->getAs<BuiltinType>();
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000758 llvm::APSInt Result(32);
Douglas Gregorcde01732009-05-19 22:10:17 +0000759 if (!BT || BT->getKind() != BuiltinType::Int)
760 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
761 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
762
763 if (Arg->isValueDependent())
764 return false;
765
766 if (!Arg->isIntegerConstantExpr(Result, Context)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000767 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
768 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000769 }
770
771 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000772 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
773 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000774 }
775
776 return false;
777}
778
Eli Friedman586d6a82009-05-03 06:04:26 +0000779/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +0000780/// This checks that val is a constant 1.
781bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
782 Expr *Arg = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000783 if (Arg->isTypeDependent() || Arg->isValueDependent())
784 return false;
785
Eli Friedmand875fed2009-05-03 04:46:36 +0000786 llvm::APSInt Result(32);
787 if (!Arg->isIntegerConstantExpr(Result, Context) || Result != 1)
788 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
789 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
790
791 return false;
792}
793
Ted Kremenekd30ef872009-01-12 23:09:09 +0000794// Handle i > 1 ? "x" : "y", recursivelly
Ted Kremenek082d9362009-03-20 21:35:28 +0000795bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
796 bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000797 unsigned format_idx, unsigned firstDataArg) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000798 if (E->isTypeDependent() || E->isValueDependent())
799 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000800
801 switch (E->getStmtClass()) {
802 case Stmt::ConditionalOperatorClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000803 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Chris Lattner813b70d2009-12-22 06:00:13 +0000804 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000805 HasVAListArg, format_idx, firstDataArg)
Ted Kremenekd30ef872009-01-12 23:09:09 +0000806 && SemaCheckStringLiteral(C->getRHS(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000807 HasVAListArg, format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000808 }
809
810 case Stmt::ImplicitCastExprClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000811 const ImplicitCastExpr *Expr = cast<ImplicitCastExpr>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000812 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000813 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000814 }
815
816 case Stmt::ParenExprClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000817 const ParenExpr *Expr = cast<ParenExpr>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000818 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000819 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000820 }
Mike Stump1eb44332009-09-09 15:08:12 +0000821
Ted Kremenek082d9362009-03-20 21:35:28 +0000822 case Stmt::DeclRefExprClass: {
823 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000824
Ted Kremenek082d9362009-03-20 21:35:28 +0000825 // As an exception, do not flag errors for variables binding to
826 // const string literals.
827 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
828 bool isConstant = false;
829 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +0000830
Ted Kremenek082d9362009-03-20 21:35:28 +0000831 if (const ArrayType *AT = Context.getAsArrayType(T)) {
832 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000833 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000834 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +0000835 PT->getPointeeType().isConstant(Context);
836 }
Mike Stump1eb44332009-09-09 15:08:12 +0000837
Ted Kremenek082d9362009-03-20 21:35:28 +0000838 if (isConstant) {
839 const VarDecl *Def = 0;
840 if (const Expr *Init = VD->getDefinition(Def))
841 return SemaCheckStringLiteral(Init, TheCall,
842 HasVAListArg, format_idx, firstDataArg);
843 }
Mike Stump1eb44332009-09-09 15:08:12 +0000844
Anders Carlssond966a552009-06-28 19:55:58 +0000845 // For vprintf* functions (i.e., HasVAListArg==true), we add a
846 // special check to see if the format string is a function parameter
847 // of the function calling the printf function. If the function
848 // has an attribute indicating it is a printf-like function, then we
849 // should suppress warnings concerning non-literals being used in a call
850 // to a vprintf function. For example:
851 //
852 // void
853 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
854 // va_list ap;
855 // va_start(ap, fmt);
856 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
857 // ...
858 //
859 //
860 // FIXME: We don't have full attribute support yet, so just check to see
861 // if the argument is a DeclRefExpr that references a parameter. We'll
862 // add proper support for checking the attribute later.
863 if (HasVAListArg)
864 if (isa<ParmVarDecl>(VD))
865 return true;
Ted Kremenek082d9362009-03-20 21:35:28 +0000866 }
Mike Stump1eb44332009-09-09 15:08:12 +0000867
Ted Kremenek082d9362009-03-20 21:35:28 +0000868 return false;
869 }
Ted Kremenekd30ef872009-01-12 23:09:09 +0000870
Anders Carlsson8f031b32009-06-27 04:05:33 +0000871 case Stmt::CallExprClass: {
872 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000873 if (const ImplicitCastExpr *ICE
Anders Carlsson8f031b32009-06-27 04:05:33 +0000874 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
875 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
876 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000877 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlsson8f031b32009-06-27 04:05:33 +0000878 unsigned ArgIndex = FA->getFormatIdx();
879 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +0000880
881 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Anders Carlsson8f031b32009-06-27 04:05:33 +0000882 format_idx, firstDataArg);
883 }
884 }
885 }
886 }
Mike Stump1eb44332009-09-09 15:08:12 +0000887
Anders Carlsson8f031b32009-06-27 04:05:33 +0000888 return false;
889 }
Ted Kremenek082d9362009-03-20 21:35:28 +0000890 case Stmt::ObjCStringLiteralClass:
891 case Stmt::StringLiteralClass: {
892 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +0000893
Ted Kremenek082d9362009-03-20 21:35:28 +0000894 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +0000895 StrE = ObjCFExpr->getString();
896 else
Ted Kremenek082d9362009-03-20 21:35:28 +0000897 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000898
Ted Kremenekd30ef872009-01-12 23:09:09 +0000899 if (StrE) {
Mike Stump1eb44332009-09-09 15:08:12 +0000900 CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000901 firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000902 return true;
903 }
Mike Stump1eb44332009-09-09 15:08:12 +0000904
Ted Kremenekd30ef872009-01-12 23:09:09 +0000905 return false;
906 }
Mike Stump1eb44332009-09-09 15:08:12 +0000907
Ted Kremenek082d9362009-03-20 21:35:28 +0000908 default:
909 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000910 }
911}
912
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +0000913void
Mike Stump1eb44332009-09-09 15:08:12 +0000914Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
915 const CallExpr *TheCall) {
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +0000916 for (NonNullAttr::iterator i = NonNull->begin(), e = NonNull->end();
917 i != e; ++i) {
Chris Lattner12b97ff2009-05-25 18:23:36 +0000918 const Expr *ArgExpr = TheCall->getArg(*i);
Douglas Gregorce940492009-09-25 04:25:58 +0000919 if (ArgExpr->isNullPointerConstant(Context,
920 Expr::NPC_ValueDependentIsNotNull))
Chris Lattner12b97ff2009-05-25 18:23:36 +0000921 Diag(TheCall->getCallee()->getLocStart(), diag::warn_null_arg)
922 << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +0000923 }
924}
Ted Kremenekd30ef872009-01-12 23:09:09 +0000925
Chris Lattner59907c42007-08-10 20:18:51 +0000926/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Mike Stump1eb44332009-09-09 15:08:12 +0000927/// correct use of format strings.
Ted Kremenek71895b92007-08-14 17:39:48 +0000928///
929/// HasVAListArg - A predicate indicating whether the printf-like
930/// function is passed an explicit va_arg argument (e.g., vprintf)
931///
932/// format_idx - The index into Args for the format string.
933///
934/// Improper format strings to functions in the printf family can be
935/// the source of bizarre bugs and very serious security holes. A
936/// good source of information is available in the following paper
937/// (which includes additional references):
Chris Lattner59907c42007-08-10 20:18:51 +0000938///
939/// FormatGuard: Automatic Protection From printf Format String
940/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremenek71895b92007-08-14 17:39:48 +0000941///
942/// Functionality implemented:
943///
944/// We can statically check the following properties for string
945/// literal format strings for non v.*printf functions (where the
946/// arguments are passed directly):
947//
948/// (1) Are the number of format conversions equal to the number of
949/// data arguments?
950///
951/// (2) Does each format conversion correctly match the type of the
952/// corresponding data argument? (TODO)
953///
954/// Moreover, for all printf functions we can:
955///
956/// (3) Check for a missing format string (when not caught by type checking).
957///
958/// (4) Check for no-operation flags; e.g. using "#" with format
959/// conversion 'c' (TODO)
960///
961/// (5) Check the use of '%n', a major source of security holes.
962///
963/// (6) Check for malformed format conversions that don't specify anything.
964///
965/// (7) Check for empty format strings. e.g: printf("");
966///
967/// (8) Check that the format string is a wide literal.
968///
Ted Kremenek6d439592008-03-03 16:50:00 +0000969/// (9) Also check the arguments of functions with the __format__ attribute.
970/// (TODO).
971///
Ted Kremenek71895b92007-08-14 17:39:48 +0000972/// All of these checks can be done by parsing the format string.
973///
974/// For now, we ONLY do (1), (3), (5), (6), (7), and (8).
Chris Lattner59907c42007-08-10 20:18:51 +0000975void
Mike Stump1eb44332009-09-09 15:08:12 +0000976Sema::CheckPrintfArguments(const CallExpr *TheCall, bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000977 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenek082d9362009-03-20 21:35:28 +0000978 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +0000979
Sebastian Redl4a2614e2009-11-17 18:02:24 +0000980 // The way the format attribute works in GCC, the implicit this argument
981 // of member functions is counted. However, it doesn't appear in our own
982 // lists, so decrement format_idx in that case.
983 if (isa<CXXMemberCallExpr>(TheCall)) {
984 // Catch a format attribute mistakenly referring to the object argument.
985 if (format_idx == 0)
986 return;
987 --format_idx;
988 if(firstDataArg != 0)
989 --firstDataArg;
990 }
991
Mike Stump1eb44332009-09-09 15:08:12 +0000992 // CHECK: printf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +0000993 if (format_idx >= TheCall->getNumArgs()) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000994 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string)
995 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000996 return;
997 }
Mike Stump1eb44332009-09-09 15:08:12 +0000998
Ted Kremenek082d9362009-03-20 21:35:28 +0000999 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001000
Chris Lattner59907c42007-08-10 20:18:51 +00001001 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001002 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001003 // Dynamically generated format strings are difficult to
1004 // automatically vet at compile time. Requiring that format strings
1005 // are string literals: (1) permits the checking of format strings by
1006 // the compiler and thereby (2) can practically remove the source of
1007 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001008
Mike Stump1eb44332009-09-09 15:08:12 +00001009 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001010 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001011 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001012 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001013 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
1014 firstDataArg))
1015 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001016
Chris Lattner655f1412009-04-29 04:59:47 +00001017 // If there are no arguments specified, warn with -Wformat-security, otherwise
1018 // warn only with -Wformat-nonliteral.
1019 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump1eb44332009-09-09 15:08:12 +00001020 Diag(TheCall->getArg(format_idx)->getLocStart(),
Chris Lattner655f1412009-04-29 04:59:47 +00001021 diag::warn_printf_nonliteral_noargs)
1022 << OrigFormatExpr->getSourceRange();
1023 else
Mike Stump1eb44332009-09-09 15:08:12 +00001024 Diag(TheCall->getArg(format_idx)->getLocStart(),
Chris Lattner655f1412009-04-29 04:59:47 +00001025 diag::warn_printf_nonliteral)
1026 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001027}
Ted Kremenek71895b92007-08-14 17:39:48 +00001028
Ted Kremenek082d9362009-03-20 21:35:28 +00001029void Sema::CheckPrintfString(const StringLiteral *FExpr,
1030 const Expr *OrigFormatExpr,
1031 const CallExpr *TheCall, bool HasVAListArg,
1032 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenekd30ef872009-01-12 23:09:09 +00001033
Ted Kremenek082d9362009-03-20 21:35:28 +00001034 const ObjCStringLiteral *ObjCFExpr =
1035 dyn_cast<ObjCStringLiteral>(OrigFormatExpr);
1036
Ted Kremenek71895b92007-08-14 17:39:48 +00001037 // CHECK: is the format string a wide literal?
1038 if (FExpr->isWide()) {
Chris Lattner925e60d2007-12-28 05:29:59 +00001039 Diag(FExpr->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001040 diag::warn_printf_format_string_is_wide_literal)
1041 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001042 return;
1043 }
1044
1045 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattnerb9fc8562009-04-29 04:12:34 +00001046 const char *Str = FExpr->getStrData();
Ted Kremenek71895b92007-08-14 17:39:48 +00001047
1048 // CHECK: empty format string?
Chris Lattnerb9fc8562009-04-29 04:12:34 +00001049 unsigned StrLen = FExpr->getByteLength();
Mike Stump1eb44332009-09-09 15:08:12 +00001050
Ted Kremenek71895b92007-08-14 17:39:48 +00001051 if (StrLen == 0) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001052 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string)
1053 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001054 return;
1055 }
1056
1057 // We process the format string using a binary state machine. The
1058 // current state is stored in CurrentState.
1059 enum {
1060 state_OrdChr,
1061 state_Conversion
1062 } CurrentState = state_OrdChr;
Mike Stump1eb44332009-09-09 15:08:12 +00001063
Ted Kremenek71895b92007-08-14 17:39:48 +00001064 // numConversions - The number of conversions seen so far. This is
1065 // incremented as we traverse the format string.
1066 unsigned numConversions = 0;
1067
1068 // numDataArgs - The number of data arguments after the format
1069 // string. This can only be determined for non vprintf-like
1070 // functions. For those functions, this value is 1 (the sole
1071 // va_arg argument).
Douglas Gregor3c385e52009-02-14 18:57:46 +00001072 unsigned numDataArgs = TheCall->getNumArgs()-firstDataArg;
Ted Kremenek71895b92007-08-14 17:39:48 +00001073
1074 // Inspect the format string.
1075 unsigned StrIdx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001076
Ted Kremenek71895b92007-08-14 17:39:48 +00001077 // LastConversionIdx - Index within the format string where we last saw
1078 // a '%' character that starts a new format conversion.
1079 unsigned LastConversionIdx = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001080
Chris Lattner925e60d2007-12-28 05:29:59 +00001081 for (; StrIdx < StrLen; ++StrIdx) {
Mike Stump1eb44332009-09-09 15:08:12 +00001082
Ted Kremenek71895b92007-08-14 17:39:48 +00001083 // Is the number of detected conversion conversions greater than
1084 // the number of matching data arguments? If so, stop.
1085 if (!HasVAListArg && numConversions > numDataArgs) break;
Mike Stump1eb44332009-09-09 15:08:12 +00001086
Ted Kremenek71895b92007-08-14 17:39:48 +00001087 // Handle "\0"
Chris Lattner925e60d2007-12-28 05:29:59 +00001088 if (Str[StrIdx] == '\0') {
Ted Kremenek71895b92007-08-14 17:39:48 +00001089 // The string returned by getStrData() is not null-terminated,
1090 // so the presence of a null character is likely an error.
Chris Lattner60800082009-02-18 17:49:48 +00001091 Diag(getLocationOfStringLiteralByte(FExpr, StrIdx),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001092 diag::warn_printf_format_string_contains_null_char)
1093 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001094 return;
1095 }
Mike Stump1eb44332009-09-09 15:08:12 +00001096
Ted Kremenek71895b92007-08-14 17:39:48 +00001097 // Ordinary characters (not processing a format conversion).
1098 if (CurrentState == state_OrdChr) {
1099 if (Str[StrIdx] == '%') {
1100 CurrentState = state_Conversion;
1101 LastConversionIdx = StrIdx;
1102 }
1103 continue;
1104 }
1105
1106 // Seen '%'. Now processing a format conversion.
1107 switch (Str[StrIdx]) {
Mike Stump1eb44332009-09-09 15:08:12 +00001108 // Handle dynamic precision or width specifier.
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001109 case '*': {
1110 ++numConversions;
Mike Stump1eb44332009-09-09 15:08:12 +00001111
Ted Kremenek42ae3e82009-05-13 16:06:05 +00001112 if (!HasVAListArg) {
1113 if (numConversions > numDataArgs) {
1114 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx);
Ted Kremenek580b6642007-10-12 20:51:52 +00001115
Ted Kremenek42ae3e82009-05-13 16:06:05 +00001116 if (Str[StrIdx-1] == '.')
1117 Diag(Loc, diag::warn_printf_asterisk_precision_missing_arg)
1118 << OrigFormatExpr->getSourceRange();
1119 else
1120 Diag(Loc, diag::warn_printf_asterisk_width_missing_arg)
1121 << OrigFormatExpr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001122
Ted Kremenek42ae3e82009-05-13 16:06:05 +00001123 // Don't do any more checking. We'll just emit spurious errors.
1124 return;
1125 }
Mike Stump1eb44332009-09-09 15:08:12 +00001126
Ted Kremenek42ae3e82009-05-13 16:06:05 +00001127 // Perform type checking on width/precision specifier.
1128 const Expr *E = TheCall->getArg(format_idx+numConversions);
John McCall183700f2009-09-21 23:43:11 +00001129 if (const BuiltinType *BT = E->getType()->getAs<BuiltinType>())
Ted Kremenek42ae3e82009-05-13 16:06:05 +00001130 if (BT->getKind() == BuiltinType::Int)
1131 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001132
Ted Kremenek42ae3e82009-05-13 16:06:05 +00001133 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr, StrIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00001134
Ted Kremenek42ae3e82009-05-13 16:06:05 +00001135 if (Str[StrIdx-1] == '.')
1136 Diag(Loc, diag::warn_printf_asterisk_precision_wrong_type)
1137 << E->getType() << E->getSourceRange();
1138 else
1139 Diag(Loc, diag::warn_printf_asterisk_width_wrong_type)
1140 << E->getType() << E->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001141
1142 break;
Ted Kremenek580b6642007-10-12 20:51:52 +00001143 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001144 }
Mike Stump1eb44332009-09-09 15:08:12 +00001145
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001146 // Characters which can terminate a format conversion
1147 // (e.g. "%d"). Characters that specify length modifiers or
1148 // other flags are handled by the default case below.
1149 //
Mike Stump1eb44332009-09-09 15:08:12 +00001150 // FIXME: additional checks will go into the following cases.
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001151 case 'i':
1152 case 'd':
Mike Stump1eb44332009-09-09 15:08:12 +00001153 case 'o':
1154 case 'u':
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001155 case 'x':
1156 case 'X':
1157 case 'D':
1158 case 'O':
1159 case 'U':
1160 case 'e':
1161 case 'E':
1162 case 'f':
1163 case 'F':
1164 case 'g':
1165 case 'G':
1166 case 'a':
1167 case 'A':
1168 case 'c':
1169 case 'C':
1170 case 'S':
1171 case 's':
Mike Stump1eb44332009-09-09 15:08:12 +00001172 case 'p':
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001173 ++numConversions;
1174 CurrentState = state_OrdChr;
1175 break;
1176
Eli Friedmanb92abb42009-06-02 08:36:19 +00001177 case 'm':
1178 // FIXME: Warn in situations where this isn't supported!
1179 CurrentState = state_OrdChr;
1180 break;
1181
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001182 // CHECK: Are we using "%n"? Issue a warning.
1183 case 'n': {
1184 ++numConversions;
1185 CurrentState = state_OrdChr;
Chris Lattner60800082009-02-18 17:49:48 +00001186 SourceLocation Loc = getLocationOfStringLiteralByte(FExpr,
1187 LastConversionIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00001188
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001189 Diag(Loc, diag::warn_printf_write_back)<<OrigFormatExpr->getSourceRange();
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001190 break;
1191 }
Mike Stump1eb44332009-09-09 15:08:12 +00001192
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001193 // Handle "%@"
1194 case '@':
1195 // %@ is allowed in ObjC format strings only.
Mike Stump1eb44332009-09-09 15:08:12 +00001196 if (ObjCFExpr != NULL)
1197 CurrentState = state_OrdChr;
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001198 else {
1199 // Issue a warning: invalid format conversion.
Mike Stump1eb44332009-09-09 15:08:12 +00001200 SourceLocation Loc =
Chris Lattner60800082009-02-18 17:49:48 +00001201 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00001202
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001203 Diag(Loc, diag::warn_printf_invalid_conversion)
1204 << std::string(Str+LastConversionIdx,
1205 Str+std::min(LastConversionIdx+2, StrLen))
1206 << OrigFormatExpr->getSourceRange();
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001207 }
1208 ++numConversions;
1209 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001210
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001211 // Handle "%%"
1212 case '%':
1213 // Sanity check: Was the first "%" character the previous one?
1214 // If not, we will assume that we have a malformed format
1215 // conversion, and that the current "%" character is the start
1216 // of a new conversion.
1217 if (StrIdx - LastConversionIdx == 1)
Mike Stump1eb44332009-09-09 15:08:12 +00001218 CurrentState = state_OrdChr;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001219 else {
1220 // Issue a warning: invalid format conversion.
Chris Lattner60800082009-02-18 17:49:48 +00001221 SourceLocation Loc =
1222 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00001223
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001224 Diag(Loc, diag::warn_printf_invalid_conversion)
1225 << std::string(Str+LastConversionIdx, Str+StrIdx)
1226 << OrigFormatExpr->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001227
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001228 // This conversion is broken. Advance to the next format
1229 // conversion.
1230 LastConversionIdx = StrIdx;
1231 ++numConversions;
Ted Kremenek71895b92007-08-14 17:39:48 +00001232 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001233 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001234
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001235 default:
1236 // This case catches all other characters: flags, widths, etc.
1237 // We should eventually process those as well.
1238 break;
Ted Kremenek71895b92007-08-14 17:39:48 +00001239 }
1240 }
1241
1242 if (CurrentState == state_Conversion) {
1243 // Issue a warning: invalid format conversion.
Chris Lattner60800082009-02-18 17:49:48 +00001244 SourceLocation Loc =
1245 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00001246
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001247 Diag(Loc, diag::warn_printf_invalid_conversion)
1248 << std::string(Str+LastConversionIdx,
1249 Str+std::min(LastConversionIdx+2, StrLen))
1250 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001251 return;
1252 }
Mike Stump1eb44332009-09-09 15:08:12 +00001253
Ted Kremenek71895b92007-08-14 17:39:48 +00001254 if (!HasVAListArg) {
1255 // CHECK: Does the number of format conversions exceed the number
1256 // of data arguments?
1257 if (numConversions > numDataArgs) {
Chris Lattner60800082009-02-18 17:49:48 +00001258 SourceLocation Loc =
1259 getLocationOfStringLiteralByte(FExpr, LastConversionIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00001260
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001261 Diag(Loc, diag::warn_printf_insufficient_data_args)
1262 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001263 }
1264 // CHECK: Does the number of data arguments exceed the number of
1265 // format conversions in the format string?
1266 else if (numConversions < numDataArgs)
Chris Lattner925e60d2007-12-28 05:29:59 +00001267 Diag(TheCall->getArg(format_idx+numConversions+1)->getLocStart(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001268 diag::warn_printf_too_many_data_args)
1269 << OrigFormatExpr->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001270 }
1271}
Ted Kremenek06de2762007-08-17 16:46:58 +00001272
1273//===--- CHECK: Return Address of Stack Variable --------------------------===//
1274
1275static DeclRefExpr* EvalVal(Expr *E);
1276static DeclRefExpr* EvalAddr(Expr* E);
1277
1278/// CheckReturnStackAddr - Check if a return statement returns the address
1279/// of a stack variable.
1280void
1281Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1282 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00001283
Ted Kremenek06de2762007-08-17 16:46:58 +00001284 // Perform checking for returned stack addresses.
Steve Naroffdd972f22008-09-05 22:11:13 +00001285 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Ted Kremenek06de2762007-08-17 16:46:58 +00001286 if (DeclRefExpr *DR = EvalAddr(RetValExp))
Chris Lattner3c73c412008-11-19 08:23:25 +00001287 Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
Chris Lattner08631c52008-11-23 21:45:46 +00001288 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001289
Steve Naroffc50a4a52008-09-16 22:25:10 +00001290 // Skip over implicit cast expressions when checking for block expressions.
Chris Lattner4ca606e2009-09-08 00:36:37 +00001291 RetValExp = RetValExp->IgnoreParenCasts();
Steve Naroffc50a4a52008-09-16 22:25:10 +00001292
Chris Lattner9e6b37a2009-10-30 04:01:58 +00001293 if (BlockExpr *C = dyn_cast<BlockExpr>(RetValExp))
Mike Stump397195b2009-04-17 00:09:41 +00001294 if (C->hasBlockDeclRefExprs())
1295 Diag(C->getLocStart(), diag::err_ret_local_block)
1296 << C->getSourceRange();
Chris Lattner9e6b37a2009-10-30 04:01:58 +00001297
1298 if (AddrLabelExpr *ALE = dyn_cast<AddrLabelExpr>(RetValExp))
1299 Diag(ALE->getLocStart(), diag::warn_ret_addr_label)
1300 << ALE->getSourceRange();
1301
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001302 } else if (lhsType->isReferenceType()) {
1303 // Perform checking for stack values returned by reference.
Douglas Gregor49badde2008-10-27 19:41:14 +00001304 // Check for a reference to the stack
1305 if (DeclRefExpr *DR = EvalVal(RetValExp))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001306 Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
Chris Lattner08631c52008-11-23 21:45:46 +00001307 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +00001308 }
1309}
1310
1311/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1312/// check if the expression in a return statement evaluates to an address
1313/// to a location on the stack. The recursion is used to traverse the
1314/// AST of the return expression, with recursion backtracking when we
1315/// encounter a subexpression that (1) clearly does not lead to the address
1316/// of a stack variable or (2) is something we cannot determine leads to
1317/// the address of a stack variable based on such local checking.
1318///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001319/// EvalAddr processes expressions that are pointers that are used as
1320/// references (and not L-values). EvalVal handles all other values.
Mike Stump1eb44332009-09-09 15:08:12 +00001321/// At the base case of the recursion is a check for a DeclRefExpr* in
Ted Kremenek06de2762007-08-17 16:46:58 +00001322/// the refers to a stack variable.
1323///
1324/// This implementation handles:
1325///
1326/// * pointer-to-pointer casts
1327/// * implicit conversions from array references to pointers
1328/// * taking the address of fields
1329/// * arbitrary interplay between "&" and "*" operators
1330/// * pointer arithmetic from an address of a stack variable
1331/// * taking the address of an array element where the array is on the stack
1332static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek06de2762007-08-17 16:46:58 +00001333 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00001334 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00001335 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001336 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001337 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00001338
Ted Kremenek06de2762007-08-17 16:46:58 +00001339 // Our "symbolic interpreter" is just a dispatch off the currently
1340 // viewed AST node. We then recursively traverse the AST by calling
1341 // EvalAddr and EvalVal appropriately.
1342 switch (E->getStmtClass()) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001343 case Stmt::ParenExprClass:
1344 // Ignore parentheses.
1345 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek06de2762007-08-17 16:46:58 +00001346
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001347 case Stmt::UnaryOperatorClass: {
1348 // The only unary operator that make sense to handle here
1349 // is AddrOf. All others don't make sense as pointers.
1350 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001351
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001352 if (U->getOpcode() == UnaryOperator::AddrOf)
1353 return EvalVal(U->getSubExpr());
1354 else
Ted Kremenek06de2762007-08-17 16:46:58 +00001355 return NULL;
1356 }
Mike Stump1eb44332009-09-09 15:08:12 +00001357
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001358 case Stmt::BinaryOperatorClass: {
1359 // Handle pointer arithmetic. All other binary operators are not valid
1360 // in this context.
1361 BinaryOperator *B = cast<BinaryOperator>(E);
1362 BinaryOperator::Opcode op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00001363
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001364 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
1365 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001366
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001367 Expr *Base = B->getLHS();
1368
1369 // Determine which argument is the real pointer base. It could be
1370 // the RHS argument instead of the LHS.
1371 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00001372
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001373 assert (Base->getType()->isPointerType());
1374 return EvalAddr(Base);
1375 }
Steve Naroff61f40a22008-09-10 19:17:48 +00001376
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001377 // For conditional operators we need to see if either the LHS or RHS are
1378 // valid DeclRefExpr*s. If one of them is valid, we return it.
1379 case Stmt::ConditionalOperatorClass: {
1380 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001381
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001382 // Handle the GNU extension for missing LHS.
1383 if (Expr *lhsExpr = C->getLHS())
1384 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
1385 return LHS;
1386
1387 return EvalAddr(C->getRHS());
1388 }
Mike Stump1eb44332009-09-09 15:08:12 +00001389
Ted Kremenek54b52742008-08-07 00:49:01 +00001390 // For casts, we need to handle conversions from arrays to
1391 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00001392 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001393 case Stmt::CStyleCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001394 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001395 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00001396 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001397
Steve Naroffdd972f22008-09-05 22:11:13 +00001398 if (SubExpr->getType()->isPointerType() ||
1399 SubExpr->getType()->isBlockPointerType() ||
1400 SubExpr->getType()->isObjCQualifiedIdType())
Ted Kremenek54b52742008-08-07 00:49:01 +00001401 return EvalAddr(SubExpr);
1402 else if (T->isArrayType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001403 return EvalVal(SubExpr);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001404 else
Ted Kremenek54b52742008-08-07 00:49:01 +00001405 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001406 }
Mike Stump1eb44332009-09-09 15:08:12 +00001407
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001408 // C++ casts. For dynamic casts, static casts, and const casts, we
1409 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00001410 // through the cast. In the case the dynamic cast doesn't fail (and
1411 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001412 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00001413 // FIXME: The comment about is wrong; we're not always converting
1414 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00001415 // handle references to objects.
1416 case Stmt::CXXStaticCastExprClass:
1417 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001418 case Stmt::CXXConstCastExprClass:
1419 case Stmt::CXXReinterpretCastExprClass: {
1420 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00001421 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001422 return EvalAddr(S);
1423 else
1424 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001425 }
Mike Stump1eb44332009-09-09 15:08:12 +00001426
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001427 // Everything else: we simply don't reason about them.
1428 default:
1429 return NULL;
1430 }
Ted Kremenek06de2762007-08-17 16:46:58 +00001431}
Mike Stump1eb44332009-09-09 15:08:12 +00001432
Ted Kremenek06de2762007-08-17 16:46:58 +00001433
1434/// EvalVal - This function is complements EvalAddr in the mutual recursion.
1435/// See the comments for EvalAddr for more details.
1436static DeclRefExpr* EvalVal(Expr *E) {
Mike Stump1eb44332009-09-09 15:08:12 +00001437
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001438 // We should only be called for evaluating non-pointer expressions, or
1439 // expressions with a pointer type that are not used as references but instead
1440 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00001441
Ted Kremenek06de2762007-08-17 16:46:58 +00001442 // Our "symbolic interpreter" is just a dispatch off the currently
1443 // viewed AST node. We then recursively traverse the AST by calling
1444 // EvalAddr and EvalVal appropriately.
1445 switch (E->getStmtClass()) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00001446 case Stmt::DeclRefExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00001447 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
1448 // at code that refers to a variable's name. We check if it has local
1449 // storage within the function, and if so, return the expression.
1450 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001451
Ted Kremenek06de2762007-08-17 16:46:58 +00001452 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Mike Stump1eb44332009-09-09 15:08:12 +00001453 if (V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
1454
Ted Kremenek06de2762007-08-17 16:46:58 +00001455 return NULL;
1456 }
Mike Stump1eb44332009-09-09 15:08:12 +00001457
Ted Kremenek06de2762007-08-17 16:46:58 +00001458 case Stmt::ParenExprClass:
1459 // Ignore parentheses.
1460 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
Mike Stump1eb44332009-09-09 15:08:12 +00001461
Ted Kremenek06de2762007-08-17 16:46:58 +00001462 case Stmt::UnaryOperatorClass: {
1463 // The only unary operator that make sense to handle here
1464 // is Deref. All others don't resolve to a "name." This includes
1465 // handling all sorts of rvalues passed to a unary operator.
1466 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001467
Ted Kremenek06de2762007-08-17 16:46:58 +00001468 if (U->getOpcode() == UnaryOperator::Deref)
1469 return EvalAddr(U->getSubExpr());
1470
1471 return NULL;
1472 }
Mike Stump1eb44332009-09-09 15:08:12 +00001473
Ted Kremenek06de2762007-08-17 16:46:58 +00001474 case Stmt::ArraySubscriptExprClass: {
1475 // Array subscripts are potential references to data on the stack. We
1476 // retrieve the DeclRefExpr* for the array variable if it indeed
1477 // has local storage.
Ted Kremenek23245122007-08-20 16:18:38 +00001478 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek06de2762007-08-17 16:46:58 +00001479 }
Mike Stump1eb44332009-09-09 15:08:12 +00001480
Ted Kremenek06de2762007-08-17 16:46:58 +00001481 case Stmt::ConditionalOperatorClass: {
1482 // For conditional operators we need to see if either the LHS or RHS are
1483 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
1484 ConditionalOperator *C = cast<ConditionalOperator>(E);
1485
Anders Carlsson39073232007-11-30 19:04:31 +00001486 // Handle the GNU extension for missing LHS.
1487 if (Expr *lhsExpr = C->getLHS())
1488 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
1489 return LHS;
1490
1491 return EvalVal(C->getRHS());
Ted Kremenek06de2762007-08-17 16:46:58 +00001492 }
Mike Stump1eb44332009-09-09 15:08:12 +00001493
Ted Kremenek06de2762007-08-17 16:46:58 +00001494 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00001495 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00001496 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001497
Ted Kremenek06de2762007-08-17 16:46:58 +00001498 // Check for indirect access. We only want direct field accesses.
1499 if (!M->isArrow())
1500 return EvalVal(M->getBase());
1501 else
1502 return NULL;
1503 }
Mike Stump1eb44332009-09-09 15:08:12 +00001504
Ted Kremenek06de2762007-08-17 16:46:58 +00001505 // Everything else: we simply don't reason about them.
1506 default:
1507 return NULL;
1508 }
1509}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001510
1511//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
1512
1513/// Check for comparisons of floating point operands using != and ==.
1514/// Issue a warning if these are no self-comparisons, as they are not likely
1515/// to do what the programmer intended.
1516void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
1517 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001518
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00001519 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek32e97b62008-01-17 17:55:13 +00001520 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001521
1522 // Special case: check for x == x (which is OK).
1523 // Do not emit warnings for such cases.
1524 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
1525 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
1526 if (DRL->getDecl() == DRR->getDecl())
1527 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001528
1529
Ted Kremenek1b500bb2007-11-29 00:59:04 +00001530 // Special case: check for comparisons against literals that can be exactly
1531 // represented by APFloat. In such cases, do not emit a warning. This
1532 // is a heuristic: often comparison against such literals are used to
1533 // detect if a value in a variable has not changed. This clearly can
1534 // lead to false negatives.
1535 if (EmitWarning) {
1536 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
1537 if (FLL->isExact())
1538 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001539 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00001540 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
1541 if (FLR->isExact())
1542 EmitWarning = false;
1543 }
1544 }
Mike Stump1eb44332009-09-09 15:08:12 +00001545
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001546 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001547 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001548 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001549 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001550 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001551
Sebastian Redl0eb23302009-01-19 00:08:26 +00001552 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001553 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001554 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001555 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001556
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001557 // Emit the diagnostic.
1558 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001559 Diag(loc, diag::warn_floatingpoint_eq)
1560 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001561}
John McCallba26e582010-01-04 23:21:16 +00001562
1563//===--- CHECK: Comparison of signed and unsigned int (-Wsign-compare) ----===//
1564
1565/// Returns true if we can prove that the result of the given
1566/// integral expression will not have its sign bit set.
1567static bool IsSignBitProvablyZero(ASTContext &Context, Expr *E) {
1568 E = E->IgnoreParens();
1569
1570 llvm::APSInt value;
1571 if (E->isIntegerConstantExpr(value, Context))
1572 return value.isNonNegative();
1573
1574 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
1575 return IsSignBitProvablyZero(Context, CO->getLHS()) &&
1576 IsSignBitProvablyZero(Context, CO->getRHS());
1577
1578 return false;
1579}
1580
1581/// \brief Implements -Wsign-compare.
1582///
1583/// \param lex the left-hand expression
1584/// \param rex the right-hand expression
1585/// \param OpLoc the location of the joining operator
1586/// \param Equality whether this is an "equality-like" join, which
1587/// suppresses the warning in some cases
1588void Sema::CheckSignCompare(Expr *lex, Expr *rex, SourceLocation OpLoc,
1589 const PartialDiagnostic &PD, bool Equality) {
1590 // Don't warn if we're in an unevaluated context.
1591 if (ExprEvalContexts.back().Context == Unevaluated)
1592 return;
1593
1594 QualType lt = lex->getType(), rt = rex->getType();
1595
1596 // Only warn if both operands are integral.
1597 if (!lt->isIntegerType() || !rt->isIntegerType())
1598 return;
1599
1600 // If either expression is value-dependent, don't warn. We'll get another
1601 // chance at instantiation time.
1602 if (lex->isValueDependent() || rex->isValueDependent())
1603 return;
1604
1605 // The rule is that the signed operand becomes unsigned, so isolate the
1606 // signed operand.
1607 Expr *signedOperand, *unsignedOperand;
1608 if (lt->isSignedIntegerType()) {
1609 if (rt->isSignedIntegerType()) return;
1610 signedOperand = lex;
1611 unsignedOperand = rex;
1612 } else {
1613 if (!rt->isSignedIntegerType()) return;
1614 signedOperand = rex;
1615 unsignedOperand = lex;
1616 }
1617
1618 // If the unsigned type is strictly smaller than the signed type,
1619 // then (1) the result type will be signed and (2) the unsigned
1620 // value will fit fully within the signed type, and thus the result
1621 // of the comparison will be exact.
1622 if (Context.getIntWidth(signedOperand->getType()) >
1623 Context.getIntWidth(unsignedOperand->getType()))
1624 return;
1625
1626 // If the value is a non-negative integer constant, then the
1627 // signed->unsigned conversion won't change it.
1628 if (IsSignBitProvablyZero(Context, signedOperand))
1629 return;
1630
1631 // For (in)equality comparisons, if the unsigned operand is a
1632 // constant which cannot collide with a overflowed signed operand,
1633 // then reinterpreting the signed operand as unsigned will not
1634 // change the result of the comparison.
1635 if (Equality && IsSignBitProvablyZero(Context, unsignedOperand))
1636 return;
1637
1638 Diag(OpLoc, PD)
1639 << lex->getType() << rex->getType()
1640 << lex->getSourceRange() << rex->getSourceRange();
1641}
1642