blob: 5091daf32355520d861651bced43d0a9c5e5ce7e [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"
Ted Kremeneke0e53132010-01-28 23:39:18 +000016#include "clang/Analysis/Analyses/PrintfFormatString.h"
Chris Lattner59907c42007-08-10 20:18:51 +000017#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000018#include "clang/AST/CharUnits.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Ted Kremenek23245122007-08-20 16:18:38 +000020#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000021#include "clang/AST/ExprObjC.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000022#include "clang/AST/DeclObjC.h"
23#include "clang/AST/StmtCXX.h"
24#include "clang/AST/StmtObjC.h"
Chris Lattner719e6152009-02-18 19:21:10 +000025#include "clang/Lex/LiteralSupport.h"
Chris Lattner59907c42007-08-10 20:18:51 +000026#include "clang/Lex/Preprocessor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000027#include "llvm/ADT/BitVector.h"
28#include "llvm/ADT/STLExtras.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000029#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000030using namespace clang;
31
Chris Lattner60800082009-02-18 17:49:48 +000032/// getLocationOfStringLiteralByte - Return a source location that points to the
33/// specified byte of the specified string literal.
34///
35/// Strings are amazingly complex. They can be formed from multiple tokens and
36/// can have escape sequences in them in addition to the usual trigraph and
37/// escaped newline business. This routine handles this complexity.
38///
39SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
40 unsigned ByteNo) const {
41 assert(!SL->isWide() && "This doesn't work for wide strings yet");
Mike Stump1eb44332009-09-09 15:08:12 +000042
Chris Lattner60800082009-02-18 17:49:48 +000043 // Loop over all of the tokens in this string until we find the one that
44 // contains the byte we're looking for.
45 unsigned TokNo = 0;
46 while (1) {
47 assert(TokNo < SL->getNumConcatenated() && "Invalid byte number!");
48 SourceLocation StrTokLoc = SL->getStrTokenLoc(TokNo);
Mike Stump1eb44332009-09-09 15:08:12 +000049
Chris Lattner60800082009-02-18 17:49:48 +000050 // Get the spelling of the string so that we can get the data that makes up
51 // the string literal, not the identifier for the macro it is potentially
52 // expanded through.
53 SourceLocation StrTokSpellingLoc = SourceMgr.getSpellingLoc(StrTokLoc);
54
55 // Re-lex the token to get its length and original spelling.
56 std::pair<FileID, unsigned> LocInfo =
57 SourceMgr.getDecomposedLoc(StrTokSpellingLoc);
Douglas Gregorf715ca12010-03-16 00:06:06 +000058 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +000059 llvm::StringRef Buffer = SourceMgr.getBufferData(LocInfo.first, &Invalid);
Douglas Gregorf715ca12010-03-16 00:06:06 +000060 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +000061 return StrTokSpellingLoc;
62
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +000063 const char *StrData = Buffer.data()+LocInfo.second;
Mike Stump1eb44332009-09-09 15:08:12 +000064
Chris Lattner60800082009-02-18 17:49:48 +000065 // Create a langops struct and enable trigraphs. This is sufficient for
66 // relexing tokens.
67 LangOptions LangOpts;
68 LangOpts.Trigraphs = true;
Mike Stump1eb44332009-09-09 15:08:12 +000069
Chris Lattner60800082009-02-18 17:49:48 +000070 // Create a lexer starting at the beginning of this token.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +000071 Lexer TheLexer(StrTokSpellingLoc, LangOpts, Buffer.begin(), StrData,
72 Buffer.end());
Chris Lattner60800082009-02-18 17:49:48 +000073 Token TheTok;
74 TheLexer.LexFromRawLexer(TheTok);
Mike Stump1eb44332009-09-09 15:08:12 +000075
Chris Lattner443e53c2009-02-18 19:26:42 +000076 // Use the StringLiteralParser to compute the length of the string in bytes.
77 StringLiteralParser SLP(&TheTok, 1, PP);
78 unsigned TokNumBytes = SLP.GetStringLength();
Mike Stump1eb44332009-09-09 15:08:12 +000079
Chris Lattner2197c962009-02-18 18:52:52 +000080 // If the byte is in this token, return the location of the byte.
Chris Lattner60800082009-02-18 17:49:48 +000081 if (ByteNo < TokNumBytes ||
82 (ByteNo == TokNumBytes && TokNo == SL->getNumConcatenated())) {
Mike Stump1eb44332009-09-09 15:08:12 +000083 unsigned Offset =
Chris Lattner719e6152009-02-18 19:21:10 +000084 StringLiteralParser::getOffsetOfStringByte(TheTok, ByteNo, PP);
Mike Stump1eb44332009-09-09 15:08:12 +000085
Chris Lattner719e6152009-02-18 19:21:10 +000086 // Now that we know the offset of the token in the spelling, use the
87 // preprocessor to get the offset in the original source.
88 return PP.AdvanceToTokenCharacter(StrTokLoc, Offset);
Chris Lattner60800082009-02-18 17:49:48 +000089 }
Mike Stump1eb44332009-09-09 15:08:12 +000090
Chris Lattner60800082009-02-18 17:49:48 +000091 // Move to the next string token.
92 ++TokNo;
93 ByteNo -= TokNumBytes;
94 }
95}
96
Ryan Flynn4403a5e2009-08-06 03:00:50 +000097/// CheckablePrintfAttr - does a function call have a "printf" attribute
98/// and arguments that merit checking?
99bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) {
100 if (Format->getType() == "printf") return true;
101 if (Format->getType() == "printf0") {
102 // printf0 allows null "format" string; if so don't check format/args
103 unsigned format_idx = Format->getFormatIdx() - 1;
Sebastian Redl4a2614e2009-11-17 18:02:24 +0000104 // Does the index refer to the implicit object argument?
105 if (isa<CXXMemberCallExpr>(TheCall)) {
106 if (format_idx == 0)
107 return false;
108 --format_idx;
109 }
Ryan Flynn4403a5e2009-08-06 03:00:50 +0000110 if (format_idx < TheCall->getNumArgs()) {
111 Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts();
Ted Kremenekefaff192010-02-27 01:41:03 +0000112 if (!Format->isNullPointerConstant(Context,
113 Expr::NPC_ValueDependentIsNull))
Ryan Flynn4403a5e2009-08-06 03:00:50 +0000114 return true;
115 }
116 }
117 return false;
118}
Chris Lattner60800082009-02-18 17:49:48 +0000119
Sebastian Redl0eb23302009-01-19 00:08:26 +0000120Action::OwningExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +0000121Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Sebastian Redl0eb23302009-01-19 00:08:26 +0000122 OwningExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +0000123
Anders Carlssond406bf02009-08-16 01:56:34 +0000124 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000125 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000126 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000127 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000128 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000129 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000130 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000131 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000132 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000133 if (SemaBuiltinVAStart(TheCall))
134 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000135 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000136 case Builtin::BI__builtin_isgreater:
137 case Builtin::BI__builtin_isgreaterequal:
138 case Builtin::BI__builtin_isless:
139 case Builtin::BI__builtin_islessequal:
140 case Builtin::BI__builtin_islessgreater:
141 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000142 if (SemaBuiltinUnorderedCompare(TheCall))
143 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000144 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000145 case Builtin::BI__builtin_fpclassify:
146 if (SemaBuiltinFPClassification(TheCall, 6))
147 return ExprError();
148 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000149 case Builtin::BI__builtin_isfinite:
150 case Builtin::BI__builtin_isinf:
151 case Builtin::BI__builtin_isinf_sign:
152 case Builtin::BI__builtin_isnan:
153 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000154 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000155 return ExprError();
156 break;
Eli Friedman6cfda232008-05-20 08:23:37 +0000157 case Builtin::BI__builtin_return_address:
158 case Builtin::BI__builtin_frame_address:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000159 if (SemaBuiltinStackAddress(TheCall))
160 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000161 break;
Chris Lattner21fb98e2009-09-23 06:06:36 +0000162 case Builtin::BI__builtin_eh_return_data_regno:
163 if (SemaBuiltinEHReturnDataRegNo(TheCall))
164 return ExprError();
165 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000166 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000167 return SemaBuiltinShuffleVector(TheCall);
168 // TheCall will be freed by the smart pointer here, but that's fine, since
169 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000170 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000171 if (SemaBuiltinPrefetch(TheCall))
172 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000173 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000174 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000175 if (SemaBuiltinObjectSize(TheCall))
176 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000177 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000178 case Builtin::BI__builtin_longjmp:
179 if (SemaBuiltinLongjmp(TheCall))
180 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000181 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000182 case Builtin::BI__sync_fetch_and_add:
183 case Builtin::BI__sync_fetch_and_sub:
184 case Builtin::BI__sync_fetch_and_or:
185 case Builtin::BI__sync_fetch_and_and:
186 case Builtin::BI__sync_fetch_and_xor:
187 case Builtin::BI__sync_add_and_fetch:
188 case Builtin::BI__sync_sub_and_fetch:
189 case Builtin::BI__sync_and_and_fetch:
190 case Builtin::BI__sync_or_and_fetch:
191 case Builtin::BI__sync_xor_and_fetch:
192 case Builtin::BI__sync_val_compare_and_swap:
193 case Builtin::BI__sync_bool_compare_and_swap:
194 case Builtin::BI__sync_lock_test_and_set:
195 case Builtin::BI__sync_lock_release:
196 if (SemaBuiltinAtomicOverloaded(TheCall))
197 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000198 break;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000199 }
Mike Stump1eb44332009-09-09 15:08:12 +0000200
Anders Carlssond406bf02009-08-16 01:56:34 +0000201 return move(TheCallResult);
202}
Daniel Dunbarde454282008-10-02 18:44:07 +0000203
Anders Carlssond406bf02009-08-16 01:56:34 +0000204/// CheckFunctionCall - Check a direct function call for various correctness
205/// and safety properties not strictly enforced by the C type system.
206bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
207 // Get the IdentifierInfo* for the called function.
208 IdentifierInfo *FnInfo = FDecl->getIdentifier();
209
210 // None of the checks below are needed for functions that don't have
211 // simple names (e.g., C++ conversion functions).
212 if (!FnInfo)
213 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000214
Daniel Dunbarde454282008-10-02 18:44:07 +0000215 // FIXME: This mechanism should be abstracted to be less fragile and
216 // more efficient. For example, just map function ids to custom
217 // handlers.
218
Chris Lattner59907c42007-08-10 20:18:51 +0000219 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000220 if (const FormatAttr *Format = FDecl->getAttr<FormatAttr>()) {
Ryan Flynn4403a5e2009-08-06 03:00:50 +0000221 if (CheckablePrintfAttr(Format, TheCall)) {
Ted Kremenek3d692df2009-02-27 17:58:43 +0000222 bool HasVAListArg = Format->getFirstArg() == 0;
Douglas Gregor3c385e52009-02-14 18:57:46 +0000223 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
Ted Kremenek3d692df2009-02-27 17:58:43 +0000224 HasVAListArg ? 0 : Format->getFirstArg() - 1);
Douglas Gregor3c385e52009-02-14 18:57:46 +0000225 }
Chris Lattner59907c42007-08-10 20:18:51 +0000226 }
Mike Stump1eb44332009-09-09 15:08:12 +0000227
228 for (const NonNullAttr *NonNull = FDecl->getAttr<NonNullAttr>(); NonNull;
Anders Carlssond406bf02009-08-16 01:56:34 +0000229 NonNull = NonNull->getNext<NonNullAttr>())
230 CheckNonNullArguments(NonNull, TheCall);
Sebastian Redl0eb23302009-01-19 00:08:26 +0000231
Anders Carlssond406bf02009-08-16 01:56:34 +0000232 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000233}
234
Anders Carlssond406bf02009-08-16 01:56:34 +0000235bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000236 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000237 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000238 if (!Format)
Anders Carlssond406bf02009-08-16 01:56:34 +0000239 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000240
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000241 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
242 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000243 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000244
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000245 QualType Ty = V->getType();
246 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000247 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000248
Anders Carlssond406bf02009-08-16 01:56:34 +0000249 if (!CheckablePrintfAttr(Format, TheCall))
250 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000251
Anders Carlssond406bf02009-08-16 01:56:34 +0000252 bool HasVAListArg = Format->getFirstArg() == 0;
Anders Carlssond406bf02009-08-16 01:56:34 +0000253 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
254 HasVAListArg ? 0 : Format->getFirstArg() - 1);
255
256 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000257}
258
Chris Lattner5caa3702009-05-08 06:58:22 +0000259/// SemaBuiltinAtomicOverloaded - We have a call to a function like
260/// __sync_fetch_and_add, which is an overloaded function based on the pointer
261/// type of its first argument. The main ActOnCallExpr routines have already
262/// promoted the types of arguments because all of these calls are prototyped as
263/// void(...).
264///
265/// This function goes through and does final semantic checking for these
266/// builtins,
267bool Sema::SemaBuiltinAtomicOverloaded(CallExpr *TheCall) {
268 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
269 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
270
271 // Ensure that we have at least one argument to do type inference from.
272 if (TheCall->getNumArgs() < 1)
273 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
274 << 0 << TheCall->getCallee()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000275
Chris Lattner5caa3702009-05-08 06:58:22 +0000276 // Inspect the first argument of the atomic builtin. This should always be
277 // a pointer type, whose element is an integral scalar or pointer type.
278 // Because it is a pointer type, we don't have to worry about any implicit
279 // casts here.
280 Expr *FirstArg = TheCall->getArg(0);
281 if (!FirstArg->getType()->isPointerType())
282 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
283 << FirstArg->getType() << FirstArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000284
Ted Kremenek6217b802009-07-29 21:53:49 +0000285 QualType ValType = FirstArg->getType()->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000286 if (!ValType->isIntegerType() && !ValType->isPointerType() &&
Chris Lattner5caa3702009-05-08 06:58:22 +0000287 !ValType->isBlockPointerType())
288 return Diag(DRE->getLocStart(),
289 diag::err_atomic_builtin_must_be_pointer_intptr)
290 << FirstArg->getType() << FirstArg->getSourceRange();
291
292 // We need to figure out which concrete builtin this maps onto. For example,
293 // __sync_fetch_and_add with a 2 byte object turns into
294 // __sync_fetch_and_add_2.
295#define BUILTIN_ROW(x) \
296 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
297 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000298
Chris Lattner5caa3702009-05-08 06:58:22 +0000299 static const unsigned BuiltinIndices[][5] = {
300 BUILTIN_ROW(__sync_fetch_and_add),
301 BUILTIN_ROW(__sync_fetch_and_sub),
302 BUILTIN_ROW(__sync_fetch_and_or),
303 BUILTIN_ROW(__sync_fetch_and_and),
304 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +0000305
Chris Lattner5caa3702009-05-08 06:58:22 +0000306 BUILTIN_ROW(__sync_add_and_fetch),
307 BUILTIN_ROW(__sync_sub_and_fetch),
308 BUILTIN_ROW(__sync_and_and_fetch),
309 BUILTIN_ROW(__sync_or_and_fetch),
310 BUILTIN_ROW(__sync_xor_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;
Ken Dyck199c3d62010-01-11 17:06:35 +0000321 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000322 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;
Mike Stump1eb44332009-09-09 15:08:12 +0000345
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000346 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
347 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
348 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
349 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 8; break;
350 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000351
Chris Lattner5caa3702009-05-08 06:58:22 +0000352 case Builtin::BI__sync_val_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000353 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +0000354 NumFixed = 2;
355 break;
356 case Builtin::BI__sync_bool_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000357 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +0000358 NumFixed = 2;
359 break;
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000360 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000361 case Builtin::BI__sync_lock_release:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000362 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000363 NumFixed = 0;
364 break;
365 }
Mike Stump1eb44332009-09-09 15:08:12 +0000366
Chris Lattner5caa3702009-05-08 06:58:22 +0000367 // Now that we know how many fixed arguments we expect, first check that we
368 // have at least that many.
369 if (TheCall->getNumArgs() < 1+NumFixed)
370 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
371 << 0 << TheCall->getCallee()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000372
373
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000374 // Get the decl for the concrete builtin from this, we can tell what the
375 // concrete integer type we should convert to is.
376 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
377 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
378 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +0000379 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000380 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
381 TUScope, false, DRE->getLocStart()));
382 const FunctionProtoType *BuiltinFT =
John McCall183700f2009-09-21 23:43:11 +0000383 NewBuiltinDecl->getType()->getAs<FunctionProtoType>();
Ted Kremenek6217b802009-07-29 21:53:49 +0000384 ValType = BuiltinFT->getArgType(0)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000385
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000386 // If the first type needs to be converted (e.g. void** -> int*), do it now.
387 if (BuiltinFT->getArgType(0) != FirstArg->getType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +0000388 ImpCastExprToType(FirstArg, BuiltinFT->getArgType(0), CastExpr::CK_BitCast);
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000389 TheCall->setArg(0, FirstArg);
390 }
Mike Stump1eb44332009-09-09 15:08:12 +0000391
Chris Lattner5caa3702009-05-08 06:58:22 +0000392 // Next, walk the valid ones promoting to the right type.
393 for (unsigned i = 0; i != NumFixed; ++i) {
394 Expr *Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +0000395
Chris Lattner5caa3702009-05-08 06:58:22 +0000396 // If the argument is an implicit cast, then there was a promotion due to
397 // "...", just remove it now.
398 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
399 Arg = ICE->getSubExpr();
400 ICE->setSubExpr(0);
401 ICE->Destroy(Context);
402 TheCall->setArg(i+1, Arg);
403 }
Mike Stump1eb44332009-09-09 15:08:12 +0000404
Chris Lattner5caa3702009-05-08 06:58:22 +0000405 // GCC does an implicit conversion to the pointer or integer ValType. This
406 // can fail in some cases (1i -> int**), check for this error case now.
Anders Carlssoncdb61972009-08-07 22:21:05 +0000407 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000408 CXXMethodDecl *ConversionDecl = 0;
409 if (CheckCastTypes(Arg->getSourceRange(), ValType, Arg, Kind,
410 ConversionDecl))
Chris Lattner5caa3702009-05-08 06:58:22 +0000411 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000412
Chris Lattner5caa3702009-05-08 06:58:22 +0000413 // Okay, we have something that *can* be converted to the right type. Check
414 // to see if there is a potentially weird extension going on here. This can
415 // happen when you do an atomic operation on something like an char* and
416 // pass in 42. The 42 gets converted to char. This is even more strange
417 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +0000418 // FIXME: Do this check.
Anders Carlssoncdb61972009-08-07 22:21:05 +0000419 ImpCastExprToType(Arg, ValType, Kind, /*isLvalue=*/false);
Chris Lattner5caa3702009-05-08 06:58:22 +0000420 TheCall->setArg(i+1, Arg);
421 }
Mike Stump1eb44332009-09-09 15:08:12 +0000422
Chris Lattner5caa3702009-05-08 06:58:22 +0000423 // Switch the DeclRefExpr to refer to the new decl.
424 DRE->setDecl(NewBuiltinDecl);
425 DRE->setType(NewBuiltinDecl->getType());
Mike Stump1eb44332009-09-09 15:08:12 +0000426
Chris Lattner5caa3702009-05-08 06:58:22 +0000427 // Set the callee in the CallExpr.
428 // FIXME: This leaks the original parens and implicit casts.
429 Expr *PromotedCall = DRE;
430 UsualUnaryConversions(PromotedCall);
431 TheCall->setCallee(PromotedCall);
Mike Stump1eb44332009-09-09 15:08:12 +0000432
Chris Lattner5caa3702009-05-08 06:58:22 +0000433
434 // Change the result type of the call to match the result type of the decl.
435 TheCall->setType(NewBuiltinDecl->getResultType());
436 return false;
437}
438
439
Chris Lattner69039812009-02-18 06:01:06 +0000440/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000441/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +0000442/// FIXME: GCC currently emits the following warning:
Mike Stump1eb44332009-09-09 15:08:12 +0000443/// "warning: input conversion stopped due to an input byte that does not
Steve Narofffd942622009-04-13 20:26:29 +0000444/// belong to the input codeset UTF-8"
445/// Note: It might also make sense to do the UTF-16 conversion here (would
446/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +0000447bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000448 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000449 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
450
451 if (!Literal || Literal->isWide()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000452 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
453 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000454 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000455 }
Mike Stump1eb44332009-09-09 15:08:12 +0000456
Daniel Dunbarf015b032009-09-22 10:03:52 +0000457 const char *Data = Literal->getStrData();
458 unsigned Length = Literal->getByteLength();
Mike Stump1eb44332009-09-09 15:08:12 +0000459
Daniel Dunbarf015b032009-09-22 10:03:52 +0000460 for (unsigned i = 0; i < Length; ++i) {
461 if (!Data[i]) {
462 Diag(getLocationOfStringLiteralByte(Literal, i),
463 diag::warn_cfstring_literal_contains_nul_character)
464 << Arg->getSourceRange();
465 break;
466 }
467 }
Mike Stump1eb44332009-09-09 15:08:12 +0000468
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000469 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000470}
471
Chris Lattnerc27c6652007-12-20 00:05:45 +0000472/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
473/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000474bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
475 Expr *Fn = TheCall->getCallee();
476 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000477 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000478 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000479 << 0 /*function call*/ << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +0000480 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000481 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000482 return true;
483 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000484
485 if (TheCall->getNumArgs() < 2) {
486 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
487 << 0 /*function call*/;
488 }
489
Chris Lattnerc27c6652007-12-20 00:05:45 +0000490 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000491 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +0000492 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000493 if (CurBlock)
494 isVariadic = CurBlock->isVariadic;
495 else if (getCurFunctionDecl()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000496 if (FunctionProtoType* FTP =
497 dyn_cast<FunctionProtoType>(getCurFunctionDecl()->getType()))
Eli Friedman56f20ae2008-12-15 22:05:35 +0000498 isVariadic = FTP->isVariadic();
499 else
500 isVariadic = false;
501 } else {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000502 isVariadic = getCurMethodDecl()->isVariadic();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000503 }
Mike Stump1eb44332009-09-09 15:08:12 +0000504
Chris Lattnerc27c6652007-12-20 00:05:45 +0000505 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000506 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
507 return true;
508 }
Mike Stump1eb44332009-09-09 15:08:12 +0000509
Chris Lattner30ce3442007-12-19 23:59:04 +0000510 // Verify that the second argument to the builtin is the last argument of the
511 // current function or method.
512 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000513 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +0000514
Anders Carlsson88cf2262008-02-11 04:20:54 +0000515 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
516 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000517 // FIXME: This isn't correct for methods (results in bogus warning).
518 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000519 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000520 if (CurBlock)
521 LastArg = *(CurBlock->TheDecl->param_end()-1);
522 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +0000523 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000524 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000525 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000526 SecondArgIsLastNamedArgument = PV == LastArg;
527 }
528 }
Mike Stump1eb44332009-09-09 15:08:12 +0000529
Chris Lattner30ce3442007-12-19 23:59:04 +0000530 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +0000531 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000532 diag::warn_second_parameter_of_va_start_not_last_named_argument);
533 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000534}
Chris Lattner30ce3442007-12-19 23:59:04 +0000535
Chris Lattner1b9a0792007-12-20 00:26:33 +0000536/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
537/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000538bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
539 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000540 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
541 << 0 /*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000542 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +0000543 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000544 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000545 << 0 /*function call*/
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000546 << SourceRange(TheCall->getArg(2)->getLocStart(),
547 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000548
Chris Lattner925e60d2007-12-28 05:29:59 +0000549 Expr *OrigArg0 = TheCall->getArg(0);
550 Expr *OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000551
Chris Lattner1b9a0792007-12-20 00:26:33 +0000552 // Do standard promotions between the two arguments, returning their common
553 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000554 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Daniel Dunbar403bc2b2009-02-19 19:28:43 +0000555
556 // Make sure any conversions are pushed back into the call; this is
557 // type safe since unordered compare builtins are declared as "_Bool
558 // foo(...)".
559 TheCall->setArg(0, OrigArg0);
560 TheCall->setArg(1, OrigArg1);
Mike Stump1eb44332009-09-09 15:08:12 +0000561
Douglas Gregorcde01732009-05-19 22:10:17 +0000562 if (OrigArg0->isTypeDependent() || OrigArg1->isTypeDependent())
563 return false;
564
Chris Lattner1b9a0792007-12-20 00:26:33 +0000565 // If the common type isn't a real floating type, then the arguments were
566 // invalid for this operation.
567 if (!Res->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000568 return Diag(OrigArg0->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000569 diag::err_typecheck_call_invalid_ordered_compare)
Chris Lattnerd1625842008-11-24 06:25:27 +0000570 << OrigArg0->getType() << OrigArg1->getType()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000571 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000572
Chris Lattner1b9a0792007-12-20 00:26:33 +0000573 return false;
574}
575
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000576/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
577/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000578/// to check everything. We expect the last argument to be a floating point
579/// value.
580bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
581 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +0000582 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
583 << 0 /*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000584 if (TheCall->getNumArgs() > NumArgs)
585 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000586 diag::err_typecheck_call_too_many_args)
587 << 0 /*function call*/
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000588 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000589 (*(TheCall->arg_end()-1))->getLocEnd());
590
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000591 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +0000592
Eli Friedman9ac6f622009-08-31 20:06:00 +0000593 if (OrigArg->isTypeDependent())
594 return false;
595
596 // This operation requires a floating-point number
597 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000598 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000599 diag::err_typecheck_call_invalid_unary_fp)
600 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000601
Eli Friedman9ac6f622009-08-31 20:06:00 +0000602 return false;
603}
604
Eli Friedman6cfda232008-05-20 08:23:37 +0000605bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) {
606 // The signature for these builtins is exact; the only thing we need
607 // to check is that the argument is a constant.
608 SourceLocation Loc;
Douglas Gregorcde01732009-05-19 22:10:17 +0000609 if (!TheCall->getArg(0)->isTypeDependent() &&
610 !TheCall->getArg(0)->isValueDependent() &&
611 !TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc))
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000612 return Diag(Loc, diag::err_stack_const_level) << TheCall->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000613
Eli Friedman6cfda232008-05-20 08:23:37 +0000614 return false;
615}
616
Eli Friedmand38617c2008-05-14 19:38:39 +0000617/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
618// This is declared to take (...), so we have to check everything.
Sebastian Redl0eb23302009-01-19 00:08:26 +0000619Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000620 if (TheCall->getNumArgs() < 3)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000621 return ExprError(Diag(TheCall->getLocEnd(),
622 diag::err_typecheck_call_too_few_args)
623 << 0 /*function call*/ << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000624
Douglas Gregorcde01732009-05-19 22:10:17 +0000625 unsigned numElements = std::numeric_limits<unsigned>::max();
626 if (!TheCall->getArg(0)->isTypeDependent() &&
627 !TheCall->getArg(1)->isTypeDependent()) {
628 QualType FAType = TheCall->getArg(0)->getType();
629 QualType SAType = TheCall->getArg(1)->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000630
Douglas Gregorcde01732009-05-19 22:10:17 +0000631 if (!FAType->isVectorType() || !SAType->isVectorType()) {
632 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000633 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000634 TheCall->getArg(1)->getLocEnd());
635 return ExprError();
636 }
Mike Stump1eb44332009-09-09 15:08:12 +0000637
Douglas Gregora4923eb2009-11-16 21:35:15 +0000638 if (!Context.hasSameUnqualifiedType(FAType, SAType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000639 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000640 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000641 TheCall->getArg(1)->getLocEnd());
642 return ExprError();
643 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000644
John McCall183700f2009-09-21 23:43:11 +0000645 numElements = FAType->getAs<VectorType>()->getNumElements();
Douglas Gregorcde01732009-05-19 22:10:17 +0000646 if (TheCall->getNumArgs() != numElements+2) {
647 if (TheCall->getNumArgs() < numElements+2)
648 return ExprError(Diag(TheCall->getLocEnd(),
649 diag::err_typecheck_call_too_few_args)
650 << 0 /*function call*/ << TheCall->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000651 return ExprError(Diag(TheCall->getLocEnd(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000652 diag::err_typecheck_call_too_many_args)
653 << 0 /*function call*/ << TheCall->getSourceRange());
654 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000655 }
656
657 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000658 if (TheCall->getArg(i)->isTypeDependent() ||
659 TheCall->getArg(i)->isValueDependent())
660 continue;
661
Eli Friedmand38617c2008-05-14 19:38:39 +0000662 llvm::APSInt Result(32);
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000663 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000664 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000665 diag::err_shufflevector_nonconstant_argument)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000666 << TheCall->getArg(i)->getSourceRange());
667
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000668 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000669 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000670 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000671 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000672 }
673
674 llvm::SmallVector<Expr*, 32> exprs;
675
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000676 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000677 exprs.push_back(TheCall->getArg(i));
678 TheCall->setArg(i, 0);
679 }
680
Nate Begemana88dc302009-08-12 02:10:25 +0000681 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
682 exprs.size(), exprs[0]->getType(),
Ted Kremenek8189cde2009-02-07 01:47:29 +0000683 TheCall->getCallee()->getLocStart(),
684 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000685}
Chris Lattner30ce3442007-12-19 23:59:04 +0000686
Daniel Dunbar4493f792008-07-21 22:59:13 +0000687/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
688// This is declared to take (const void*, ...) and can take two
689// optional constant int args.
690bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000691 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000692
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000693 if (NumArgs > 3)
694 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000695 << 0 /*function call*/ << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000696
697 // Argument 0 is checked for us and the remaining arguments must be
698 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000699 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000700 Expr *Arg = TheCall->getArg(i);
Douglas Gregorcde01732009-05-19 22:10:17 +0000701 if (Arg->isTypeDependent())
702 continue;
703
Eli Friedman9aef7262009-12-04 00:30:06 +0000704 if (!Arg->getType()->isIntegralType())
705 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_arg_type)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000706 << Arg->getSourceRange();
Douglas Gregorcde01732009-05-19 22:10:17 +0000707
Eli Friedman9aef7262009-12-04 00:30:06 +0000708 ImpCastExprToType(Arg, Context.IntTy, CastExpr::CK_IntegralCast);
709 TheCall->setArg(i, Arg);
710
Douglas Gregorcde01732009-05-19 22:10:17 +0000711 if (Arg->isValueDependent())
712 continue;
713
Eli Friedman9aef7262009-12-04 00:30:06 +0000714 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +0000715 if (!Arg->isIntegerConstantExpr(Result, Context))
Eli Friedman9aef7262009-12-04 00:30:06 +0000716 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_arg_ice)
Douglas Gregorcde01732009-05-19 22:10:17 +0000717 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000718
Daniel Dunbar4493f792008-07-21 22:59:13 +0000719 // FIXME: gcc issues a warning and rewrites these to 0. These
720 // seems especially odd for the third argument since the default
721 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000722 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +0000723 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000724 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000725 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000726 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +0000727 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000728 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000729 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000730 }
731 }
732
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000733 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000734}
735
Chris Lattner21fb98e2009-09-23 06:06:36 +0000736/// SemaBuiltinEHReturnDataRegNo - Handle __builtin_eh_return_data_regno, the
737/// operand must be an integer constant.
738bool Sema::SemaBuiltinEHReturnDataRegNo(CallExpr *TheCall) {
739 llvm::APSInt Result;
740 if (!TheCall->getArg(0)->isIntegerConstantExpr(Result, Context))
741 return Diag(TheCall->getLocStart(), diag::err_expr_not_ice)
742 << TheCall->getArg(0)->getSourceRange();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +0000743
Chris Lattner21fb98e2009-09-23 06:06:36 +0000744 return false;
745}
746
747
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000748/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
749/// int type). This simply type checks that type is one of the defined
750/// constants (0-3).
Eric Christopherfee667f2009-12-23 03:49:37 +0000751// For compatability check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000752bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
753 Expr *Arg = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000754 if (Arg->isTypeDependent())
755 return false;
756
Mike Stump1eb44332009-09-09 15:08:12 +0000757 QualType ArgType = Arg->getType();
John McCall183700f2009-09-21 23:43:11 +0000758 const BuiltinType *BT = ArgType->getAs<BuiltinType>();
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000759 llvm::APSInt Result(32);
Douglas Gregorcde01732009-05-19 22:10:17 +0000760 if (!BT || BT->getKind() != BuiltinType::Int)
761 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
762 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
763
764 if (Arg->isValueDependent())
765 return false;
766
767 if (!Arg->isIntegerConstantExpr(Result, Context)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000768 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
769 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000770 }
771
772 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000773 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
774 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000775 }
776
777 return false;
778}
779
Eli Friedman586d6a82009-05-03 06:04:26 +0000780/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +0000781/// This checks that val is a constant 1.
782bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
783 Expr *Arg = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000784 if (Arg->isTypeDependent() || Arg->isValueDependent())
785 return false;
786
Eli Friedmand875fed2009-05-03 04:46:36 +0000787 llvm::APSInt Result(32);
788 if (!Arg->isIntegerConstantExpr(Result, Context) || Result != 1)
789 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
790 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
791
792 return false;
793}
794
Ted Kremenekd30ef872009-01-12 23:09:09 +0000795// Handle i > 1 ? "x" : "y", recursivelly
Ted Kremenek082d9362009-03-20 21:35:28 +0000796bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
797 bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000798 unsigned format_idx, unsigned firstDataArg) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000799 if (E->isTypeDependent() || E->isValueDependent())
800 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000801
802 switch (E->getStmtClass()) {
803 case Stmt::ConditionalOperatorClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000804 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Chris Lattner813b70d2009-12-22 06:00:13 +0000805 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000806 HasVAListArg, format_idx, firstDataArg)
Ted Kremenekd30ef872009-01-12 23:09:09 +0000807 && SemaCheckStringLiteral(C->getRHS(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000808 HasVAListArg, format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000809 }
810
811 case Stmt::ImplicitCastExprClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000812 const ImplicitCastExpr *Expr = cast<ImplicitCastExpr>(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 }
816
817 case Stmt::ParenExprClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000818 const ParenExpr *Expr = cast<ParenExpr>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000819 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000820 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000821 }
Mike Stump1eb44332009-09-09 15:08:12 +0000822
Ted Kremenek082d9362009-03-20 21:35:28 +0000823 case Stmt::DeclRefExprClass: {
824 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000825
Ted Kremenek082d9362009-03-20 21:35:28 +0000826 // As an exception, do not flag errors for variables binding to
827 // const string literals.
828 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
829 bool isConstant = false;
830 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +0000831
Ted Kremenek082d9362009-03-20 21:35:28 +0000832 if (const ArrayType *AT = Context.getAsArrayType(T)) {
833 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000834 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000835 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +0000836 PT->getPointeeType().isConstant(Context);
837 }
Mike Stump1eb44332009-09-09 15:08:12 +0000838
Ted Kremenek082d9362009-03-20 21:35:28 +0000839 if (isConstant) {
Sebastian Redl31310a22010-02-01 20:16:42 +0000840 if (const Expr *Init = VD->getAnyInitializer())
Ted Kremenek082d9362009-03-20 21:35:28 +0000841 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);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +0000919 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +0000920 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///
Ted Kremenek7f70dc82010-02-26 19:18:41 +0000942/// TODO:
Ted Kremenek71895b92007-08-14 17:39:48 +0000943/// Functionality implemented:
944///
945/// We can statically check the following properties for string
946/// literal format strings for non v.*printf functions (where the
947/// arguments are passed directly):
948//
949/// (1) Are the number of format conversions equal to the number of
950/// data arguments?
951///
952/// (2) Does each format conversion correctly match the type of the
Ted Kremenek7f70dc82010-02-26 19:18:41 +0000953/// corresponding data argument?
Ted Kremenek71895b92007-08-14 17:39:48 +0000954///
955/// Moreover, for all printf functions we can:
956///
957/// (3) Check for a missing format string (when not caught by type checking).
958///
959/// (4) Check for no-operation flags; e.g. using "#" with format
960/// conversion 'c' (TODO)
961///
962/// (5) Check the use of '%n', a major source of security holes.
963///
964/// (6) Check for malformed format conversions that don't specify anything.
965///
966/// (7) Check for empty format strings. e.g: printf("");
967///
968/// (8) Check that the format string is a wide literal.
969///
970/// All of these checks can be done by parsing the format string.
971///
Chris Lattner59907c42007-08-10 20:18:51 +0000972void
Mike Stump1eb44332009-09-09 15:08:12 +0000973Sema::CheckPrintfArguments(const CallExpr *TheCall, bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000974 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenek082d9362009-03-20 21:35:28 +0000975 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +0000976
Sebastian Redl4a2614e2009-11-17 18:02:24 +0000977 // The way the format attribute works in GCC, the implicit this argument
978 // of member functions is counted. However, it doesn't appear in our own
979 // lists, so decrement format_idx in that case.
980 if (isa<CXXMemberCallExpr>(TheCall)) {
981 // Catch a format attribute mistakenly referring to the object argument.
982 if (format_idx == 0)
983 return;
984 --format_idx;
985 if(firstDataArg != 0)
986 --firstDataArg;
987 }
988
Mike Stump1eb44332009-09-09 15:08:12 +0000989 // CHECK: printf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +0000990 if (format_idx >= TheCall->getNumArgs()) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000991 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string)
992 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +0000993 return;
994 }
Mike Stump1eb44332009-09-09 15:08:12 +0000995
Ted Kremenek082d9362009-03-20 21:35:28 +0000996 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +0000997
Chris Lattner59907c42007-08-10 20:18:51 +0000998 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +0000999 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001000 // Dynamically generated format strings are difficult to
1001 // automatically vet at compile time. Requiring that format strings
1002 // are string literals: (1) permits the checking of format strings by
1003 // the compiler and thereby (2) can practically remove the source of
1004 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001005
Mike Stump1eb44332009-09-09 15:08:12 +00001006 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001007 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001008 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001009 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001010 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
1011 firstDataArg))
1012 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001013
Chris Lattner655f1412009-04-29 04:59:47 +00001014 // If there are no arguments specified, warn with -Wformat-security, otherwise
1015 // warn only with -Wformat-nonliteral.
1016 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump1eb44332009-09-09 15:08:12 +00001017 Diag(TheCall->getArg(format_idx)->getLocStart(),
Chris Lattner655f1412009-04-29 04:59:47 +00001018 diag::warn_printf_nonliteral_noargs)
1019 << OrigFormatExpr->getSourceRange();
1020 else
Mike Stump1eb44332009-09-09 15:08:12 +00001021 Diag(TheCall->getArg(format_idx)->getLocStart(),
Chris Lattner655f1412009-04-29 04:59:47 +00001022 diag::warn_printf_nonliteral)
1023 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001024}
Ted Kremenek71895b92007-08-14 17:39:48 +00001025
Ted Kremeneke0e53132010-01-28 23:39:18 +00001026namespace {
Ted Kremenek74d56a12010-02-04 20:46:58 +00001027class CheckPrintfHandler : public analyze_printf::FormatStringHandler {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001028 Sema &S;
1029 const StringLiteral *FExpr;
1030 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001031 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001032 const unsigned NumDataArgs;
1033 const bool IsObjCLiteral;
1034 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001035 const bool HasVAListArg;
1036 const CallExpr *TheCall;
1037 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001038 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001039 bool usesPositionalArgs;
1040 bool atFirstArg;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001041public:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001042 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001043 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001044 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001045 const char *beg, bool hasVAListArg,
1046 const CallExpr *theCall, unsigned formatIdx)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001047 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek6ee76532010-03-25 03:59:12 +00001048 FirstDataArg(firstDataArg),
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001049 NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001050 IsObjCLiteral(isObjCLiteral), Beg(beg),
1051 HasVAListArg(hasVAListArg),
Ted Kremenekefaff192010-02-27 01:41:03 +00001052 TheCall(theCall), FormatIdx(formatIdx),
1053 usesPositionalArgs(false), atFirstArg(true) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001054 CoveredArgs.resize(numDataArgs);
1055 CoveredArgs.reset();
1056 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001057
Ted Kremenek07d161f2010-01-29 01:50:07 +00001058 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001059
Ted Kremenek808015a2010-01-29 03:16:21 +00001060 void HandleIncompleteFormatSpecifier(const char *startSpecifier,
1061 unsigned specifierLen);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001062
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001063 bool
Ted Kremenek74d56a12010-02-04 20:46:58 +00001064 HandleInvalidConversionSpecifier(const analyze_printf::FormatSpecifier &FS,
1065 const char *startSpecifier,
1066 unsigned specifierLen);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001067
Ted Kremenekefaff192010-02-27 01:41:03 +00001068 virtual void HandleInvalidPosition(const char *startSpecifier,
1069 unsigned specifierLen,
1070 analyze_printf::PositionContext p);
1071
1072 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1073
Ted Kremeneke0e53132010-01-28 23:39:18 +00001074 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001075
Ted Kremeneke0e53132010-01-28 23:39:18 +00001076 bool HandleFormatSpecifier(const analyze_printf::FormatSpecifier &FS,
1077 const char *startSpecifier,
1078 unsigned specifierLen);
1079private:
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001080 SourceRange getFormatStringRange();
1081 SourceRange getFormatSpecifierRange(const char *startSpecifier,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001082 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001083 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001084
Ted Kremenekefaff192010-02-27 01:41:03 +00001085 bool HandleAmount(const analyze_printf::OptionalAmount &Amt, unsigned k,
1086 const char *startSpecifier, unsigned specifierLen);
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001087 void HandleFlags(const analyze_printf::FormatSpecifier &FS,
1088 llvm::StringRef flag, llvm::StringRef cspec,
1089 const char *startSpecifier, unsigned specifierLen);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001090
Ted Kremenek0d277352010-01-29 01:06:55 +00001091 const Expr *getDataArg(unsigned i) const;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001092};
1093}
1094
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001095SourceRange CheckPrintfHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001096 return OrigFormatExpr->getSourceRange();
1097}
1098
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001099SourceRange CheckPrintfHandler::
1100getFormatSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
1101 return SourceRange(getLocationOfByte(startSpecifier),
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001102 getLocationOfByte(startSpecifier+specifierLen-1));
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001103}
1104
Ted Kremeneke0e53132010-01-28 23:39:18 +00001105SourceLocation CheckPrintfHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001106 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001107}
1108
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001109void CheckPrintfHandler::
Ted Kremenek808015a2010-01-29 03:16:21 +00001110HandleIncompleteFormatSpecifier(const char *startSpecifier,
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001111 unsigned specifierLen) {
Ted Kremenek808015a2010-01-29 03:16:21 +00001112 SourceLocation Loc = getLocationOfByte(startSpecifier);
1113 S.Diag(Loc, diag::warn_printf_incomplete_specifier)
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001114 << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek808015a2010-01-29 03:16:21 +00001115}
1116
Ted Kremenekefaff192010-02-27 01:41:03 +00001117void
1118CheckPrintfHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1119 analyze_printf::PositionContext p) {
1120 SourceLocation Loc = getLocationOfByte(startPos);
1121 S.Diag(Loc, diag::warn_printf_invalid_positional_specifier)
1122 << (unsigned) p << getFormatSpecifierRange(startPos, posLen);
1123}
1124
1125void CheckPrintfHandler::HandleZeroPosition(const char *startPos,
1126 unsigned posLen) {
1127 SourceLocation Loc = getLocationOfByte(startPos);
1128 S.Diag(Loc, diag::warn_printf_zero_positional_specifier)
1129 << getFormatSpecifierRange(startPos, posLen);
1130}
1131
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001132bool CheckPrintfHandler::
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001133HandleInvalidConversionSpecifier(const analyze_printf::FormatSpecifier &FS,
1134 const char *startSpecifier,
1135 unsigned specifierLen) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001136
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001137 unsigned argIndex = FS.getArgIndex();
1138 bool keepGoing = true;
1139 if (argIndex < NumDataArgs) {
1140 // Consider the argument coverered, even though the specifier doesn't
1141 // make sense.
1142 CoveredArgs.set(argIndex);
1143 }
1144 else {
1145 // If argIndex exceeds the number of data arguments we
1146 // don't issue a warning because that is just a cascade of warnings (and
1147 // they may have intended '%%' anyway). We don't want to continue processing
1148 // the format string after this point, however, as we will like just get
1149 // gibberish when trying to match arguments.
1150 keepGoing = false;
1151 }
1152
Ted Kremenek808015a2010-01-29 03:16:21 +00001153 const analyze_printf::ConversionSpecifier &CS =
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001154 FS.getConversionSpecifier();
Ted Kremenek808015a2010-01-29 03:16:21 +00001155 SourceLocation Loc = getLocationOfByte(CS.getStart());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001156 S.Diag(Loc, diag::warn_printf_invalid_conversion)
Ted Kremenek808015a2010-01-29 03:16:21 +00001157 << llvm::StringRef(CS.getStart(), CS.getLength())
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001158 << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001159
1160 return keepGoing;
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001161}
1162
Ted Kremeneke0e53132010-01-28 23:39:18 +00001163void CheckPrintfHandler::HandleNullChar(const char *nullCharacter) {
1164 // The presence of a null character is likely an error.
1165 S.Diag(getLocationOfByte(nullCharacter),
1166 diag::warn_printf_format_string_contains_null_char)
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001167 << getFormatStringRange();
Ted Kremeneke0e53132010-01-28 23:39:18 +00001168}
1169
Ted Kremenek0d277352010-01-29 01:06:55 +00001170const Expr *CheckPrintfHandler::getDataArg(unsigned i) const {
Ted Kremenek6ee76532010-03-25 03:59:12 +00001171 return TheCall->getArg(FirstDataArg + i);
Ted Kremenek0d277352010-01-29 01:06:55 +00001172}
1173
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001174void CheckPrintfHandler::HandleFlags(const analyze_printf::FormatSpecifier &FS,
1175 llvm::StringRef flag,
1176 llvm::StringRef cspec,
1177 const char *startSpecifier,
1178 unsigned specifierLen) {
1179 const analyze_printf::ConversionSpecifier &CS = FS.getConversionSpecifier();
1180 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_nonsensical_flag)
1181 << flag << cspec << getFormatSpecifierRange(startSpecifier, specifierLen);
1182}
1183
Ted Kremenek0d277352010-01-29 01:06:55 +00001184bool
1185CheckPrintfHandler::HandleAmount(const analyze_printf::OptionalAmount &Amt,
Ted Kremenekefaff192010-02-27 01:41:03 +00001186 unsigned k, const char *startSpecifier,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001187 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001188
1189 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001190 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001191 unsigned argIndex = Amt.getArgIndex();
1192 if (argIndex >= NumDataArgs) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001193 S.Diag(getLocationOfByte(Amt.getStart()),
1194 diag::warn_printf_asterisk_missing_arg)
1195 << k << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek0d277352010-01-29 01:06:55 +00001196 // Don't do any more checking. We will just emit
1197 // spurious errors.
1198 return false;
1199 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001200
Ted Kremenek0d277352010-01-29 01:06:55 +00001201 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00001202 // Although not in conformance with C99, we also allow the argument to be
1203 // an 'unsigned int' as that is a reasonably safe case. GCC also
1204 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001205 CoveredArgs.set(argIndex);
1206 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00001207 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001208
1209 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1210 assert(ATR.isValid());
1211
1212 if (!ATR.matchesType(S.Context, T)) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001213 S.Diag(getLocationOfByte(Amt.getStart()),
1214 diag::warn_printf_asterisk_wrong_type)
1215 << k
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001216 << ATR.getRepresentativeType(S.Context) << T
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001217 << getFormatSpecifierRange(startSpecifier, specifierLen)
1218 << Arg->getSourceRange();
Ted Kremenek0d277352010-01-29 01:06:55 +00001219 // Don't do any more checking. We will just emit
1220 // spurious errors.
1221 return false;
1222 }
1223 }
1224 }
1225 return true;
1226}
Ted Kremenek0d277352010-01-29 01:06:55 +00001227
Ted Kremeneke0e53132010-01-28 23:39:18 +00001228bool
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001229CheckPrintfHandler::HandleFormatSpecifier(const analyze_printf::FormatSpecifier
1230 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001231 const char *startSpecifier,
1232 unsigned specifierLen) {
1233
Ted Kremenekefaff192010-02-27 01:41:03 +00001234 using namespace analyze_printf;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001235 const ConversionSpecifier &CS = FS.getConversionSpecifier();
1236
Ted Kremenekefaff192010-02-27 01:41:03 +00001237 if (atFirstArg) {
1238 atFirstArg = false;
1239 usesPositionalArgs = FS.usesPositionalArg();
1240 }
1241 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1242 // Cannot mix-and-match positional and non-positional arguments.
1243 S.Diag(getLocationOfByte(CS.getStart()),
1244 diag::warn_printf_mix_positional_nonpositional_args)
1245 << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek0d277352010-01-29 01:06:55 +00001246 return false;
1247 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001248
Ted Kremenekefaff192010-02-27 01:41:03 +00001249 // First check if the field width, precision, and conversion specifier
1250 // have matching data arguments.
1251 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1252 startSpecifier, specifierLen)) {
1253 return false;
1254 }
1255
1256 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1257 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001258 return false;
1259 }
1260
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001261 if (!CS.consumesDataArgument()) {
1262 // FIXME: Technically specifying a precision or field width here
1263 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001264 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001265 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001266
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001267 // Consume the argument.
1268 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00001269 if (argIndex < NumDataArgs) {
1270 // The check to see if the argIndex is valid will come later.
1271 // We set the bit here because we may exit early from this
1272 // function if we encounter some other error.
1273 CoveredArgs.set(argIndex);
1274 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001275
1276 // Check for using an Objective-C specific conversion specifier
1277 // in a non-ObjC literal.
1278 if (!IsObjCLiteral && CS.isObjCArg()) {
1279 return HandleInvalidConversionSpecifier(FS, startSpecifier, specifierLen);
1280 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001281
Ted Kremeneke82d8042010-01-29 01:35:25 +00001282 // Are we using '%n'? Issue a warning about this being
1283 // a possible security issue.
1284 if (CS.getKind() == ConversionSpecifier::OutIntPtrArg) {
1285 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001286 << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremeneke82d8042010-01-29 01:35:25 +00001287 // Continue checking the other format specifiers.
1288 return true;
1289 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001290
1291 if (CS.getKind() == ConversionSpecifier::VoidPtrArg) {
1292 if (FS.getPrecision().getHowSpecified() != OptionalAmount::NotSpecified)
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001293 S.Diag(getLocationOfByte(CS.getStart()),
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001294 diag::warn_printf_nonsensical_precision)
1295 << CS.getCharacters()
1296 << getFormatSpecifierRange(startSpecifier, specifierLen);
1297 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001298 if (CS.getKind() == ConversionSpecifier::VoidPtrArg ||
1299 CS.getKind() == ConversionSpecifier::CStrArg) {
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001300 // FIXME: Instead of using "0", "+", etc., eventually get them from
1301 // the FormatSpecifier.
1302 if (FS.hasLeadingZeros())
1303 HandleFlags(FS, "0", CS.getCharacters(), startSpecifier, specifierLen);
1304 if (FS.hasPlusPrefix())
1305 HandleFlags(FS, "+", CS.getCharacters(), startSpecifier, specifierLen);
1306 if (FS.hasSpacePrefix())
1307 HandleFlags(FS, " ", CS.getCharacters(), startSpecifier, specifierLen);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001308 }
1309
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001310 // The remaining checks depend on the data arguments.
1311 if (HasVAListArg)
1312 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001313
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001314 if (argIndex >= NumDataArgs) {
Ted Kremenek6ee76532010-03-25 03:59:12 +00001315 if (FS.usesPositionalArg()) {
1316 S.Diag(getLocationOfByte(CS.getStart()),
1317 diag::warn_printf_positional_arg_exceeds_data_args)
1318 << (argIndex+1) << NumDataArgs
1319 << getFormatSpecifierRange(startSpecifier, specifierLen);
1320 }
1321 else {
1322 S.Diag(getLocationOfByte(CS.getStart()),
1323 diag::warn_printf_insufficient_data_args)
1324 << getFormatSpecifierRange(startSpecifier, specifierLen);
1325 }
1326
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001327 // Don't do any more checking.
1328 return false;
1329 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001330
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001331 // Now type check the data expression that matches the
1332 // format specifier.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001333 const Expr *Ex = getDataArg(argIndex);
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001334 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001335 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
1336 // Check if we didn't match because of an implicit cast from a 'char'
1337 // or 'short' to an 'int'. This is done because printf is a varargs
1338 // function.
1339 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
1340 if (ICE->getType() == S.Context.IntTy)
1341 if (ATR.matchesType(S.Context, ICE->getSubExpr()->getType()))
1342 return true;
Ted Kremenek105d41c2010-02-01 19:38:10 +00001343
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001344 S.Diag(getLocationOfByte(CS.getStart()),
1345 diag::warn_printf_conversion_argument_type_mismatch)
1346 << ATR.getRepresentativeType(S.Context) << Ex->getType()
Ted Kremenek1497bff2010-02-11 19:37:25 +00001347 << getFormatSpecifierRange(startSpecifier, specifierLen)
1348 << Ex->getSourceRange();
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001349 }
Ted Kremeneke0e53132010-01-28 23:39:18 +00001350
1351 return true;
1352}
1353
Ted Kremenek07d161f2010-01-29 01:50:07 +00001354void CheckPrintfHandler::DoneProcessing() {
1355 // Does the number of data arguments exceed the number of
1356 // format conversions in the format string?
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001357 if (!HasVAListArg) {
1358 // Find any arguments that weren't covered.
1359 CoveredArgs.flip();
1360 signed notCoveredArg = CoveredArgs.find_first();
1361 if (notCoveredArg >= 0) {
1362 assert((unsigned)notCoveredArg < NumDataArgs);
1363 S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(),
1364 diag::warn_printf_data_arg_not_used)
1365 << getFormatStringRange();
1366 }
1367 }
Ted Kremenek07d161f2010-01-29 01:50:07 +00001368}
Ted Kremeneke0e53132010-01-28 23:39:18 +00001369
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001370void Sema::CheckPrintfString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001371 const Expr *OrigFormatExpr,
1372 const CallExpr *TheCall, bool HasVAListArg,
1373 unsigned format_idx, unsigned firstDataArg) {
1374
Ted Kremeneke0e53132010-01-28 23:39:18 +00001375 // CHECK: is the format string a wide literal?
1376 if (FExpr->isWide()) {
1377 Diag(FExpr->getLocStart(),
1378 diag::warn_printf_format_string_is_wide_literal)
1379 << OrigFormatExpr->getSourceRange();
1380 return;
1381 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001382
Ted Kremeneke0e53132010-01-28 23:39:18 +00001383 // Str - The format string. NOTE: this is NOT null-terminated!
1384 const char *Str = FExpr->getStrData();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001385
Ted Kremeneke0e53132010-01-28 23:39:18 +00001386 // CHECK: empty format string?
1387 unsigned StrLen = FExpr->getByteLength();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001388
Ted Kremeneke0e53132010-01-28 23:39:18 +00001389 if (StrLen == 0) {
1390 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string)
1391 << OrigFormatExpr->getSourceRange();
1392 return;
1393 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001394
Ted Kremenek6ee76532010-03-25 03:59:12 +00001395 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001396 TheCall->getNumArgs() - firstDataArg,
Ted Kremenek0d277352010-01-29 01:06:55 +00001397 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1398 HasVAListArg, TheCall, format_idx);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001399
Ted Kremenek74d56a12010-02-04 20:46:58 +00001400 if (!analyze_printf::ParseFormatString(H, Str, Str + StrLen))
Ted Kremenek808015a2010-01-29 03:16:21 +00001401 H.DoneProcessing();
Ted Kremenekce7024e2010-01-28 01:18:22 +00001402}
1403
Ted Kremenek06de2762007-08-17 16:46:58 +00001404//===--- CHECK: Return Address of Stack Variable --------------------------===//
1405
1406static DeclRefExpr* EvalVal(Expr *E);
1407static DeclRefExpr* EvalAddr(Expr* E);
1408
1409/// CheckReturnStackAddr - Check if a return statement returns the address
1410/// of a stack variable.
1411void
1412Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1413 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00001414
Ted Kremenek06de2762007-08-17 16:46:58 +00001415 // Perform checking for returned stack addresses.
Steve Naroffdd972f22008-09-05 22:11:13 +00001416 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Ted Kremenek06de2762007-08-17 16:46:58 +00001417 if (DeclRefExpr *DR = EvalAddr(RetValExp))
Chris Lattner3c73c412008-11-19 08:23:25 +00001418 Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
Chris Lattner08631c52008-11-23 21:45:46 +00001419 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001420
Steve Naroffc50a4a52008-09-16 22:25:10 +00001421 // Skip over implicit cast expressions when checking for block expressions.
Chris Lattner4ca606e2009-09-08 00:36:37 +00001422 RetValExp = RetValExp->IgnoreParenCasts();
Steve Naroffc50a4a52008-09-16 22:25:10 +00001423
Chris Lattner9e6b37a2009-10-30 04:01:58 +00001424 if (BlockExpr *C = dyn_cast<BlockExpr>(RetValExp))
Mike Stump397195b2009-04-17 00:09:41 +00001425 if (C->hasBlockDeclRefExprs())
1426 Diag(C->getLocStart(), diag::err_ret_local_block)
1427 << C->getSourceRange();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001428
Chris Lattner9e6b37a2009-10-30 04:01:58 +00001429 if (AddrLabelExpr *ALE = dyn_cast<AddrLabelExpr>(RetValExp))
1430 Diag(ALE->getLocStart(), diag::warn_ret_addr_label)
1431 << ALE->getSourceRange();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001432
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001433 } else if (lhsType->isReferenceType()) {
1434 // Perform checking for stack values returned by reference.
Douglas Gregor49badde2008-10-27 19:41:14 +00001435 // Check for a reference to the stack
1436 if (DeclRefExpr *DR = EvalVal(RetValExp))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001437 Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
Chris Lattner08631c52008-11-23 21:45:46 +00001438 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +00001439 }
1440}
1441
1442/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1443/// check if the expression in a return statement evaluates to an address
1444/// to a location on the stack. The recursion is used to traverse the
1445/// AST of the return expression, with recursion backtracking when we
1446/// encounter a subexpression that (1) clearly does not lead to the address
1447/// of a stack variable or (2) is something we cannot determine leads to
1448/// the address of a stack variable based on such local checking.
1449///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001450/// EvalAddr processes expressions that are pointers that are used as
1451/// references (and not L-values). EvalVal handles all other values.
Mike Stump1eb44332009-09-09 15:08:12 +00001452/// At the base case of the recursion is a check for a DeclRefExpr* in
Ted Kremenek06de2762007-08-17 16:46:58 +00001453/// the refers to a stack variable.
1454///
1455/// This implementation handles:
1456///
1457/// * pointer-to-pointer casts
1458/// * implicit conversions from array references to pointers
1459/// * taking the address of fields
1460/// * arbitrary interplay between "&" and "*" operators
1461/// * pointer arithmetic from an address of a stack variable
1462/// * taking the address of an array element where the array is on the stack
1463static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek06de2762007-08-17 16:46:58 +00001464 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00001465 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00001466 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001467 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001468 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00001469
Ted Kremenek06de2762007-08-17 16:46:58 +00001470 // Our "symbolic interpreter" is just a dispatch off the currently
1471 // viewed AST node. We then recursively traverse the AST by calling
1472 // EvalAddr and EvalVal appropriately.
1473 switch (E->getStmtClass()) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001474 case Stmt::ParenExprClass:
1475 // Ignore parentheses.
1476 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek06de2762007-08-17 16:46:58 +00001477
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001478 case Stmt::UnaryOperatorClass: {
1479 // The only unary operator that make sense to handle here
1480 // is AddrOf. All others don't make sense as pointers.
1481 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001482
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001483 if (U->getOpcode() == UnaryOperator::AddrOf)
1484 return EvalVal(U->getSubExpr());
1485 else
Ted Kremenek06de2762007-08-17 16:46:58 +00001486 return NULL;
1487 }
Mike Stump1eb44332009-09-09 15:08:12 +00001488
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001489 case Stmt::BinaryOperatorClass: {
1490 // Handle pointer arithmetic. All other binary operators are not valid
1491 // in this context.
1492 BinaryOperator *B = cast<BinaryOperator>(E);
1493 BinaryOperator::Opcode op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00001494
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001495 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
1496 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001497
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001498 Expr *Base = B->getLHS();
1499
1500 // Determine which argument is the real pointer base. It could be
1501 // the RHS argument instead of the LHS.
1502 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00001503
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001504 assert (Base->getType()->isPointerType());
1505 return EvalAddr(Base);
1506 }
Steve Naroff61f40a22008-09-10 19:17:48 +00001507
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001508 // For conditional operators we need to see if either the LHS or RHS are
1509 // valid DeclRefExpr*s. If one of them is valid, we return it.
1510 case Stmt::ConditionalOperatorClass: {
1511 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001512
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001513 // Handle the GNU extension for missing LHS.
1514 if (Expr *lhsExpr = C->getLHS())
1515 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
1516 return LHS;
1517
1518 return EvalAddr(C->getRHS());
1519 }
Mike Stump1eb44332009-09-09 15:08:12 +00001520
Ted Kremenek54b52742008-08-07 00:49:01 +00001521 // For casts, we need to handle conversions from arrays to
1522 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00001523 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001524 case Stmt::CStyleCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001525 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001526 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00001527 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001528
Steve Naroffdd972f22008-09-05 22:11:13 +00001529 if (SubExpr->getType()->isPointerType() ||
1530 SubExpr->getType()->isBlockPointerType() ||
1531 SubExpr->getType()->isObjCQualifiedIdType())
Ted Kremenek54b52742008-08-07 00:49:01 +00001532 return EvalAddr(SubExpr);
1533 else if (T->isArrayType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001534 return EvalVal(SubExpr);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001535 else
Ted Kremenek54b52742008-08-07 00:49:01 +00001536 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001537 }
Mike Stump1eb44332009-09-09 15:08:12 +00001538
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001539 // C++ casts. For dynamic casts, static casts, and const casts, we
1540 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00001541 // through the cast. In the case the dynamic cast doesn't fail (and
1542 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001543 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00001544 // FIXME: The comment about is wrong; we're not always converting
1545 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00001546 // handle references to objects.
1547 case Stmt::CXXStaticCastExprClass:
1548 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001549 case Stmt::CXXConstCastExprClass:
1550 case Stmt::CXXReinterpretCastExprClass: {
1551 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00001552 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001553 return EvalAddr(S);
1554 else
1555 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001556 }
Mike Stump1eb44332009-09-09 15:08:12 +00001557
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001558 // Everything else: we simply don't reason about them.
1559 default:
1560 return NULL;
1561 }
Ted Kremenek06de2762007-08-17 16:46:58 +00001562}
Mike Stump1eb44332009-09-09 15:08:12 +00001563
Ted Kremenek06de2762007-08-17 16:46:58 +00001564
1565/// EvalVal - This function is complements EvalAddr in the mutual recursion.
1566/// See the comments for EvalAddr for more details.
1567static DeclRefExpr* EvalVal(Expr *E) {
Mike Stump1eb44332009-09-09 15:08:12 +00001568
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001569 // We should only be called for evaluating non-pointer expressions, or
1570 // expressions with a pointer type that are not used as references but instead
1571 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00001572
Ted Kremenek06de2762007-08-17 16:46:58 +00001573 // Our "symbolic interpreter" is just a dispatch off the currently
1574 // viewed AST node. We then recursively traverse the AST by calling
1575 // EvalAddr and EvalVal appropriately.
1576 switch (E->getStmtClass()) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00001577 case Stmt::DeclRefExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00001578 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
1579 // at code that refers to a variable's name. We check if it has local
1580 // storage within the function, and if so, return the expression.
1581 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001582
Ted Kremenek06de2762007-08-17 16:46:58 +00001583 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Mike Stump1eb44332009-09-09 15:08:12 +00001584 if (V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
1585
Ted Kremenek06de2762007-08-17 16:46:58 +00001586 return NULL;
1587 }
Mike Stump1eb44332009-09-09 15:08:12 +00001588
Ted Kremenek06de2762007-08-17 16:46:58 +00001589 case Stmt::ParenExprClass:
1590 // Ignore parentheses.
1591 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
Mike Stump1eb44332009-09-09 15:08:12 +00001592
Ted Kremenek06de2762007-08-17 16:46:58 +00001593 case Stmt::UnaryOperatorClass: {
1594 // The only unary operator that make sense to handle here
1595 // is Deref. All others don't resolve to a "name." This includes
1596 // handling all sorts of rvalues passed to a unary operator.
1597 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001598
Ted Kremenek06de2762007-08-17 16:46:58 +00001599 if (U->getOpcode() == UnaryOperator::Deref)
1600 return EvalAddr(U->getSubExpr());
1601
1602 return NULL;
1603 }
Mike Stump1eb44332009-09-09 15:08:12 +00001604
Ted Kremenek06de2762007-08-17 16:46:58 +00001605 case Stmt::ArraySubscriptExprClass: {
1606 // Array subscripts are potential references to data on the stack. We
1607 // retrieve the DeclRefExpr* for the array variable if it indeed
1608 // has local storage.
Ted Kremenek23245122007-08-20 16:18:38 +00001609 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek06de2762007-08-17 16:46:58 +00001610 }
Mike Stump1eb44332009-09-09 15:08:12 +00001611
Ted Kremenek06de2762007-08-17 16:46:58 +00001612 case Stmt::ConditionalOperatorClass: {
1613 // For conditional operators we need to see if either the LHS or RHS are
1614 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
1615 ConditionalOperator *C = cast<ConditionalOperator>(E);
1616
Anders Carlsson39073232007-11-30 19:04:31 +00001617 // Handle the GNU extension for missing LHS.
1618 if (Expr *lhsExpr = C->getLHS())
1619 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
1620 return LHS;
1621
1622 return EvalVal(C->getRHS());
Ted Kremenek06de2762007-08-17 16:46:58 +00001623 }
Mike Stump1eb44332009-09-09 15:08:12 +00001624
Ted Kremenek06de2762007-08-17 16:46:58 +00001625 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00001626 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00001627 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001628
Ted Kremenek06de2762007-08-17 16:46:58 +00001629 // Check for indirect access. We only want direct field accesses.
1630 if (!M->isArrow())
1631 return EvalVal(M->getBase());
1632 else
1633 return NULL;
1634 }
Mike Stump1eb44332009-09-09 15:08:12 +00001635
Ted Kremenek06de2762007-08-17 16:46:58 +00001636 // Everything else: we simply don't reason about them.
1637 default:
1638 return NULL;
1639 }
1640}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001641
1642//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
1643
1644/// Check for comparisons of floating point operands using != and ==.
1645/// Issue a warning if these are no self-comparisons, as they are not likely
1646/// to do what the programmer intended.
1647void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
1648 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001649
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00001650 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek32e97b62008-01-17 17:55:13 +00001651 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001652
1653 // Special case: check for x == x (which is OK).
1654 // Do not emit warnings for such cases.
1655 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
1656 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
1657 if (DRL->getDecl() == DRR->getDecl())
1658 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001659
1660
Ted Kremenek1b500bb2007-11-29 00:59:04 +00001661 // Special case: check for comparisons against literals that can be exactly
1662 // represented by APFloat. In such cases, do not emit a warning. This
1663 // is a heuristic: often comparison against such literals are used to
1664 // detect if a value in a variable has not changed. This clearly can
1665 // lead to false negatives.
1666 if (EmitWarning) {
1667 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
1668 if (FLL->isExact())
1669 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001670 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00001671 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
1672 if (FLR->isExact())
1673 EmitWarning = false;
1674 }
1675 }
Mike Stump1eb44332009-09-09 15:08:12 +00001676
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001677 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001678 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001679 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001680 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001681 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001682
Sebastian Redl0eb23302009-01-19 00:08:26 +00001683 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001684 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001685 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001686 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001687
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001688 // Emit the diagnostic.
1689 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001690 Diag(loc, diag::warn_floatingpoint_eq)
1691 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001692}
John McCallba26e582010-01-04 23:21:16 +00001693
John McCallf2370c92010-01-06 05:24:50 +00001694//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
1695//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00001696
John McCallf2370c92010-01-06 05:24:50 +00001697namespace {
John McCallba26e582010-01-04 23:21:16 +00001698
John McCallf2370c92010-01-06 05:24:50 +00001699/// Structure recording the 'active' range of an integer-valued
1700/// expression.
1701struct IntRange {
1702 /// The number of bits active in the int.
1703 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00001704
John McCallf2370c92010-01-06 05:24:50 +00001705 /// True if the int is known not to have negative values.
1706 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00001707
John McCallf2370c92010-01-06 05:24:50 +00001708 IntRange() {}
1709 IntRange(unsigned Width, bool NonNegative)
1710 : Width(Width), NonNegative(NonNegative)
1711 {}
John McCallba26e582010-01-04 23:21:16 +00001712
John McCallf2370c92010-01-06 05:24:50 +00001713 // Returns the range of the bool type.
1714 static IntRange forBoolType() {
1715 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00001716 }
1717
John McCallf2370c92010-01-06 05:24:50 +00001718 // Returns the range of an integral type.
1719 static IntRange forType(ASTContext &C, QualType T) {
1720 return forCanonicalType(C, T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00001721 }
1722
John McCallf2370c92010-01-06 05:24:50 +00001723 // Returns the range of an integeral type based on its canonical
1724 // representation.
1725 static IntRange forCanonicalType(ASTContext &C, const Type *T) {
1726 assert(T->isCanonicalUnqualified());
1727
1728 if (const VectorType *VT = dyn_cast<VectorType>(T))
1729 T = VT->getElementType().getTypePtr();
1730 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
1731 T = CT->getElementType().getTypePtr();
1732 if (const EnumType *ET = dyn_cast<EnumType>(T))
1733 T = ET->getDecl()->getIntegerType().getTypePtr();
1734
1735 const BuiltinType *BT = cast<BuiltinType>(T);
1736 assert(BT->isInteger());
1737
1738 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
1739 }
1740
1741 // Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00001742 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00001743 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00001744 L.NonNegative && R.NonNegative);
1745 }
1746
1747 // Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00001748 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00001749 return IntRange(std::min(L.Width, R.Width),
1750 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00001751 }
1752};
1753
1754IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
1755 if (value.isSigned() && value.isNegative())
1756 return IntRange(value.getMinSignedBits(), false);
1757
1758 if (value.getBitWidth() > MaxWidth)
1759 value.trunc(MaxWidth);
1760
1761 // isNonNegative() just checks the sign bit without considering
1762 // signedness.
1763 return IntRange(value.getActiveBits(), true);
1764}
1765
John McCall0acc3112010-01-06 22:57:21 +00001766IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCallf2370c92010-01-06 05:24:50 +00001767 unsigned MaxWidth) {
1768 if (result.isInt())
1769 return GetValueRange(C, result.getInt(), MaxWidth);
1770
1771 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00001772 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
1773 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
1774 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
1775 R = IntRange::join(R, El);
1776 }
John McCallf2370c92010-01-06 05:24:50 +00001777 return R;
1778 }
1779
1780 if (result.isComplexInt()) {
1781 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
1782 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
1783 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00001784 }
1785
1786 // This can happen with lossless casts to intptr_t of "based" lvalues.
1787 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00001788 // FIXME: The only reason we need to pass the type in here is to get
1789 // the sign right on this one case. It would be nice if APValue
1790 // preserved this.
John McCallf2370c92010-01-06 05:24:50 +00001791 assert(result.isLValue());
John McCall0acc3112010-01-06 22:57:21 +00001792 return IntRange(MaxWidth, Ty->isUnsignedIntegerType());
John McCall51313c32010-01-04 23:31:57 +00001793}
John McCallf2370c92010-01-06 05:24:50 +00001794
1795/// Pseudo-evaluate the given integer expression, estimating the
1796/// range of values it might take.
1797///
1798/// \param MaxWidth - the width to which the value will be truncated
1799IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
1800 E = E->IgnoreParens();
1801
1802 // Try a full evaluation first.
1803 Expr::EvalResult result;
1804 if (E->Evaluate(result, C))
John McCall0acc3112010-01-06 22:57:21 +00001805 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00001806
1807 // I think we only want to look through implicit casts here; if the
1808 // user has an explicit widening cast, we should treat the value as
1809 // being of the new, wider type.
1810 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
1811 if (CE->getCastKind() == CastExpr::CK_NoOp)
1812 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
1813
1814 IntRange OutputTypeRange = IntRange::forType(C, CE->getType());
1815
John McCall60fad452010-01-06 22:07:33 +00001816 bool isIntegerCast = (CE->getCastKind() == CastExpr::CK_IntegralCast);
1817 if (!isIntegerCast && CE->getCastKind() == CastExpr::CK_Unknown)
1818 isIntegerCast = CE->getSubExpr()->getType()->isIntegerType();
1819
John McCallf2370c92010-01-06 05:24:50 +00001820 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00001821 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00001822 return OutputTypeRange;
1823
1824 IntRange SubRange
1825 = GetExprRange(C, CE->getSubExpr(),
1826 std::min(MaxWidth, OutputTypeRange.Width));
1827
1828 // Bail out if the subexpr's range is as wide as the cast type.
1829 if (SubRange.Width >= OutputTypeRange.Width)
1830 return OutputTypeRange;
1831
1832 // Otherwise, we take the smaller width, and we're non-negative if
1833 // either the output type or the subexpr is.
1834 return IntRange(SubRange.Width,
1835 SubRange.NonNegative || OutputTypeRange.NonNegative);
1836 }
1837
1838 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1839 // If we can fold the condition, just take that operand.
1840 bool CondResult;
1841 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
1842 return GetExprRange(C, CondResult ? CO->getTrueExpr()
1843 : CO->getFalseExpr(),
1844 MaxWidth);
1845
1846 // Otherwise, conservatively merge.
1847 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
1848 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
1849 return IntRange::join(L, R);
1850 }
1851
1852 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
1853 switch (BO->getOpcode()) {
1854
1855 // Boolean-valued operations are single-bit and positive.
1856 case BinaryOperator::LAnd:
1857 case BinaryOperator::LOr:
1858 case BinaryOperator::LT:
1859 case BinaryOperator::GT:
1860 case BinaryOperator::LE:
1861 case BinaryOperator::GE:
1862 case BinaryOperator::EQ:
1863 case BinaryOperator::NE:
1864 return IntRange::forBoolType();
1865
John McCallc0cd21d2010-02-23 19:22:29 +00001866 // The type of these compound assignments is the type of the LHS,
1867 // so the RHS is not necessarily an integer.
1868 case BinaryOperator::MulAssign:
1869 case BinaryOperator::DivAssign:
1870 case BinaryOperator::RemAssign:
1871 case BinaryOperator::AddAssign:
1872 case BinaryOperator::SubAssign:
1873 return IntRange::forType(C, E->getType());
1874
John McCallf2370c92010-01-06 05:24:50 +00001875 // Operations with opaque sources are black-listed.
1876 case BinaryOperator::PtrMemD:
1877 case BinaryOperator::PtrMemI:
1878 return IntRange::forType(C, E->getType());
1879
John McCall60fad452010-01-06 22:07:33 +00001880 // Bitwise-and uses the *infinum* of the two source ranges.
1881 case BinaryOperator::And:
John McCallc0cd21d2010-02-23 19:22:29 +00001882 case BinaryOperator::AndAssign:
John McCall60fad452010-01-06 22:07:33 +00001883 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
1884 GetExprRange(C, BO->getRHS(), MaxWidth));
1885
John McCallf2370c92010-01-06 05:24:50 +00001886 // Left shift gets black-listed based on a judgement call.
1887 case BinaryOperator::Shl:
John McCall3aae6092010-04-07 01:14:35 +00001888 // ...except that we want to treat '1 << (blah)' as logically
1889 // positive. It's an important idiom.
1890 if (IntegerLiteral *I
1891 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
1892 if (I->getValue() == 1) {
1893 IntRange R = IntRange::forType(C, E->getType());
1894 return IntRange(R.Width, /*NonNegative*/ true);
1895 }
1896 }
1897 // fallthrough
1898
John McCallc0cd21d2010-02-23 19:22:29 +00001899 case BinaryOperator::ShlAssign:
John McCallf2370c92010-01-06 05:24:50 +00001900 return IntRange::forType(C, E->getType());
1901
John McCall60fad452010-01-06 22:07:33 +00001902 // Right shift by a constant can narrow its left argument.
John McCallc0cd21d2010-02-23 19:22:29 +00001903 case BinaryOperator::Shr:
1904 case BinaryOperator::ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00001905 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
1906
1907 // If the shift amount is a positive constant, drop the width by
1908 // that much.
1909 llvm::APSInt shift;
1910 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
1911 shift.isNonNegative()) {
1912 unsigned zext = shift.getZExtValue();
1913 if (zext >= L.Width)
1914 L.Width = (L.NonNegative ? 0 : 1);
1915 else
1916 L.Width -= zext;
1917 }
1918
1919 return L;
1920 }
1921
1922 // Comma acts as its right operand.
John McCallf2370c92010-01-06 05:24:50 +00001923 case BinaryOperator::Comma:
1924 return GetExprRange(C, BO->getRHS(), MaxWidth);
1925
John McCall60fad452010-01-06 22:07:33 +00001926 // Black-list pointer subtractions.
John McCallf2370c92010-01-06 05:24:50 +00001927 case BinaryOperator::Sub:
1928 if (BO->getLHS()->getType()->isPointerType())
1929 return IntRange::forType(C, E->getType());
1930 // fallthrough
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001931
John McCallf2370c92010-01-06 05:24:50 +00001932 default:
1933 break;
1934 }
1935
1936 // Treat every other operator as if it were closed on the
1937 // narrowest type that encompasses both operands.
1938 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
1939 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
1940 return IntRange::join(L, R);
1941 }
1942
1943 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1944 switch (UO->getOpcode()) {
1945 // Boolean-valued operations are white-listed.
1946 case UnaryOperator::LNot:
1947 return IntRange::forBoolType();
1948
1949 // Operations with opaque sources are black-listed.
1950 case UnaryOperator::Deref:
1951 case UnaryOperator::AddrOf: // should be impossible
1952 case UnaryOperator::OffsetOf:
1953 return IntRange::forType(C, E->getType());
1954
1955 default:
1956 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
1957 }
1958 }
1959
1960 FieldDecl *BitField = E->getBitField();
1961 if (BitField) {
1962 llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C);
1963 unsigned BitWidth = BitWidthAP.getZExtValue();
1964
1965 return IntRange(BitWidth, BitField->getType()->isUnsignedIntegerType());
1966 }
1967
1968 return IntRange::forType(C, E->getType());
1969}
John McCall51313c32010-01-04 23:31:57 +00001970
1971/// Checks whether the given value, which currently has the given
1972/// source semantics, has the same value when coerced through the
1973/// target semantics.
John McCallf2370c92010-01-06 05:24:50 +00001974bool IsSameFloatAfterCast(const llvm::APFloat &value,
1975 const llvm::fltSemantics &Src,
1976 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00001977 llvm::APFloat truncated = value;
1978
1979 bool ignored;
1980 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
1981 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
1982
1983 return truncated.bitwiseIsEqual(value);
1984}
1985
1986/// Checks whether the given value, which currently has the given
1987/// source semantics, has the same value when coerced through the
1988/// target semantics.
1989///
1990/// The value might be a vector of floats (or a complex number).
John McCallf2370c92010-01-06 05:24:50 +00001991bool IsSameFloatAfterCast(const APValue &value,
1992 const llvm::fltSemantics &Src,
1993 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00001994 if (value.isFloat())
1995 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
1996
1997 if (value.isVector()) {
1998 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
1999 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
2000 return false;
2001 return true;
2002 }
2003
2004 assert(value.isComplexFloat());
2005 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
2006 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
2007}
2008
John McCallf2370c92010-01-06 05:24:50 +00002009} // end anonymous namespace
John McCall51313c32010-01-04 23:31:57 +00002010
John McCallba26e582010-01-04 23:21:16 +00002011/// \brief Implements -Wsign-compare.
2012///
2013/// \param lex the left-hand expression
2014/// \param rex the right-hand expression
2015/// \param OpLoc the location of the joining operator
John McCalld1b47bf2010-03-11 19:43:18 +00002016/// \param BinOpc binary opcode or 0
John McCallba26e582010-01-04 23:21:16 +00002017void Sema::CheckSignCompare(Expr *lex, Expr *rex, SourceLocation OpLoc,
John McCalld1b47bf2010-03-11 19:43:18 +00002018 const BinaryOperator::Opcode* BinOpc) {
John McCallba26e582010-01-04 23:21:16 +00002019 // Don't warn if we're in an unevaluated context.
2020 if (ExprEvalContexts.back().Context == Unevaluated)
2021 return;
2022
John McCallf2370c92010-01-06 05:24:50 +00002023 // If either expression is value-dependent, don't warn. We'll get another
2024 // chance at instantiation time.
2025 if (lex->isValueDependent() || rex->isValueDependent())
2026 return;
2027
John McCallba26e582010-01-04 23:21:16 +00002028 QualType lt = lex->getType(), rt = rex->getType();
2029
2030 // Only warn if both operands are integral.
2031 if (!lt->isIntegerType() || !rt->isIntegerType())
2032 return;
2033
John McCallf2370c92010-01-06 05:24:50 +00002034 // In C, the width of a bitfield determines its type, and the
2035 // declared type only contributes the signedness. This duplicates
2036 // the work that will later be done by UsualUnaryConversions.
2037 // Eventually, this check will be reorganized in a way that avoids
2038 // this duplication.
2039 if (!getLangOptions().CPlusPlus) {
2040 QualType tmp;
2041 tmp = Context.isPromotableBitField(lex);
2042 if (!tmp.isNull()) lt = tmp;
2043 tmp = Context.isPromotableBitField(rex);
2044 if (!tmp.isNull()) rt = tmp;
2045 }
John McCallba26e582010-01-04 23:21:16 +00002046
John McCalla2936be2010-03-19 18:53:26 +00002047 if (const EnumType *E = lt->getAs<EnumType>())
2048 lt = E->getDecl()->getPromotionType();
2049 if (const EnumType *E = rt->getAs<EnumType>())
2050 rt = E->getDecl()->getPromotionType();
2051
John McCallba26e582010-01-04 23:21:16 +00002052 // The rule is that the signed operand becomes unsigned, so isolate the
2053 // signed operand.
John McCallf2370c92010-01-06 05:24:50 +00002054 Expr *signedOperand = lex, *unsignedOperand = rex;
2055 QualType signedType = lt, unsignedType = rt;
John McCallba26e582010-01-04 23:21:16 +00002056 if (lt->isSignedIntegerType()) {
2057 if (rt->isSignedIntegerType()) return;
John McCallba26e582010-01-04 23:21:16 +00002058 } else {
2059 if (!rt->isSignedIntegerType()) return;
John McCallf2370c92010-01-06 05:24:50 +00002060 std::swap(signedOperand, unsignedOperand);
2061 std::swap(signedType, unsignedType);
John McCallba26e582010-01-04 23:21:16 +00002062 }
2063
John McCallf2370c92010-01-06 05:24:50 +00002064 unsigned unsignedWidth = Context.getIntWidth(unsignedType);
2065 unsigned signedWidth = Context.getIntWidth(signedType);
2066
John McCallba26e582010-01-04 23:21:16 +00002067 // If the unsigned type is strictly smaller than the signed type,
2068 // then (1) the result type will be signed and (2) the unsigned
2069 // value will fit fully within the signed type, and thus the result
2070 // of the comparison will be exact.
John McCallf2370c92010-01-06 05:24:50 +00002071 if (signedWidth > unsignedWidth)
John McCallba26e582010-01-04 23:21:16 +00002072 return;
2073
John McCallf2370c92010-01-06 05:24:50 +00002074 // Otherwise, calculate the effective ranges.
2075 IntRange signedRange = GetExprRange(Context, signedOperand, signedWidth);
2076 IntRange unsignedRange = GetExprRange(Context, unsignedOperand, unsignedWidth);
2077
2078 // We should never be unable to prove that the unsigned operand is
2079 // non-negative.
2080 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
2081
2082 // If the signed operand is non-negative, then the signed->unsigned
2083 // conversion won't change it.
John McCalld1b47bf2010-03-11 19:43:18 +00002084 if (signedRange.NonNegative) {
2085 // Emit warnings for comparisons of unsigned to integer constant 0.
2086 // always false: x < 0 (or 0 > x)
2087 // always true: x >= 0 (or 0 <= x)
2088 llvm::APSInt X;
2089 if (BinOpc && signedOperand->isIntegerConstantExpr(X, Context) && X == 0) {
2090 if (signedOperand != lex) {
2091 if (*BinOpc == BinaryOperator::LT) {
2092 Diag(OpLoc, diag::warn_lunsigned_always_true_comparison)
2093 << "< 0" << "false"
2094 << lex->getSourceRange() << rex->getSourceRange();
2095 }
2096 else if (*BinOpc == BinaryOperator::GE) {
2097 Diag(OpLoc, diag::warn_lunsigned_always_true_comparison)
2098 << ">= 0" << "true"
2099 << lex->getSourceRange() << rex->getSourceRange();
2100 }
2101 }
2102 else {
2103 if (*BinOpc == BinaryOperator::GT) {
2104 Diag(OpLoc, diag::warn_runsigned_always_true_comparison)
2105 << "0 >" << "false"
2106 << lex->getSourceRange() << rex->getSourceRange();
2107 }
2108 else if (*BinOpc == BinaryOperator::LE) {
2109 Diag(OpLoc, diag::warn_runsigned_always_true_comparison)
2110 << "0 <=" << "true"
2111 << lex->getSourceRange() << rex->getSourceRange();
2112 }
2113 }
2114 }
John McCallba26e582010-01-04 23:21:16 +00002115 return;
John McCalld1b47bf2010-03-11 19:43:18 +00002116 }
John McCallba26e582010-01-04 23:21:16 +00002117
2118 // For (in)equality comparisons, if the unsigned operand is a
2119 // constant which cannot collide with a overflowed signed operand,
2120 // then reinterpreting the signed operand as unsigned will not
2121 // change the result of the comparison.
John McCalld1b47bf2010-03-11 19:43:18 +00002122 if (BinOpc &&
2123 (*BinOpc == BinaryOperator::EQ || *BinOpc == BinaryOperator::NE) &&
2124 unsignedRange.Width < unsignedWidth)
John McCallba26e582010-01-04 23:21:16 +00002125 return;
2126
John McCalld1b47bf2010-03-11 19:43:18 +00002127 Diag(OpLoc, BinOpc ? diag::warn_mixed_sign_comparison
2128 : diag::warn_mixed_sign_conditional)
John McCallf2370c92010-01-06 05:24:50 +00002129 << lt << rt << lex->getSourceRange() << rex->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00002130}
2131
John McCall51313c32010-01-04 23:31:57 +00002132/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
2133static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, unsigned diag) {
2134 S.Diag(E->getExprLoc(), diag) << E->getType() << T << E->getSourceRange();
2135}
2136
2137/// Implements -Wconversion.
2138void Sema::CheckImplicitConversion(Expr *E, QualType T) {
2139 // Don't diagnose in unevaluated contexts.
2140 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
2141 return;
2142
2143 // Don't diagnose for value-dependent expressions.
2144 if (E->isValueDependent())
2145 return;
2146
2147 const Type *Source = Context.getCanonicalType(E->getType()).getTypePtr();
2148 const Type *Target = Context.getCanonicalType(T).getTypePtr();
2149
2150 // Never diagnose implicit casts to bool.
2151 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
2152 return;
2153
2154 // Strip vector types.
2155 if (isa<VectorType>(Source)) {
2156 if (!isa<VectorType>(Target))
2157 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_vector_scalar);
2158
2159 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
2160 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
2161 }
2162
2163 // Strip complex types.
2164 if (isa<ComplexType>(Source)) {
2165 if (!isa<ComplexType>(Target))
2166 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_complex_scalar);
2167
2168 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
2169 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
2170 }
2171
2172 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
2173 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
2174
2175 // If the source is floating point...
2176 if (SourceBT && SourceBT->isFloatingPoint()) {
2177 // ...and the target is floating point...
2178 if (TargetBT && TargetBT->isFloatingPoint()) {
2179 // ...then warn if we're dropping FP rank.
2180
2181 // Builtin FP kinds are ordered by increasing FP rank.
2182 if (SourceBT->getKind() > TargetBT->getKind()) {
2183 // Don't warn about float constants that are precisely
2184 // representable in the target type.
2185 Expr::EvalResult result;
2186 if (E->Evaluate(result, Context)) {
2187 // Value might be a float, a float vector, or a float complex.
2188 if (IsSameFloatAfterCast(result.Val,
2189 Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
2190 Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
2191 return;
2192 }
2193
2194 DiagnoseImpCast(*this, E, T, diag::warn_impcast_float_precision);
2195 }
2196 return;
2197 }
2198
2199 // If the target is integral, always warn.
2200 if ((TargetBT && TargetBT->isInteger()))
2201 // TODO: don't warn for integer values?
2202 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_float_integer);
2203
2204 return;
2205 }
2206
John McCallf2370c92010-01-06 05:24:50 +00002207 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00002208 return;
2209
John McCallf2370c92010-01-06 05:24:50 +00002210 IntRange SourceRange = GetExprRange(Context, E, Context.getIntWidth(E->getType()));
2211 IntRange TargetRange = IntRange::forCanonicalType(Context, Target);
John McCall51313c32010-01-04 23:31:57 +00002212
John McCallf2370c92010-01-06 05:24:50 +00002213 // FIXME: also signed<->unsigned?
2214
2215 if (SourceRange.Width > TargetRange.Width) {
John McCall51313c32010-01-04 23:31:57 +00002216 // People want to build with -Wshorten-64-to-32 and not -Wconversion
2217 // and by god we'll let them.
John McCallf2370c92010-01-06 05:24:50 +00002218 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCall51313c32010-01-04 23:31:57 +00002219 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_integer_64_32);
2220 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_integer_precision);
2221 }
2222
2223 return;
2224}
2225
Mike Stumpf8c49212010-01-21 03:59:47 +00002226/// CheckParmsForFunctionDef - Check that the parameters of the given
2227/// function are appropriate for the definition of a function. This
2228/// takes care of any checks that cannot be performed on the
2229/// declaration itself, e.g., that the types of each of the function
2230/// parameters are complete.
2231bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
2232 bool HasInvalidParm = false;
2233 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2234 ParmVarDecl *Param = FD->getParamDecl(p);
2235
2236 // C99 6.7.5.3p4: the parameters in a parameter type list in a
2237 // function declarator that is part of a function definition of
2238 // that function shall not have incomplete type.
2239 //
2240 // This is also C++ [dcl.fct]p6.
2241 if (!Param->isInvalidDecl() &&
2242 RequireCompleteType(Param->getLocation(), Param->getType(),
2243 diag::err_typecheck_decl_incomplete_type)) {
2244 Param->setInvalidDecl();
2245 HasInvalidParm = true;
2246 }
2247
2248 // C99 6.9.1p5: If the declarator includes a parameter type list, the
2249 // declaration of each parameter shall include an identifier.
2250 if (Param->getIdentifier() == 0 &&
2251 !Param->isImplicit() &&
2252 !getLangOptions().CPlusPlus)
2253 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00002254
2255 // C99 6.7.5.3p12:
2256 // If the function declarator is not part of a definition of that
2257 // function, parameters may have incomplete type and may use the [*]
2258 // notation in their sequences of declarator specifiers to specify
2259 // variable length array types.
2260 QualType PType = Param->getOriginalType();
2261 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
2262 if (AT->getSizeModifier() == ArrayType::Star) {
2263 // FIXME: This diagnosic should point the the '[*]' if source-location
2264 // information is added for it.
2265 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
2266 }
2267 }
Mike Stumpf8c49212010-01-21 03:59:47 +00002268 }
2269
2270 return HasInvalidParm;
2271}