blob: 033a36c90ebcc3ef8e926420cc3da2c9c0609bef [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)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000273 return Diag(TheCall->getLocEnd(),
274 diag::err_typecheck_call_too_few_args_at_least)
275 << 0 << 1 << TheCall->getNumArgs()
276 << TheCall->getCallee()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000277
Chris Lattner5caa3702009-05-08 06:58:22 +0000278 // Inspect the first argument of the atomic builtin. This should always be
279 // a pointer type, whose element is an integral scalar or pointer type.
280 // Because it is a pointer type, we don't have to worry about any implicit
281 // casts here.
282 Expr *FirstArg = TheCall->getArg(0);
283 if (!FirstArg->getType()->isPointerType())
284 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
285 << FirstArg->getType() << FirstArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000286
Ted Kremenek6217b802009-07-29 21:53:49 +0000287 QualType ValType = FirstArg->getType()->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000288 if (!ValType->isIntegerType() && !ValType->isPointerType() &&
Chris Lattner5caa3702009-05-08 06:58:22 +0000289 !ValType->isBlockPointerType())
290 return Diag(DRE->getLocStart(),
291 diag::err_atomic_builtin_must_be_pointer_intptr)
292 << FirstArg->getType() << FirstArg->getSourceRange();
293
294 // We need to figure out which concrete builtin this maps onto. For example,
295 // __sync_fetch_and_add with a 2 byte object turns into
296 // __sync_fetch_and_add_2.
297#define BUILTIN_ROW(x) \
298 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
299 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000300
Chris Lattner5caa3702009-05-08 06:58:22 +0000301 static const unsigned BuiltinIndices[][5] = {
302 BUILTIN_ROW(__sync_fetch_and_add),
303 BUILTIN_ROW(__sync_fetch_and_sub),
304 BUILTIN_ROW(__sync_fetch_and_or),
305 BUILTIN_ROW(__sync_fetch_and_and),
306 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +0000307
Chris Lattner5caa3702009-05-08 06:58:22 +0000308 BUILTIN_ROW(__sync_add_and_fetch),
309 BUILTIN_ROW(__sync_sub_and_fetch),
310 BUILTIN_ROW(__sync_and_and_fetch),
311 BUILTIN_ROW(__sync_or_and_fetch),
312 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000313
Chris Lattner5caa3702009-05-08 06:58:22 +0000314 BUILTIN_ROW(__sync_val_compare_and_swap),
315 BUILTIN_ROW(__sync_bool_compare_and_swap),
316 BUILTIN_ROW(__sync_lock_test_and_set),
317 BUILTIN_ROW(__sync_lock_release)
318 };
Mike Stump1eb44332009-09-09 15:08:12 +0000319#undef BUILTIN_ROW
320
Chris Lattner5caa3702009-05-08 06:58:22 +0000321 // Determine the index of the size.
322 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000323 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000324 case 1: SizeIndex = 0; break;
325 case 2: SizeIndex = 1; break;
326 case 4: SizeIndex = 2; break;
327 case 8: SizeIndex = 3; break;
328 case 16: SizeIndex = 4; break;
329 default:
330 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
331 << FirstArg->getType() << FirstArg->getSourceRange();
332 }
Mike Stump1eb44332009-09-09 15:08:12 +0000333
Chris Lattner5caa3702009-05-08 06:58:22 +0000334 // Each of these builtins has one pointer argument, followed by some number of
335 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
336 // that we ignore. Find out which row of BuiltinIndices to read from as well
337 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000338 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000339 unsigned BuiltinIndex, NumFixed = 1;
340 switch (BuiltinID) {
341 default: assert(0 && "Unknown overloaded atomic builtin!");
342 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
343 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
344 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
345 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
346 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000347
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000348 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
349 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
350 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
351 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 8; break;
352 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000353
Chris Lattner5caa3702009-05-08 06:58:22 +0000354 case Builtin::BI__sync_val_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000355 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +0000356 NumFixed = 2;
357 break;
358 case Builtin::BI__sync_bool_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000359 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +0000360 NumFixed = 2;
361 break;
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000362 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000363 case Builtin::BI__sync_lock_release:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000364 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000365 NumFixed = 0;
366 break;
367 }
Mike Stump1eb44332009-09-09 15:08:12 +0000368
Chris Lattner5caa3702009-05-08 06:58:22 +0000369 // Now that we know how many fixed arguments we expect, first check that we
370 // have at least that many.
371 if (TheCall->getNumArgs() < 1+NumFixed)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000372 return Diag(TheCall->getLocEnd(),
373 diag::err_typecheck_call_too_few_args_at_least)
374 << 0 << 1+NumFixed << TheCall->getNumArgs()
375 << TheCall->getCallee()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000376
377
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000378 // Get the decl for the concrete builtin from this, we can tell what the
379 // concrete integer type we should convert to is.
380 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
381 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
382 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +0000383 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000384 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
385 TUScope, false, DRE->getLocStart()));
386 const FunctionProtoType *BuiltinFT =
John McCall183700f2009-09-21 23:43:11 +0000387 NewBuiltinDecl->getType()->getAs<FunctionProtoType>();
Ted Kremenek6217b802009-07-29 21:53:49 +0000388 ValType = BuiltinFT->getArgType(0)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000389
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000390 // If the first type needs to be converted (e.g. void** -> int*), do it now.
391 if (BuiltinFT->getArgType(0) != FirstArg->getType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +0000392 ImpCastExprToType(FirstArg, BuiltinFT->getArgType(0), CastExpr::CK_BitCast);
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000393 TheCall->setArg(0, FirstArg);
394 }
Mike Stump1eb44332009-09-09 15:08:12 +0000395
Chris Lattner5caa3702009-05-08 06:58:22 +0000396 // Next, walk the valid ones promoting to the right type.
397 for (unsigned i = 0; i != NumFixed; ++i) {
398 Expr *Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +0000399
Chris Lattner5caa3702009-05-08 06:58:22 +0000400 // If the argument is an implicit cast, then there was a promotion due to
401 // "...", just remove it now.
402 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
403 Arg = ICE->getSubExpr();
404 ICE->setSubExpr(0);
405 ICE->Destroy(Context);
406 TheCall->setArg(i+1, Arg);
407 }
Mike Stump1eb44332009-09-09 15:08:12 +0000408
Chris Lattner5caa3702009-05-08 06:58:22 +0000409 // GCC does an implicit conversion to the pointer or integer ValType. This
410 // can fail in some cases (1i -> int**), check for this error case now.
Anders Carlssoncdb61972009-08-07 22:21:05 +0000411 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Douglas Gregord6e44a32010-04-16 22:09:46 +0000412 if (CheckCastTypes(Arg->getSourceRange(), ValType, Arg, Kind))
Chris Lattner5caa3702009-05-08 06:58:22 +0000413 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000414
Chris Lattner5caa3702009-05-08 06:58:22 +0000415 // Okay, we have something that *can* be converted to the right type. Check
416 // to see if there is a potentially weird extension going on here. This can
417 // happen when you do an atomic operation on something like an char* and
418 // pass in 42. The 42 gets converted to char. This is even more strange
419 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +0000420 // FIXME: Do this check.
Anders Carlssoncdb61972009-08-07 22:21:05 +0000421 ImpCastExprToType(Arg, ValType, Kind, /*isLvalue=*/false);
Chris Lattner5caa3702009-05-08 06:58:22 +0000422 TheCall->setArg(i+1, Arg);
423 }
Mike Stump1eb44332009-09-09 15:08:12 +0000424
Chris Lattner5caa3702009-05-08 06:58:22 +0000425 // Switch the DeclRefExpr to refer to the new decl.
426 DRE->setDecl(NewBuiltinDecl);
427 DRE->setType(NewBuiltinDecl->getType());
Mike Stump1eb44332009-09-09 15:08:12 +0000428
Chris Lattner5caa3702009-05-08 06:58:22 +0000429 // Set the callee in the CallExpr.
430 // FIXME: This leaks the original parens and implicit casts.
431 Expr *PromotedCall = DRE;
432 UsualUnaryConversions(PromotedCall);
433 TheCall->setCallee(PromotedCall);
Mike Stump1eb44332009-09-09 15:08:12 +0000434
Chris Lattner5caa3702009-05-08 06:58:22 +0000435
436 // Change the result type of the call to match the result type of the decl.
437 TheCall->setType(NewBuiltinDecl->getResultType());
438 return false;
439}
440
441
Chris Lattner69039812009-02-18 06:01:06 +0000442/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000443/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +0000444/// FIXME: GCC currently emits the following warning:
Mike Stump1eb44332009-09-09 15:08:12 +0000445/// "warning: input conversion stopped due to an input byte that does not
Steve Narofffd942622009-04-13 20:26:29 +0000446/// belong to the input codeset UTF-8"
447/// Note: It might also make sense to do the UTF-16 conversion here (would
448/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +0000449bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000450 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000451 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
452
453 if (!Literal || Literal->isWide()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000454 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
455 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000456 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000457 }
Mike Stump1eb44332009-09-09 15:08:12 +0000458
Daniel Dunbarf015b032009-09-22 10:03:52 +0000459 const char *Data = Literal->getStrData();
460 unsigned Length = Literal->getByteLength();
Mike Stump1eb44332009-09-09 15:08:12 +0000461
Daniel Dunbarf015b032009-09-22 10:03:52 +0000462 for (unsigned i = 0; i < Length; ++i) {
463 if (!Data[i]) {
464 Diag(getLocationOfStringLiteralByte(Literal, i),
465 diag::warn_cfstring_literal_contains_nul_character)
466 << Arg->getSourceRange();
467 break;
468 }
469 }
Mike Stump1eb44332009-09-09 15:08:12 +0000470
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000471 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000472}
473
Chris Lattnerc27c6652007-12-20 00:05:45 +0000474/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
475/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000476bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
477 Expr *Fn = TheCall->getCallee();
478 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000479 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000480 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000481 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
482 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +0000483 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000484 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000485 return true;
486 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000487
488 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +0000489 return Diag(TheCall->getLocEnd(),
490 diag::err_typecheck_call_too_few_args_at_least)
491 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000492 }
493
Chris Lattnerc27c6652007-12-20 00:05:45 +0000494 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000495 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +0000496 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000497 if (CurBlock)
498 isVariadic = CurBlock->isVariadic;
499 else if (getCurFunctionDecl()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000500 if (FunctionProtoType* FTP =
501 dyn_cast<FunctionProtoType>(getCurFunctionDecl()->getType()))
Eli Friedman56f20ae2008-12-15 22:05:35 +0000502 isVariadic = FTP->isVariadic();
503 else
504 isVariadic = false;
505 } else {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000506 isVariadic = getCurMethodDecl()->isVariadic();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000507 }
Mike Stump1eb44332009-09-09 15:08:12 +0000508
Chris Lattnerc27c6652007-12-20 00:05:45 +0000509 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000510 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
511 return true;
512 }
Mike Stump1eb44332009-09-09 15:08:12 +0000513
Chris Lattner30ce3442007-12-19 23:59:04 +0000514 // Verify that the second argument to the builtin is the last argument of the
515 // current function or method.
516 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000517 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +0000518
Anders Carlsson88cf2262008-02-11 04:20:54 +0000519 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
520 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000521 // FIXME: This isn't correct for methods (results in bogus warning).
522 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000523 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000524 if (CurBlock)
525 LastArg = *(CurBlock->TheDecl->param_end()-1);
526 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +0000527 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000528 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000529 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000530 SecondArgIsLastNamedArgument = PV == LastArg;
531 }
532 }
Mike Stump1eb44332009-09-09 15:08:12 +0000533
Chris Lattner30ce3442007-12-19 23:59:04 +0000534 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +0000535 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000536 diag::warn_second_parameter_of_va_start_not_last_named_argument);
537 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000538}
Chris Lattner30ce3442007-12-19 23:59:04 +0000539
Chris Lattner1b9a0792007-12-20 00:26:33 +0000540/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
541/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000542bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
543 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000544 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000545 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000546 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +0000547 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000548 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000549 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000550 << SourceRange(TheCall->getArg(2)->getLocStart(),
551 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000552
Chris Lattner925e60d2007-12-28 05:29:59 +0000553 Expr *OrigArg0 = TheCall->getArg(0);
554 Expr *OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000555
Chris Lattner1b9a0792007-12-20 00:26:33 +0000556 // Do standard promotions between the two arguments, returning their common
557 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000558 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Daniel Dunbar403bc2b2009-02-19 19:28:43 +0000559
560 // Make sure any conversions are pushed back into the call; this is
561 // type safe since unordered compare builtins are declared as "_Bool
562 // foo(...)".
563 TheCall->setArg(0, OrigArg0);
564 TheCall->setArg(1, OrigArg1);
Mike Stump1eb44332009-09-09 15:08:12 +0000565
Douglas Gregorcde01732009-05-19 22:10:17 +0000566 if (OrigArg0->isTypeDependent() || OrigArg1->isTypeDependent())
567 return false;
568
Chris Lattner1b9a0792007-12-20 00:26:33 +0000569 // If the common type isn't a real floating type, then the arguments were
570 // invalid for this operation.
571 if (!Res->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000572 return Diag(OrigArg0->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000573 diag::err_typecheck_call_invalid_ordered_compare)
Chris Lattnerd1625842008-11-24 06:25:27 +0000574 << OrigArg0->getType() << OrigArg1->getType()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000575 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000576
Chris Lattner1b9a0792007-12-20 00:26:33 +0000577 return false;
578}
579
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000580/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
581/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000582/// to check everything. We expect the last argument to be a floating point
583/// value.
584bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
585 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +0000586 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000587 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000588 if (TheCall->getNumArgs() > NumArgs)
589 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000590 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000591 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000592 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000593 (*(TheCall->arg_end()-1))->getLocEnd());
594
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000595 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +0000596
Eli Friedman9ac6f622009-08-31 20:06:00 +0000597 if (OrigArg->isTypeDependent())
598 return false;
599
600 // This operation requires a floating-point number
601 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000602 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000603 diag::err_typecheck_call_invalid_unary_fp)
604 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000605
Eli Friedman9ac6f622009-08-31 20:06:00 +0000606 return false;
607}
608
Eli Friedman6cfda232008-05-20 08:23:37 +0000609bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) {
610 // The signature for these builtins is exact; the only thing we need
611 // to check is that the argument is a constant.
612 SourceLocation Loc;
Douglas Gregorcde01732009-05-19 22:10:17 +0000613 if (!TheCall->getArg(0)->isTypeDependent() &&
614 !TheCall->getArg(0)->isValueDependent() &&
615 !TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc))
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000616 return Diag(Loc, diag::err_stack_const_level) << TheCall->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000617
Eli Friedman6cfda232008-05-20 08:23:37 +0000618 return false;
619}
620
Eli Friedmand38617c2008-05-14 19:38:39 +0000621/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
622// This is declared to take (...), so we have to check everything.
Sebastian Redl0eb23302009-01-19 00:08:26 +0000623Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000624 if (TheCall->getNumArgs() < 3)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000625 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +0000626 diag::err_typecheck_call_too_few_args_at_least)
627 << 0 /*function call*/ << 3 << TheCall->getNumArgs()
628 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000629
Douglas Gregorcde01732009-05-19 22:10:17 +0000630 unsigned numElements = std::numeric_limits<unsigned>::max();
631 if (!TheCall->getArg(0)->isTypeDependent() &&
632 !TheCall->getArg(1)->isTypeDependent()) {
633 QualType FAType = TheCall->getArg(0)->getType();
634 QualType SAType = TheCall->getArg(1)->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000635
Douglas Gregorcde01732009-05-19 22:10:17 +0000636 if (!FAType->isVectorType() || !SAType->isVectorType()) {
637 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000638 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000639 TheCall->getArg(1)->getLocEnd());
640 return ExprError();
641 }
Mike Stump1eb44332009-09-09 15:08:12 +0000642
Douglas Gregora4923eb2009-11-16 21:35:15 +0000643 if (!Context.hasSameUnqualifiedType(FAType, SAType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000644 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000645 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000646 TheCall->getArg(1)->getLocEnd());
647 return ExprError();
648 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000649
John McCall183700f2009-09-21 23:43:11 +0000650 numElements = FAType->getAs<VectorType>()->getNumElements();
Douglas Gregorcde01732009-05-19 22:10:17 +0000651 if (TheCall->getNumArgs() != numElements+2) {
652 if (TheCall->getNumArgs() < numElements+2)
653 return ExprError(Diag(TheCall->getLocEnd(),
654 diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000655 << 0 /*function call*/
656 << numElements+2 << TheCall->getNumArgs()
657 << TheCall->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000658 return ExprError(Diag(TheCall->getLocEnd(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000659 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000660 << 0 /*function call*/
661 << numElements+2 << TheCall->getNumArgs()
662 << TheCall->getSourceRange());
Douglas Gregorcde01732009-05-19 22:10:17 +0000663 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000664 }
665
666 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000667 if (TheCall->getArg(i)->isTypeDependent() ||
668 TheCall->getArg(i)->isValueDependent())
669 continue;
670
Eli Friedmand38617c2008-05-14 19:38:39 +0000671 llvm::APSInt Result(32);
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000672 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000673 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000674 diag::err_shufflevector_nonconstant_argument)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000675 << TheCall->getArg(i)->getSourceRange());
676
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000677 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000678 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000679 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000680 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000681 }
682
683 llvm::SmallVector<Expr*, 32> exprs;
684
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000685 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000686 exprs.push_back(TheCall->getArg(i));
687 TheCall->setArg(i, 0);
688 }
689
Nate Begemana88dc302009-08-12 02:10:25 +0000690 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
691 exprs.size(), exprs[0]->getType(),
Ted Kremenek8189cde2009-02-07 01:47:29 +0000692 TheCall->getCallee()->getLocStart(),
693 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000694}
Chris Lattner30ce3442007-12-19 23:59:04 +0000695
Daniel Dunbar4493f792008-07-21 22:59:13 +0000696/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
697// This is declared to take (const void*, ...) and can take two
698// optional constant int args.
699bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000700 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000701
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000702 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +0000703 return Diag(TheCall->getLocEnd(),
704 diag::err_typecheck_call_too_many_args_at_most)
705 << 0 /*function call*/ << 3 << NumArgs
706 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000707
708 // Argument 0 is checked for us and the remaining arguments must be
709 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000710 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000711 Expr *Arg = TheCall->getArg(i);
Douglas Gregorcde01732009-05-19 22:10:17 +0000712 if (Arg->isTypeDependent())
713 continue;
714
Eli Friedman9aef7262009-12-04 00:30:06 +0000715 if (!Arg->getType()->isIntegralType())
716 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_arg_type)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000717 << Arg->getSourceRange();
Douglas Gregorcde01732009-05-19 22:10:17 +0000718
Eli Friedman9aef7262009-12-04 00:30:06 +0000719 ImpCastExprToType(Arg, Context.IntTy, CastExpr::CK_IntegralCast);
720 TheCall->setArg(i, Arg);
721
Douglas Gregorcde01732009-05-19 22:10:17 +0000722 if (Arg->isValueDependent())
723 continue;
724
Eli Friedman9aef7262009-12-04 00:30:06 +0000725 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +0000726 if (!Arg->isIntegerConstantExpr(Result, Context))
Eli Friedman9aef7262009-12-04 00:30:06 +0000727 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_arg_ice)
Douglas Gregorcde01732009-05-19 22:10:17 +0000728 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000729
Daniel Dunbar4493f792008-07-21 22:59:13 +0000730 // FIXME: gcc issues a warning and rewrites these to 0. These
731 // seems especially odd for the third argument since the default
732 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000733 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +0000734 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000735 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000736 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000737 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +0000738 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000739 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000740 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000741 }
742 }
743
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000744 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000745}
746
Chris Lattner21fb98e2009-09-23 06:06:36 +0000747/// SemaBuiltinEHReturnDataRegNo - Handle __builtin_eh_return_data_regno, the
748/// operand must be an integer constant.
749bool Sema::SemaBuiltinEHReturnDataRegNo(CallExpr *TheCall) {
750 llvm::APSInt Result;
751 if (!TheCall->getArg(0)->isIntegerConstantExpr(Result, Context))
752 return Diag(TheCall->getLocStart(), diag::err_expr_not_ice)
753 << TheCall->getArg(0)->getSourceRange();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +0000754
Chris Lattner21fb98e2009-09-23 06:06:36 +0000755 return false;
756}
757
758
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000759/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
760/// int type). This simply type checks that type is one of the defined
761/// constants (0-3).
Eric Christopherfee667f2009-12-23 03:49:37 +0000762// For compatability check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000763bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
764 Expr *Arg = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000765 if (Arg->isTypeDependent())
766 return false;
767
Mike Stump1eb44332009-09-09 15:08:12 +0000768 QualType ArgType = Arg->getType();
John McCall183700f2009-09-21 23:43:11 +0000769 const BuiltinType *BT = ArgType->getAs<BuiltinType>();
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000770 llvm::APSInt Result(32);
Douglas Gregorcde01732009-05-19 22:10:17 +0000771 if (!BT || BT->getKind() != BuiltinType::Int)
772 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
773 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
774
775 if (Arg->isValueDependent())
776 return false;
777
778 if (!Arg->isIntegerConstantExpr(Result, Context)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000779 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
780 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000781 }
782
783 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000784 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
785 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000786 }
787
788 return false;
789}
790
Eli Friedman586d6a82009-05-03 06:04:26 +0000791/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +0000792/// This checks that val is a constant 1.
793bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
794 Expr *Arg = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000795 if (Arg->isTypeDependent() || Arg->isValueDependent())
796 return false;
797
Eli Friedmand875fed2009-05-03 04:46:36 +0000798 llvm::APSInt Result(32);
799 if (!Arg->isIntegerConstantExpr(Result, Context) || Result != 1)
800 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
801 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
802
803 return false;
804}
805
Ted Kremenekd30ef872009-01-12 23:09:09 +0000806// Handle i > 1 ? "x" : "y", recursivelly
Ted Kremenek082d9362009-03-20 21:35:28 +0000807bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
808 bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000809 unsigned format_idx, unsigned firstDataArg) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000810 if (E->isTypeDependent() || E->isValueDependent())
811 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000812
813 switch (E->getStmtClass()) {
814 case Stmt::ConditionalOperatorClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000815 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Chris Lattner813b70d2009-12-22 06:00:13 +0000816 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000817 HasVAListArg, format_idx, firstDataArg)
Ted Kremenekd30ef872009-01-12 23:09:09 +0000818 && SemaCheckStringLiteral(C->getRHS(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000819 HasVAListArg, format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000820 }
821
822 case Stmt::ImplicitCastExprClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000823 const ImplicitCastExpr *Expr = cast<ImplicitCastExpr>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000824 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000825 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000826 }
827
828 case Stmt::ParenExprClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000829 const ParenExpr *Expr = cast<ParenExpr>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000830 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000831 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000832 }
Mike Stump1eb44332009-09-09 15:08:12 +0000833
Ted Kremenek082d9362009-03-20 21:35:28 +0000834 case Stmt::DeclRefExprClass: {
835 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000836
Ted Kremenek082d9362009-03-20 21:35:28 +0000837 // As an exception, do not flag errors for variables binding to
838 // const string literals.
839 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
840 bool isConstant = false;
841 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +0000842
Ted Kremenek082d9362009-03-20 21:35:28 +0000843 if (const ArrayType *AT = Context.getAsArrayType(T)) {
844 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000845 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000846 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +0000847 PT->getPointeeType().isConstant(Context);
848 }
Mike Stump1eb44332009-09-09 15:08:12 +0000849
Ted Kremenek082d9362009-03-20 21:35:28 +0000850 if (isConstant) {
Sebastian Redl31310a22010-02-01 20:16:42 +0000851 if (const Expr *Init = VD->getAnyInitializer())
Ted Kremenek082d9362009-03-20 21:35:28 +0000852 return SemaCheckStringLiteral(Init, TheCall,
853 HasVAListArg, format_idx, firstDataArg);
854 }
Mike Stump1eb44332009-09-09 15:08:12 +0000855
Anders Carlssond966a552009-06-28 19:55:58 +0000856 // For vprintf* functions (i.e., HasVAListArg==true), we add a
857 // special check to see if the format string is a function parameter
858 // of the function calling the printf function. If the function
859 // has an attribute indicating it is a printf-like function, then we
860 // should suppress warnings concerning non-literals being used in a call
861 // to a vprintf function. For example:
862 //
863 // void
864 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
865 // va_list ap;
866 // va_start(ap, fmt);
867 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
868 // ...
869 //
870 //
871 // FIXME: We don't have full attribute support yet, so just check to see
872 // if the argument is a DeclRefExpr that references a parameter. We'll
873 // add proper support for checking the attribute later.
874 if (HasVAListArg)
875 if (isa<ParmVarDecl>(VD))
876 return true;
Ted Kremenek082d9362009-03-20 21:35:28 +0000877 }
Mike Stump1eb44332009-09-09 15:08:12 +0000878
Ted Kremenek082d9362009-03-20 21:35:28 +0000879 return false;
880 }
Ted Kremenekd30ef872009-01-12 23:09:09 +0000881
Anders Carlsson8f031b32009-06-27 04:05:33 +0000882 case Stmt::CallExprClass: {
883 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000884 if (const ImplicitCastExpr *ICE
Anders Carlsson8f031b32009-06-27 04:05:33 +0000885 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
886 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
887 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000888 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlsson8f031b32009-06-27 04:05:33 +0000889 unsigned ArgIndex = FA->getFormatIdx();
890 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +0000891
892 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Anders Carlsson8f031b32009-06-27 04:05:33 +0000893 format_idx, firstDataArg);
894 }
895 }
896 }
897 }
Mike Stump1eb44332009-09-09 15:08:12 +0000898
Anders Carlsson8f031b32009-06-27 04:05:33 +0000899 return false;
900 }
Ted Kremenek082d9362009-03-20 21:35:28 +0000901 case Stmt::ObjCStringLiteralClass:
902 case Stmt::StringLiteralClass: {
903 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +0000904
Ted Kremenek082d9362009-03-20 21:35:28 +0000905 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +0000906 StrE = ObjCFExpr->getString();
907 else
Ted Kremenek082d9362009-03-20 21:35:28 +0000908 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000909
Ted Kremenekd30ef872009-01-12 23:09:09 +0000910 if (StrE) {
Mike Stump1eb44332009-09-09 15:08:12 +0000911 CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000912 firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000913 return true;
914 }
Mike Stump1eb44332009-09-09 15:08:12 +0000915
Ted Kremenekd30ef872009-01-12 23:09:09 +0000916 return false;
917 }
Mike Stump1eb44332009-09-09 15:08:12 +0000918
Ted Kremenek082d9362009-03-20 21:35:28 +0000919 default:
920 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000921 }
922}
923
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +0000924void
Mike Stump1eb44332009-09-09 15:08:12 +0000925Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
926 const CallExpr *TheCall) {
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +0000927 for (NonNullAttr::iterator i = NonNull->begin(), e = NonNull->end();
928 i != e; ++i) {
Chris Lattner12b97ff2009-05-25 18:23:36 +0000929 const Expr *ArgExpr = TheCall->getArg(*i);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +0000930 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +0000931 Expr::NPC_ValueDependentIsNotNull))
Chris Lattner12b97ff2009-05-25 18:23:36 +0000932 Diag(TheCall->getCallee()->getLocStart(), diag::warn_null_arg)
933 << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +0000934 }
935}
Ted Kremenekd30ef872009-01-12 23:09:09 +0000936
Chris Lattner59907c42007-08-10 20:18:51 +0000937/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Mike Stump1eb44332009-09-09 15:08:12 +0000938/// correct use of format strings.
Ted Kremenek71895b92007-08-14 17:39:48 +0000939///
940/// HasVAListArg - A predicate indicating whether the printf-like
941/// function is passed an explicit va_arg argument (e.g., vprintf)
942///
943/// format_idx - The index into Args for the format string.
944///
945/// Improper format strings to functions in the printf family can be
946/// the source of bizarre bugs and very serious security holes. A
947/// good source of information is available in the following paper
948/// (which includes additional references):
Chris Lattner59907c42007-08-10 20:18:51 +0000949///
950/// FormatGuard: Automatic Protection From printf Format String
951/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremenek71895b92007-08-14 17:39:48 +0000952///
Ted Kremenek7f70dc82010-02-26 19:18:41 +0000953/// TODO:
Ted Kremenek71895b92007-08-14 17:39:48 +0000954/// Functionality implemented:
955///
956/// We can statically check the following properties for string
957/// literal format strings for non v.*printf functions (where the
958/// arguments are passed directly):
959//
960/// (1) Are the number of format conversions equal to the number of
961/// data arguments?
962///
963/// (2) Does each format conversion correctly match the type of the
Ted Kremenek7f70dc82010-02-26 19:18:41 +0000964/// corresponding data argument?
Ted Kremenek71895b92007-08-14 17:39:48 +0000965///
966/// Moreover, for all printf functions we can:
967///
968/// (3) Check for a missing format string (when not caught by type checking).
969///
970/// (4) Check for no-operation flags; e.g. using "#" with format
971/// conversion 'c' (TODO)
972///
973/// (5) Check the use of '%n', a major source of security holes.
974///
975/// (6) Check for malformed format conversions that don't specify anything.
976///
977/// (7) Check for empty format strings. e.g: printf("");
978///
979/// (8) Check that the format string is a wide literal.
980///
981/// All of these checks can be done by parsing the format string.
982///
Chris Lattner59907c42007-08-10 20:18:51 +0000983void
Mike Stump1eb44332009-09-09 15:08:12 +0000984Sema::CheckPrintfArguments(const CallExpr *TheCall, bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000985 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenek082d9362009-03-20 21:35:28 +0000986 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +0000987
Sebastian Redl4a2614e2009-11-17 18:02:24 +0000988 // The way the format attribute works in GCC, the implicit this argument
989 // of member functions is counted. However, it doesn't appear in our own
990 // lists, so decrement format_idx in that case.
991 if (isa<CXXMemberCallExpr>(TheCall)) {
992 // Catch a format attribute mistakenly referring to the object argument.
993 if (format_idx == 0)
994 return;
995 --format_idx;
996 if(firstDataArg != 0)
997 --firstDataArg;
998 }
999
Mike Stump1eb44332009-09-09 15:08:12 +00001000 // CHECK: printf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +00001001 if (format_idx >= TheCall->getNumArgs()) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001002 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string)
1003 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001004 return;
1005 }
Mike Stump1eb44332009-09-09 15:08:12 +00001006
Ted Kremenek082d9362009-03-20 21:35:28 +00001007 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001008
Chris Lattner59907c42007-08-10 20:18:51 +00001009 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001010 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001011 // Dynamically generated format strings are difficult to
1012 // automatically vet at compile time. Requiring that format strings
1013 // are string literals: (1) permits the checking of format strings by
1014 // the compiler and thereby (2) can practically remove the source of
1015 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001016
Mike Stump1eb44332009-09-09 15:08:12 +00001017 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001018 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001019 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001020 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001021 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
1022 firstDataArg))
1023 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001024
Chris Lattner655f1412009-04-29 04:59:47 +00001025 // If there are no arguments specified, warn with -Wformat-security, otherwise
1026 // warn only with -Wformat-nonliteral.
1027 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump1eb44332009-09-09 15:08:12 +00001028 Diag(TheCall->getArg(format_idx)->getLocStart(),
Chris Lattner655f1412009-04-29 04:59:47 +00001029 diag::warn_printf_nonliteral_noargs)
1030 << OrigFormatExpr->getSourceRange();
1031 else
Mike Stump1eb44332009-09-09 15:08:12 +00001032 Diag(TheCall->getArg(format_idx)->getLocStart(),
Chris Lattner655f1412009-04-29 04:59:47 +00001033 diag::warn_printf_nonliteral)
1034 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001035}
Ted Kremenek71895b92007-08-14 17:39:48 +00001036
Ted Kremeneke0e53132010-01-28 23:39:18 +00001037namespace {
Ted Kremenek74d56a12010-02-04 20:46:58 +00001038class CheckPrintfHandler : public analyze_printf::FormatStringHandler {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001039 Sema &S;
1040 const StringLiteral *FExpr;
1041 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001042 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001043 const unsigned NumDataArgs;
1044 const bool IsObjCLiteral;
1045 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001046 const bool HasVAListArg;
1047 const CallExpr *TheCall;
1048 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001049 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001050 bool usesPositionalArgs;
1051 bool atFirstArg;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001052public:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001053 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001054 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001055 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001056 const char *beg, bool hasVAListArg,
1057 const CallExpr *theCall, unsigned formatIdx)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001058 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek6ee76532010-03-25 03:59:12 +00001059 FirstDataArg(firstDataArg),
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001060 NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001061 IsObjCLiteral(isObjCLiteral), Beg(beg),
1062 HasVAListArg(hasVAListArg),
Ted Kremenekefaff192010-02-27 01:41:03 +00001063 TheCall(theCall), FormatIdx(formatIdx),
1064 usesPositionalArgs(false), atFirstArg(true) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001065 CoveredArgs.resize(numDataArgs);
1066 CoveredArgs.reset();
1067 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001068
Ted Kremenek07d161f2010-01-29 01:50:07 +00001069 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001070
Ted Kremenek808015a2010-01-29 03:16:21 +00001071 void HandleIncompleteFormatSpecifier(const char *startSpecifier,
1072 unsigned specifierLen);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001073
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001074 bool
Ted Kremenek74d56a12010-02-04 20:46:58 +00001075 HandleInvalidConversionSpecifier(const analyze_printf::FormatSpecifier &FS,
1076 const char *startSpecifier,
1077 unsigned specifierLen);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001078
Ted Kremenekefaff192010-02-27 01:41:03 +00001079 virtual void HandleInvalidPosition(const char *startSpecifier,
1080 unsigned specifierLen,
1081 analyze_printf::PositionContext p);
1082
1083 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1084
Ted Kremeneke0e53132010-01-28 23:39:18 +00001085 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001086
Ted Kremeneke0e53132010-01-28 23:39:18 +00001087 bool HandleFormatSpecifier(const analyze_printf::FormatSpecifier &FS,
1088 const char *startSpecifier,
1089 unsigned specifierLen);
1090private:
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001091 SourceRange getFormatStringRange();
1092 SourceRange getFormatSpecifierRange(const char *startSpecifier,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001093 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001094 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001095
Ted Kremenekefaff192010-02-27 01:41:03 +00001096 bool HandleAmount(const analyze_printf::OptionalAmount &Amt, unsigned k,
1097 const char *startSpecifier, unsigned specifierLen);
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001098 void HandleFlags(const analyze_printf::FormatSpecifier &FS,
1099 llvm::StringRef flag, llvm::StringRef cspec,
1100 const char *startSpecifier, unsigned specifierLen);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001101
Ted Kremenek0d277352010-01-29 01:06:55 +00001102 const Expr *getDataArg(unsigned i) const;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001103};
1104}
1105
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001106SourceRange CheckPrintfHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001107 return OrigFormatExpr->getSourceRange();
1108}
1109
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001110SourceRange CheckPrintfHandler::
1111getFormatSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
1112 return SourceRange(getLocationOfByte(startSpecifier),
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001113 getLocationOfByte(startSpecifier+specifierLen-1));
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001114}
1115
Ted Kremeneke0e53132010-01-28 23:39:18 +00001116SourceLocation CheckPrintfHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001117 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001118}
1119
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001120void CheckPrintfHandler::
Ted Kremenek808015a2010-01-29 03:16:21 +00001121HandleIncompleteFormatSpecifier(const char *startSpecifier,
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001122 unsigned specifierLen) {
Ted Kremenek808015a2010-01-29 03:16:21 +00001123 SourceLocation Loc = getLocationOfByte(startSpecifier);
1124 S.Diag(Loc, diag::warn_printf_incomplete_specifier)
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001125 << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek808015a2010-01-29 03:16:21 +00001126}
1127
Ted Kremenekefaff192010-02-27 01:41:03 +00001128void
1129CheckPrintfHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1130 analyze_printf::PositionContext p) {
1131 SourceLocation Loc = getLocationOfByte(startPos);
1132 S.Diag(Loc, diag::warn_printf_invalid_positional_specifier)
1133 << (unsigned) p << getFormatSpecifierRange(startPos, posLen);
1134}
1135
1136void CheckPrintfHandler::HandleZeroPosition(const char *startPos,
1137 unsigned posLen) {
1138 SourceLocation Loc = getLocationOfByte(startPos);
1139 S.Diag(Loc, diag::warn_printf_zero_positional_specifier)
1140 << getFormatSpecifierRange(startPos, posLen);
1141}
1142
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001143bool CheckPrintfHandler::
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001144HandleInvalidConversionSpecifier(const analyze_printf::FormatSpecifier &FS,
1145 const char *startSpecifier,
1146 unsigned specifierLen) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001147
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001148 unsigned argIndex = FS.getArgIndex();
1149 bool keepGoing = true;
1150 if (argIndex < NumDataArgs) {
1151 // Consider the argument coverered, even though the specifier doesn't
1152 // make sense.
1153 CoveredArgs.set(argIndex);
1154 }
1155 else {
1156 // If argIndex exceeds the number of data arguments we
1157 // don't issue a warning because that is just a cascade of warnings (and
1158 // they may have intended '%%' anyway). We don't want to continue processing
1159 // the format string after this point, however, as we will like just get
1160 // gibberish when trying to match arguments.
1161 keepGoing = false;
1162 }
1163
Ted Kremenek808015a2010-01-29 03:16:21 +00001164 const analyze_printf::ConversionSpecifier &CS =
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001165 FS.getConversionSpecifier();
Ted Kremenek808015a2010-01-29 03:16:21 +00001166 SourceLocation Loc = getLocationOfByte(CS.getStart());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001167 S.Diag(Loc, diag::warn_printf_invalid_conversion)
Ted Kremenek808015a2010-01-29 03:16:21 +00001168 << llvm::StringRef(CS.getStart(), CS.getLength())
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001169 << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001170
1171 return keepGoing;
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001172}
1173
Ted Kremeneke0e53132010-01-28 23:39:18 +00001174void CheckPrintfHandler::HandleNullChar(const char *nullCharacter) {
1175 // The presence of a null character is likely an error.
1176 S.Diag(getLocationOfByte(nullCharacter),
1177 diag::warn_printf_format_string_contains_null_char)
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001178 << getFormatStringRange();
Ted Kremeneke0e53132010-01-28 23:39:18 +00001179}
1180
Ted Kremenek0d277352010-01-29 01:06:55 +00001181const Expr *CheckPrintfHandler::getDataArg(unsigned i) const {
Ted Kremenek6ee76532010-03-25 03:59:12 +00001182 return TheCall->getArg(FirstDataArg + i);
Ted Kremenek0d277352010-01-29 01:06:55 +00001183}
1184
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001185void CheckPrintfHandler::HandleFlags(const analyze_printf::FormatSpecifier &FS,
1186 llvm::StringRef flag,
1187 llvm::StringRef cspec,
1188 const char *startSpecifier,
1189 unsigned specifierLen) {
1190 const analyze_printf::ConversionSpecifier &CS = FS.getConversionSpecifier();
1191 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_nonsensical_flag)
1192 << flag << cspec << getFormatSpecifierRange(startSpecifier, specifierLen);
1193}
1194
Ted Kremenek0d277352010-01-29 01:06:55 +00001195bool
1196CheckPrintfHandler::HandleAmount(const analyze_printf::OptionalAmount &Amt,
Ted Kremenekefaff192010-02-27 01:41:03 +00001197 unsigned k, const char *startSpecifier,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001198 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001199
1200 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001201 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001202 unsigned argIndex = Amt.getArgIndex();
1203 if (argIndex >= NumDataArgs) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001204 S.Diag(getLocationOfByte(Amt.getStart()),
1205 diag::warn_printf_asterisk_missing_arg)
1206 << k << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek0d277352010-01-29 01:06:55 +00001207 // Don't do any more checking. We will just emit
1208 // spurious errors.
1209 return false;
1210 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001211
Ted Kremenek0d277352010-01-29 01:06:55 +00001212 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00001213 // Although not in conformance with C99, we also allow the argument to be
1214 // an 'unsigned int' as that is a reasonably safe case. GCC also
1215 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001216 CoveredArgs.set(argIndex);
1217 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00001218 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001219
1220 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1221 assert(ATR.isValid());
1222
1223 if (!ATR.matchesType(S.Context, T)) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001224 S.Diag(getLocationOfByte(Amt.getStart()),
1225 diag::warn_printf_asterisk_wrong_type)
1226 << k
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001227 << ATR.getRepresentativeType(S.Context) << T
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001228 << getFormatSpecifierRange(startSpecifier, specifierLen)
1229 << Arg->getSourceRange();
Ted Kremenek0d277352010-01-29 01:06:55 +00001230 // Don't do any more checking. We will just emit
1231 // spurious errors.
1232 return false;
1233 }
1234 }
1235 }
1236 return true;
1237}
Ted Kremenek0d277352010-01-29 01:06:55 +00001238
Ted Kremeneke0e53132010-01-28 23:39:18 +00001239bool
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001240CheckPrintfHandler::HandleFormatSpecifier(const analyze_printf::FormatSpecifier
1241 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001242 const char *startSpecifier,
1243 unsigned specifierLen) {
1244
Ted Kremenekefaff192010-02-27 01:41:03 +00001245 using namespace analyze_printf;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001246 const ConversionSpecifier &CS = FS.getConversionSpecifier();
1247
Ted Kremenekefaff192010-02-27 01:41:03 +00001248 if (atFirstArg) {
1249 atFirstArg = false;
1250 usesPositionalArgs = FS.usesPositionalArg();
1251 }
1252 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1253 // Cannot mix-and-match positional and non-positional arguments.
1254 S.Diag(getLocationOfByte(CS.getStart()),
1255 diag::warn_printf_mix_positional_nonpositional_args)
1256 << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek0d277352010-01-29 01:06:55 +00001257 return false;
1258 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001259
Ted Kremenekefaff192010-02-27 01:41:03 +00001260 // First check if the field width, precision, and conversion specifier
1261 // have matching data arguments.
1262 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1263 startSpecifier, specifierLen)) {
1264 return false;
1265 }
1266
1267 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1268 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001269 return false;
1270 }
1271
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001272 if (!CS.consumesDataArgument()) {
1273 // FIXME: Technically specifying a precision or field width here
1274 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001275 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001276 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001277
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001278 // Consume the argument.
1279 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00001280 if (argIndex < NumDataArgs) {
1281 // The check to see if the argIndex is valid will come later.
1282 // We set the bit here because we may exit early from this
1283 // function if we encounter some other error.
1284 CoveredArgs.set(argIndex);
1285 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001286
1287 // Check for using an Objective-C specific conversion specifier
1288 // in a non-ObjC literal.
1289 if (!IsObjCLiteral && CS.isObjCArg()) {
1290 return HandleInvalidConversionSpecifier(FS, startSpecifier, specifierLen);
1291 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001292
Ted Kremeneke82d8042010-01-29 01:35:25 +00001293 // Are we using '%n'? Issue a warning about this being
1294 // a possible security issue.
1295 if (CS.getKind() == ConversionSpecifier::OutIntPtrArg) {
1296 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001297 << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremeneke82d8042010-01-29 01:35:25 +00001298 // Continue checking the other format specifiers.
1299 return true;
1300 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001301
1302 if (CS.getKind() == ConversionSpecifier::VoidPtrArg) {
1303 if (FS.getPrecision().getHowSpecified() != OptionalAmount::NotSpecified)
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001304 S.Diag(getLocationOfByte(CS.getStart()),
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001305 diag::warn_printf_nonsensical_precision)
1306 << CS.getCharacters()
1307 << getFormatSpecifierRange(startSpecifier, specifierLen);
1308 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001309 if (CS.getKind() == ConversionSpecifier::VoidPtrArg ||
1310 CS.getKind() == ConversionSpecifier::CStrArg) {
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001311 // FIXME: Instead of using "0", "+", etc., eventually get them from
1312 // the FormatSpecifier.
1313 if (FS.hasLeadingZeros())
1314 HandleFlags(FS, "0", CS.getCharacters(), startSpecifier, specifierLen);
1315 if (FS.hasPlusPrefix())
1316 HandleFlags(FS, "+", CS.getCharacters(), startSpecifier, specifierLen);
1317 if (FS.hasSpacePrefix())
1318 HandleFlags(FS, " ", CS.getCharacters(), startSpecifier, specifierLen);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001319 }
1320
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001321 // The remaining checks depend on the data arguments.
1322 if (HasVAListArg)
1323 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001324
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001325 if (argIndex >= NumDataArgs) {
Ted Kremenek6ee76532010-03-25 03:59:12 +00001326 if (FS.usesPositionalArg()) {
1327 S.Diag(getLocationOfByte(CS.getStart()),
1328 diag::warn_printf_positional_arg_exceeds_data_args)
1329 << (argIndex+1) << NumDataArgs
1330 << getFormatSpecifierRange(startSpecifier, specifierLen);
1331 }
1332 else {
1333 S.Diag(getLocationOfByte(CS.getStart()),
1334 diag::warn_printf_insufficient_data_args)
1335 << getFormatSpecifierRange(startSpecifier, specifierLen);
1336 }
1337
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001338 // Don't do any more checking.
1339 return false;
1340 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001341
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001342 // Now type check the data expression that matches the
1343 // format specifier.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001344 const Expr *Ex = getDataArg(argIndex);
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001345 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001346 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
1347 // Check if we didn't match because of an implicit cast from a 'char'
1348 // or 'short' to an 'int'. This is done because printf is a varargs
1349 // function.
1350 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
1351 if (ICE->getType() == S.Context.IntTy)
1352 if (ATR.matchesType(S.Context, ICE->getSubExpr()->getType()))
1353 return true;
Ted Kremenek105d41c2010-02-01 19:38:10 +00001354
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001355 S.Diag(getLocationOfByte(CS.getStart()),
1356 diag::warn_printf_conversion_argument_type_mismatch)
1357 << ATR.getRepresentativeType(S.Context) << Ex->getType()
Ted Kremenek1497bff2010-02-11 19:37:25 +00001358 << getFormatSpecifierRange(startSpecifier, specifierLen)
1359 << Ex->getSourceRange();
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001360 }
Ted Kremeneke0e53132010-01-28 23:39:18 +00001361
1362 return true;
1363}
1364
Ted Kremenek07d161f2010-01-29 01:50:07 +00001365void CheckPrintfHandler::DoneProcessing() {
1366 // Does the number of data arguments exceed the number of
1367 // format conversions in the format string?
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001368 if (!HasVAListArg) {
1369 // Find any arguments that weren't covered.
1370 CoveredArgs.flip();
1371 signed notCoveredArg = CoveredArgs.find_first();
1372 if (notCoveredArg >= 0) {
1373 assert((unsigned)notCoveredArg < NumDataArgs);
1374 S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(),
1375 diag::warn_printf_data_arg_not_used)
1376 << getFormatStringRange();
1377 }
1378 }
Ted Kremenek07d161f2010-01-29 01:50:07 +00001379}
Ted Kremeneke0e53132010-01-28 23:39:18 +00001380
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001381void Sema::CheckPrintfString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001382 const Expr *OrigFormatExpr,
1383 const CallExpr *TheCall, bool HasVAListArg,
1384 unsigned format_idx, unsigned firstDataArg) {
1385
Ted Kremeneke0e53132010-01-28 23:39:18 +00001386 // CHECK: is the format string a wide literal?
1387 if (FExpr->isWide()) {
1388 Diag(FExpr->getLocStart(),
1389 diag::warn_printf_format_string_is_wide_literal)
1390 << OrigFormatExpr->getSourceRange();
1391 return;
1392 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001393
Ted Kremeneke0e53132010-01-28 23:39:18 +00001394 // Str - The format string. NOTE: this is NOT null-terminated!
1395 const char *Str = FExpr->getStrData();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001396
Ted Kremeneke0e53132010-01-28 23:39:18 +00001397 // CHECK: empty format string?
1398 unsigned StrLen = FExpr->getByteLength();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001399
Ted Kremeneke0e53132010-01-28 23:39:18 +00001400 if (StrLen == 0) {
1401 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string)
1402 << OrigFormatExpr->getSourceRange();
1403 return;
1404 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001405
Ted Kremenek6ee76532010-03-25 03:59:12 +00001406 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001407 TheCall->getNumArgs() - firstDataArg,
Ted Kremenek0d277352010-01-29 01:06:55 +00001408 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1409 HasVAListArg, TheCall, format_idx);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001410
Ted Kremenek74d56a12010-02-04 20:46:58 +00001411 if (!analyze_printf::ParseFormatString(H, Str, Str + StrLen))
Ted Kremenek808015a2010-01-29 03:16:21 +00001412 H.DoneProcessing();
Ted Kremenekce7024e2010-01-28 01:18:22 +00001413}
1414
Ted Kremenek06de2762007-08-17 16:46:58 +00001415//===--- CHECK: Return Address of Stack Variable --------------------------===//
1416
1417static DeclRefExpr* EvalVal(Expr *E);
1418static DeclRefExpr* EvalAddr(Expr* E);
1419
1420/// CheckReturnStackAddr - Check if a return statement returns the address
1421/// of a stack variable.
1422void
1423Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1424 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00001425
Ted Kremenek06de2762007-08-17 16:46:58 +00001426 // Perform checking for returned stack addresses.
Steve Naroffdd972f22008-09-05 22:11:13 +00001427 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Ted Kremenek06de2762007-08-17 16:46:58 +00001428 if (DeclRefExpr *DR = EvalAddr(RetValExp))
Chris Lattner3c73c412008-11-19 08:23:25 +00001429 Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
Chris Lattner08631c52008-11-23 21:45:46 +00001430 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001431
Steve Naroffc50a4a52008-09-16 22:25:10 +00001432 // Skip over implicit cast expressions when checking for block expressions.
Chris Lattner4ca606e2009-09-08 00:36:37 +00001433 RetValExp = RetValExp->IgnoreParenCasts();
Steve Naroffc50a4a52008-09-16 22:25:10 +00001434
Chris Lattner9e6b37a2009-10-30 04:01:58 +00001435 if (BlockExpr *C = dyn_cast<BlockExpr>(RetValExp))
Mike Stump397195b2009-04-17 00:09:41 +00001436 if (C->hasBlockDeclRefExprs())
1437 Diag(C->getLocStart(), diag::err_ret_local_block)
1438 << C->getSourceRange();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001439
Chris Lattner9e6b37a2009-10-30 04:01:58 +00001440 if (AddrLabelExpr *ALE = dyn_cast<AddrLabelExpr>(RetValExp))
1441 Diag(ALE->getLocStart(), diag::warn_ret_addr_label)
1442 << ALE->getSourceRange();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001443
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001444 } else if (lhsType->isReferenceType()) {
1445 // Perform checking for stack values returned by reference.
Douglas Gregor49badde2008-10-27 19:41:14 +00001446 // Check for a reference to the stack
1447 if (DeclRefExpr *DR = EvalVal(RetValExp))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001448 Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
Chris Lattner08631c52008-11-23 21:45:46 +00001449 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +00001450 }
1451}
1452
1453/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1454/// check if the expression in a return statement evaluates to an address
1455/// to a location on the stack. The recursion is used to traverse the
1456/// AST of the return expression, with recursion backtracking when we
1457/// encounter a subexpression that (1) clearly does not lead to the address
1458/// of a stack variable or (2) is something we cannot determine leads to
1459/// the address of a stack variable based on such local checking.
1460///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001461/// EvalAddr processes expressions that are pointers that are used as
1462/// references (and not L-values). EvalVal handles all other values.
Mike Stump1eb44332009-09-09 15:08:12 +00001463/// At the base case of the recursion is a check for a DeclRefExpr* in
Ted Kremenek06de2762007-08-17 16:46:58 +00001464/// the refers to a stack variable.
1465///
1466/// This implementation handles:
1467///
1468/// * pointer-to-pointer casts
1469/// * implicit conversions from array references to pointers
1470/// * taking the address of fields
1471/// * arbitrary interplay between "&" and "*" operators
1472/// * pointer arithmetic from an address of a stack variable
1473/// * taking the address of an array element where the array is on the stack
1474static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek06de2762007-08-17 16:46:58 +00001475 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00001476 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00001477 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001478 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001479 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00001480
Ted Kremenek06de2762007-08-17 16:46:58 +00001481 // Our "symbolic interpreter" is just a dispatch off the currently
1482 // viewed AST node. We then recursively traverse the AST by calling
1483 // EvalAddr and EvalVal appropriately.
1484 switch (E->getStmtClass()) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001485 case Stmt::ParenExprClass:
1486 // Ignore parentheses.
1487 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek06de2762007-08-17 16:46:58 +00001488
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001489 case Stmt::UnaryOperatorClass: {
1490 // The only unary operator that make sense to handle here
1491 // is AddrOf. All others don't make sense as pointers.
1492 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001493
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001494 if (U->getOpcode() == UnaryOperator::AddrOf)
1495 return EvalVal(U->getSubExpr());
1496 else
Ted Kremenek06de2762007-08-17 16:46:58 +00001497 return NULL;
1498 }
Mike Stump1eb44332009-09-09 15:08:12 +00001499
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001500 case Stmt::BinaryOperatorClass: {
1501 // Handle pointer arithmetic. All other binary operators are not valid
1502 // in this context.
1503 BinaryOperator *B = cast<BinaryOperator>(E);
1504 BinaryOperator::Opcode op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00001505
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001506 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
1507 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001508
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001509 Expr *Base = B->getLHS();
1510
1511 // Determine which argument is the real pointer base. It could be
1512 // the RHS argument instead of the LHS.
1513 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00001514
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001515 assert (Base->getType()->isPointerType());
1516 return EvalAddr(Base);
1517 }
Steve Naroff61f40a22008-09-10 19:17:48 +00001518
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001519 // For conditional operators we need to see if either the LHS or RHS are
1520 // valid DeclRefExpr*s. If one of them is valid, we return it.
1521 case Stmt::ConditionalOperatorClass: {
1522 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001523
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001524 // Handle the GNU extension for missing LHS.
1525 if (Expr *lhsExpr = C->getLHS())
1526 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
1527 return LHS;
1528
1529 return EvalAddr(C->getRHS());
1530 }
Mike Stump1eb44332009-09-09 15:08:12 +00001531
Ted Kremenek54b52742008-08-07 00:49:01 +00001532 // For casts, we need to handle conversions from arrays to
1533 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00001534 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001535 case Stmt::CStyleCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001536 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001537 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00001538 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001539
Steve Naroffdd972f22008-09-05 22:11:13 +00001540 if (SubExpr->getType()->isPointerType() ||
1541 SubExpr->getType()->isBlockPointerType() ||
1542 SubExpr->getType()->isObjCQualifiedIdType())
Ted Kremenek54b52742008-08-07 00:49:01 +00001543 return EvalAddr(SubExpr);
1544 else if (T->isArrayType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001545 return EvalVal(SubExpr);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001546 else
Ted Kremenek54b52742008-08-07 00:49:01 +00001547 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001548 }
Mike Stump1eb44332009-09-09 15:08:12 +00001549
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001550 // C++ casts. For dynamic casts, static casts, and const casts, we
1551 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00001552 // through the cast. In the case the dynamic cast doesn't fail (and
1553 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001554 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00001555 // FIXME: The comment about is wrong; we're not always converting
1556 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00001557 // handle references to objects.
1558 case Stmt::CXXStaticCastExprClass:
1559 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001560 case Stmt::CXXConstCastExprClass:
1561 case Stmt::CXXReinterpretCastExprClass: {
1562 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00001563 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001564 return EvalAddr(S);
1565 else
1566 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001567 }
Mike Stump1eb44332009-09-09 15:08:12 +00001568
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001569 // Everything else: we simply don't reason about them.
1570 default:
1571 return NULL;
1572 }
Ted Kremenek06de2762007-08-17 16:46:58 +00001573}
Mike Stump1eb44332009-09-09 15:08:12 +00001574
Ted Kremenek06de2762007-08-17 16:46:58 +00001575
1576/// EvalVal - This function is complements EvalAddr in the mutual recursion.
1577/// See the comments for EvalAddr for more details.
1578static DeclRefExpr* EvalVal(Expr *E) {
Mike Stump1eb44332009-09-09 15:08:12 +00001579
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001580 // We should only be called for evaluating non-pointer expressions, or
1581 // expressions with a pointer type that are not used as references but instead
1582 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00001583
Ted Kremenek06de2762007-08-17 16:46:58 +00001584 // Our "symbolic interpreter" is just a dispatch off the currently
1585 // viewed AST node. We then recursively traverse the AST by calling
1586 // EvalAddr and EvalVal appropriately.
1587 switch (E->getStmtClass()) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00001588 case Stmt::DeclRefExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00001589 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
1590 // at code that refers to a variable's name. We check if it has local
1591 // storage within the function, and if so, return the expression.
1592 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001593
Ted Kremenek06de2762007-08-17 16:46:58 +00001594 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Mike Stump1eb44332009-09-09 15:08:12 +00001595 if (V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
1596
Ted Kremenek06de2762007-08-17 16:46:58 +00001597 return NULL;
1598 }
Mike Stump1eb44332009-09-09 15:08:12 +00001599
Ted Kremenek06de2762007-08-17 16:46:58 +00001600 case Stmt::ParenExprClass:
1601 // Ignore parentheses.
1602 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
Mike Stump1eb44332009-09-09 15:08:12 +00001603
Ted Kremenek06de2762007-08-17 16:46:58 +00001604 case Stmt::UnaryOperatorClass: {
1605 // The only unary operator that make sense to handle here
1606 // is Deref. All others don't resolve to a "name." This includes
1607 // handling all sorts of rvalues passed to a unary operator.
1608 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001609
Ted Kremenek06de2762007-08-17 16:46:58 +00001610 if (U->getOpcode() == UnaryOperator::Deref)
1611 return EvalAddr(U->getSubExpr());
1612
1613 return NULL;
1614 }
Mike Stump1eb44332009-09-09 15:08:12 +00001615
Ted Kremenek06de2762007-08-17 16:46:58 +00001616 case Stmt::ArraySubscriptExprClass: {
1617 // Array subscripts are potential references to data on the stack. We
1618 // retrieve the DeclRefExpr* for the array variable if it indeed
1619 // has local storage.
Ted Kremenek23245122007-08-20 16:18:38 +00001620 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek06de2762007-08-17 16:46:58 +00001621 }
Mike Stump1eb44332009-09-09 15:08:12 +00001622
Ted Kremenek06de2762007-08-17 16:46:58 +00001623 case Stmt::ConditionalOperatorClass: {
1624 // For conditional operators we need to see if either the LHS or RHS are
1625 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
1626 ConditionalOperator *C = cast<ConditionalOperator>(E);
1627
Anders Carlsson39073232007-11-30 19:04:31 +00001628 // Handle the GNU extension for missing LHS.
1629 if (Expr *lhsExpr = C->getLHS())
1630 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
1631 return LHS;
1632
1633 return EvalVal(C->getRHS());
Ted Kremenek06de2762007-08-17 16:46:58 +00001634 }
Mike Stump1eb44332009-09-09 15:08:12 +00001635
Ted Kremenek06de2762007-08-17 16:46:58 +00001636 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00001637 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00001638 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001639
Ted Kremenek06de2762007-08-17 16:46:58 +00001640 // Check for indirect access. We only want direct field accesses.
1641 if (!M->isArrow())
1642 return EvalVal(M->getBase());
1643 else
1644 return NULL;
1645 }
Mike Stump1eb44332009-09-09 15:08:12 +00001646
Ted Kremenek06de2762007-08-17 16:46:58 +00001647 // Everything else: we simply don't reason about them.
1648 default:
1649 return NULL;
1650 }
1651}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001652
1653//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
1654
1655/// Check for comparisons of floating point operands using != and ==.
1656/// Issue a warning if these are no self-comparisons, as they are not likely
1657/// to do what the programmer intended.
1658void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
1659 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001660
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00001661 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek32e97b62008-01-17 17:55:13 +00001662 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001663
1664 // Special case: check for x == x (which is OK).
1665 // Do not emit warnings for such cases.
1666 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
1667 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
1668 if (DRL->getDecl() == DRR->getDecl())
1669 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001670
1671
Ted Kremenek1b500bb2007-11-29 00:59:04 +00001672 // Special case: check for comparisons against literals that can be exactly
1673 // represented by APFloat. In such cases, do not emit a warning. This
1674 // is a heuristic: often comparison against such literals are used to
1675 // detect if a value in a variable has not changed. This clearly can
1676 // lead to false negatives.
1677 if (EmitWarning) {
1678 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
1679 if (FLL->isExact())
1680 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001681 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00001682 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
1683 if (FLR->isExact())
1684 EmitWarning = false;
1685 }
1686 }
Mike Stump1eb44332009-09-09 15:08:12 +00001687
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001688 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001689 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001690 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001691 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001692 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001693
Sebastian Redl0eb23302009-01-19 00:08:26 +00001694 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001695 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001696 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001697 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001698
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001699 // Emit the diagnostic.
1700 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001701 Diag(loc, diag::warn_floatingpoint_eq)
1702 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001703}
John McCallba26e582010-01-04 23:21:16 +00001704
John McCallf2370c92010-01-06 05:24:50 +00001705//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
1706//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00001707
John McCallf2370c92010-01-06 05:24:50 +00001708namespace {
John McCallba26e582010-01-04 23:21:16 +00001709
John McCallf2370c92010-01-06 05:24:50 +00001710/// Structure recording the 'active' range of an integer-valued
1711/// expression.
1712struct IntRange {
1713 /// The number of bits active in the int.
1714 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00001715
John McCallf2370c92010-01-06 05:24:50 +00001716 /// True if the int is known not to have negative values.
1717 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00001718
John McCallf2370c92010-01-06 05:24:50 +00001719 IntRange() {}
1720 IntRange(unsigned Width, bool NonNegative)
1721 : Width(Width), NonNegative(NonNegative)
1722 {}
John McCallba26e582010-01-04 23:21:16 +00001723
John McCallf2370c92010-01-06 05:24:50 +00001724 // Returns the range of the bool type.
1725 static IntRange forBoolType() {
1726 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00001727 }
1728
John McCallf2370c92010-01-06 05:24:50 +00001729 // Returns the range of an integral type.
1730 static IntRange forType(ASTContext &C, QualType T) {
1731 return forCanonicalType(C, T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00001732 }
1733
John McCallf2370c92010-01-06 05:24:50 +00001734 // Returns the range of an integeral type based on its canonical
1735 // representation.
1736 static IntRange forCanonicalType(ASTContext &C, const Type *T) {
1737 assert(T->isCanonicalUnqualified());
1738
1739 if (const VectorType *VT = dyn_cast<VectorType>(T))
1740 T = VT->getElementType().getTypePtr();
1741 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
1742 T = CT->getElementType().getTypePtr();
1743 if (const EnumType *ET = dyn_cast<EnumType>(T))
1744 T = ET->getDecl()->getIntegerType().getTypePtr();
1745
1746 const BuiltinType *BT = cast<BuiltinType>(T);
1747 assert(BT->isInteger());
1748
1749 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
1750 }
1751
1752 // Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00001753 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00001754 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00001755 L.NonNegative && R.NonNegative);
1756 }
1757
1758 // Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00001759 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00001760 return IntRange(std::min(L.Width, R.Width),
1761 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00001762 }
1763};
1764
1765IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
1766 if (value.isSigned() && value.isNegative())
1767 return IntRange(value.getMinSignedBits(), false);
1768
1769 if (value.getBitWidth() > MaxWidth)
1770 value.trunc(MaxWidth);
1771
1772 // isNonNegative() just checks the sign bit without considering
1773 // signedness.
1774 return IntRange(value.getActiveBits(), true);
1775}
1776
John McCall0acc3112010-01-06 22:57:21 +00001777IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCallf2370c92010-01-06 05:24:50 +00001778 unsigned MaxWidth) {
1779 if (result.isInt())
1780 return GetValueRange(C, result.getInt(), MaxWidth);
1781
1782 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00001783 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
1784 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
1785 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
1786 R = IntRange::join(R, El);
1787 }
John McCallf2370c92010-01-06 05:24:50 +00001788 return R;
1789 }
1790
1791 if (result.isComplexInt()) {
1792 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
1793 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
1794 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00001795 }
1796
1797 // This can happen with lossless casts to intptr_t of "based" lvalues.
1798 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00001799 // FIXME: The only reason we need to pass the type in here is to get
1800 // the sign right on this one case. It would be nice if APValue
1801 // preserved this.
John McCallf2370c92010-01-06 05:24:50 +00001802 assert(result.isLValue());
John McCall0acc3112010-01-06 22:57:21 +00001803 return IntRange(MaxWidth, Ty->isUnsignedIntegerType());
John McCall51313c32010-01-04 23:31:57 +00001804}
John McCallf2370c92010-01-06 05:24:50 +00001805
1806/// Pseudo-evaluate the given integer expression, estimating the
1807/// range of values it might take.
1808///
1809/// \param MaxWidth - the width to which the value will be truncated
1810IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
1811 E = E->IgnoreParens();
1812
1813 // Try a full evaluation first.
1814 Expr::EvalResult result;
1815 if (E->Evaluate(result, C))
John McCall0acc3112010-01-06 22:57:21 +00001816 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00001817
1818 // I think we only want to look through implicit casts here; if the
1819 // user has an explicit widening cast, we should treat the value as
1820 // being of the new, wider type.
1821 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
1822 if (CE->getCastKind() == CastExpr::CK_NoOp)
1823 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
1824
1825 IntRange OutputTypeRange = IntRange::forType(C, CE->getType());
1826
John McCall60fad452010-01-06 22:07:33 +00001827 bool isIntegerCast = (CE->getCastKind() == CastExpr::CK_IntegralCast);
1828 if (!isIntegerCast && CE->getCastKind() == CastExpr::CK_Unknown)
1829 isIntegerCast = CE->getSubExpr()->getType()->isIntegerType();
1830
John McCallf2370c92010-01-06 05:24:50 +00001831 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00001832 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00001833 return OutputTypeRange;
1834
1835 IntRange SubRange
1836 = GetExprRange(C, CE->getSubExpr(),
1837 std::min(MaxWidth, OutputTypeRange.Width));
1838
1839 // Bail out if the subexpr's range is as wide as the cast type.
1840 if (SubRange.Width >= OutputTypeRange.Width)
1841 return OutputTypeRange;
1842
1843 // Otherwise, we take the smaller width, and we're non-negative if
1844 // either the output type or the subexpr is.
1845 return IntRange(SubRange.Width,
1846 SubRange.NonNegative || OutputTypeRange.NonNegative);
1847 }
1848
1849 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1850 // If we can fold the condition, just take that operand.
1851 bool CondResult;
1852 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
1853 return GetExprRange(C, CondResult ? CO->getTrueExpr()
1854 : CO->getFalseExpr(),
1855 MaxWidth);
1856
1857 // Otherwise, conservatively merge.
1858 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
1859 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
1860 return IntRange::join(L, R);
1861 }
1862
1863 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
1864 switch (BO->getOpcode()) {
1865
1866 // Boolean-valued operations are single-bit and positive.
1867 case BinaryOperator::LAnd:
1868 case BinaryOperator::LOr:
1869 case BinaryOperator::LT:
1870 case BinaryOperator::GT:
1871 case BinaryOperator::LE:
1872 case BinaryOperator::GE:
1873 case BinaryOperator::EQ:
1874 case BinaryOperator::NE:
1875 return IntRange::forBoolType();
1876
John McCallc0cd21d2010-02-23 19:22:29 +00001877 // The type of these compound assignments is the type of the LHS,
1878 // so the RHS is not necessarily an integer.
1879 case BinaryOperator::MulAssign:
1880 case BinaryOperator::DivAssign:
1881 case BinaryOperator::RemAssign:
1882 case BinaryOperator::AddAssign:
1883 case BinaryOperator::SubAssign:
1884 return IntRange::forType(C, E->getType());
1885
John McCallf2370c92010-01-06 05:24:50 +00001886 // Operations with opaque sources are black-listed.
1887 case BinaryOperator::PtrMemD:
1888 case BinaryOperator::PtrMemI:
1889 return IntRange::forType(C, E->getType());
1890
John McCall60fad452010-01-06 22:07:33 +00001891 // Bitwise-and uses the *infinum* of the two source ranges.
1892 case BinaryOperator::And:
John McCallc0cd21d2010-02-23 19:22:29 +00001893 case BinaryOperator::AndAssign:
John McCall60fad452010-01-06 22:07:33 +00001894 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
1895 GetExprRange(C, BO->getRHS(), MaxWidth));
1896
John McCallf2370c92010-01-06 05:24:50 +00001897 // Left shift gets black-listed based on a judgement call.
1898 case BinaryOperator::Shl:
John McCall3aae6092010-04-07 01:14:35 +00001899 // ...except that we want to treat '1 << (blah)' as logically
1900 // positive. It's an important idiom.
1901 if (IntegerLiteral *I
1902 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
1903 if (I->getValue() == 1) {
1904 IntRange R = IntRange::forType(C, E->getType());
1905 return IntRange(R.Width, /*NonNegative*/ true);
1906 }
1907 }
1908 // fallthrough
1909
John McCallc0cd21d2010-02-23 19:22:29 +00001910 case BinaryOperator::ShlAssign:
John McCallf2370c92010-01-06 05:24:50 +00001911 return IntRange::forType(C, E->getType());
1912
John McCall60fad452010-01-06 22:07:33 +00001913 // Right shift by a constant can narrow its left argument.
John McCallc0cd21d2010-02-23 19:22:29 +00001914 case BinaryOperator::Shr:
1915 case BinaryOperator::ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00001916 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
1917
1918 // If the shift amount is a positive constant, drop the width by
1919 // that much.
1920 llvm::APSInt shift;
1921 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
1922 shift.isNonNegative()) {
1923 unsigned zext = shift.getZExtValue();
1924 if (zext >= L.Width)
1925 L.Width = (L.NonNegative ? 0 : 1);
1926 else
1927 L.Width -= zext;
1928 }
1929
1930 return L;
1931 }
1932
1933 // Comma acts as its right operand.
John McCallf2370c92010-01-06 05:24:50 +00001934 case BinaryOperator::Comma:
1935 return GetExprRange(C, BO->getRHS(), MaxWidth);
1936
John McCall60fad452010-01-06 22:07:33 +00001937 // Black-list pointer subtractions.
John McCallf2370c92010-01-06 05:24:50 +00001938 case BinaryOperator::Sub:
1939 if (BO->getLHS()->getType()->isPointerType())
1940 return IntRange::forType(C, E->getType());
1941 // fallthrough
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001942
John McCallf2370c92010-01-06 05:24:50 +00001943 default:
1944 break;
1945 }
1946
1947 // Treat every other operator as if it were closed on the
1948 // narrowest type that encompasses both operands.
1949 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
1950 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
1951 return IntRange::join(L, R);
1952 }
1953
1954 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1955 switch (UO->getOpcode()) {
1956 // Boolean-valued operations are white-listed.
1957 case UnaryOperator::LNot:
1958 return IntRange::forBoolType();
1959
1960 // Operations with opaque sources are black-listed.
1961 case UnaryOperator::Deref:
1962 case UnaryOperator::AddrOf: // should be impossible
1963 case UnaryOperator::OffsetOf:
1964 return IntRange::forType(C, E->getType());
1965
1966 default:
1967 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
1968 }
1969 }
1970
1971 FieldDecl *BitField = E->getBitField();
1972 if (BitField) {
1973 llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C);
1974 unsigned BitWidth = BitWidthAP.getZExtValue();
1975
1976 return IntRange(BitWidth, BitField->getType()->isUnsignedIntegerType());
1977 }
1978
1979 return IntRange::forType(C, E->getType());
1980}
John McCall51313c32010-01-04 23:31:57 +00001981
1982/// Checks whether the given value, which currently has the given
1983/// source semantics, has the same value when coerced through the
1984/// target semantics.
John McCallf2370c92010-01-06 05:24:50 +00001985bool IsSameFloatAfterCast(const llvm::APFloat &value,
1986 const llvm::fltSemantics &Src,
1987 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00001988 llvm::APFloat truncated = value;
1989
1990 bool ignored;
1991 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
1992 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
1993
1994 return truncated.bitwiseIsEqual(value);
1995}
1996
1997/// Checks whether the given value, which currently has the given
1998/// source semantics, has the same value when coerced through the
1999/// target semantics.
2000///
2001/// The value might be a vector of floats (or a complex number).
John McCallf2370c92010-01-06 05:24:50 +00002002bool IsSameFloatAfterCast(const APValue &value,
2003 const llvm::fltSemantics &Src,
2004 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002005 if (value.isFloat())
2006 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
2007
2008 if (value.isVector()) {
2009 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
2010 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
2011 return false;
2012 return true;
2013 }
2014
2015 assert(value.isComplexFloat());
2016 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
2017 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
2018}
2019
John McCallf2370c92010-01-06 05:24:50 +00002020} // end anonymous namespace
John McCall51313c32010-01-04 23:31:57 +00002021
John McCallba26e582010-01-04 23:21:16 +00002022/// \brief Implements -Wsign-compare.
2023///
2024/// \param lex the left-hand expression
2025/// \param rex the right-hand expression
2026/// \param OpLoc the location of the joining operator
John McCalld1b47bf2010-03-11 19:43:18 +00002027/// \param BinOpc binary opcode or 0
John McCallba26e582010-01-04 23:21:16 +00002028void Sema::CheckSignCompare(Expr *lex, Expr *rex, SourceLocation OpLoc,
John McCalld1b47bf2010-03-11 19:43:18 +00002029 const BinaryOperator::Opcode* BinOpc) {
John McCallba26e582010-01-04 23:21:16 +00002030 // Don't warn if we're in an unevaluated context.
2031 if (ExprEvalContexts.back().Context == Unevaluated)
2032 return;
2033
John McCallf2370c92010-01-06 05:24:50 +00002034 // If either expression is value-dependent, don't warn. We'll get another
2035 // chance at instantiation time.
2036 if (lex->isValueDependent() || rex->isValueDependent())
2037 return;
2038
John McCallba26e582010-01-04 23:21:16 +00002039 QualType lt = lex->getType(), rt = rex->getType();
2040
2041 // Only warn if both operands are integral.
2042 if (!lt->isIntegerType() || !rt->isIntegerType())
2043 return;
2044
John McCallf2370c92010-01-06 05:24:50 +00002045 // In C, the width of a bitfield determines its type, and the
2046 // declared type only contributes the signedness. This duplicates
2047 // the work that will later be done by UsualUnaryConversions.
2048 // Eventually, this check will be reorganized in a way that avoids
2049 // this duplication.
2050 if (!getLangOptions().CPlusPlus) {
2051 QualType tmp;
2052 tmp = Context.isPromotableBitField(lex);
2053 if (!tmp.isNull()) lt = tmp;
2054 tmp = Context.isPromotableBitField(rex);
2055 if (!tmp.isNull()) rt = tmp;
2056 }
John McCallba26e582010-01-04 23:21:16 +00002057
John McCalla2936be2010-03-19 18:53:26 +00002058 if (const EnumType *E = lt->getAs<EnumType>())
2059 lt = E->getDecl()->getPromotionType();
2060 if (const EnumType *E = rt->getAs<EnumType>())
2061 rt = E->getDecl()->getPromotionType();
2062
John McCallba26e582010-01-04 23:21:16 +00002063 // The rule is that the signed operand becomes unsigned, so isolate the
2064 // signed operand.
John McCallf2370c92010-01-06 05:24:50 +00002065 Expr *signedOperand = lex, *unsignedOperand = rex;
2066 QualType signedType = lt, unsignedType = rt;
John McCallba26e582010-01-04 23:21:16 +00002067 if (lt->isSignedIntegerType()) {
2068 if (rt->isSignedIntegerType()) return;
John McCallba26e582010-01-04 23:21:16 +00002069 } else {
2070 if (!rt->isSignedIntegerType()) return;
John McCallf2370c92010-01-06 05:24:50 +00002071 std::swap(signedOperand, unsignedOperand);
2072 std::swap(signedType, unsignedType);
John McCallba26e582010-01-04 23:21:16 +00002073 }
2074
John McCallf2370c92010-01-06 05:24:50 +00002075 unsigned unsignedWidth = Context.getIntWidth(unsignedType);
2076 unsigned signedWidth = Context.getIntWidth(signedType);
2077
John McCallba26e582010-01-04 23:21:16 +00002078 // If the unsigned type is strictly smaller than the signed type,
2079 // then (1) the result type will be signed and (2) the unsigned
2080 // value will fit fully within the signed type, and thus the result
2081 // of the comparison will be exact.
John McCallf2370c92010-01-06 05:24:50 +00002082 if (signedWidth > unsignedWidth)
John McCallba26e582010-01-04 23:21:16 +00002083 return;
2084
John McCallf2370c92010-01-06 05:24:50 +00002085 // Otherwise, calculate the effective ranges.
2086 IntRange signedRange = GetExprRange(Context, signedOperand, signedWidth);
2087 IntRange unsignedRange = GetExprRange(Context, unsignedOperand, unsignedWidth);
2088
2089 // We should never be unable to prove that the unsigned operand is
2090 // non-negative.
2091 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
2092
2093 // If the signed operand is non-negative, then the signed->unsigned
2094 // conversion won't change it.
John McCalld1b47bf2010-03-11 19:43:18 +00002095 if (signedRange.NonNegative) {
2096 // Emit warnings for comparisons of unsigned to integer constant 0.
2097 // always false: x < 0 (or 0 > x)
2098 // always true: x >= 0 (or 0 <= x)
2099 llvm::APSInt X;
2100 if (BinOpc && signedOperand->isIntegerConstantExpr(X, Context) && X == 0) {
2101 if (signedOperand != lex) {
2102 if (*BinOpc == BinaryOperator::LT) {
2103 Diag(OpLoc, diag::warn_lunsigned_always_true_comparison)
2104 << "< 0" << "false"
2105 << lex->getSourceRange() << rex->getSourceRange();
2106 }
2107 else if (*BinOpc == BinaryOperator::GE) {
2108 Diag(OpLoc, diag::warn_lunsigned_always_true_comparison)
2109 << ">= 0" << "true"
2110 << lex->getSourceRange() << rex->getSourceRange();
2111 }
2112 }
2113 else {
2114 if (*BinOpc == BinaryOperator::GT) {
2115 Diag(OpLoc, diag::warn_runsigned_always_true_comparison)
2116 << "0 >" << "false"
2117 << lex->getSourceRange() << rex->getSourceRange();
2118 }
2119 else if (*BinOpc == BinaryOperator::LE) {
2120 Diag(OpLoc, diag::warn_runsigned_always_true_comparison)
2121 << "0 <=" << "true"
2122 << lex->getSourceRange() << rex->getSourceRange();
2123 }
2124 }
2125 }
John McCallba26e582010-01-04 23:21:16 +00002126 return;
John McCalld1b47bf2010-03-11 19:43:18 +00002127 }
John McCallba26e582010-01-04 23:21:16 +00002128
2129 // For (in)equality comparisons, if the unsigned operand is a
2130 // constant which cannot collide with a overflowed signed operand,
2131 // then reinterpreting the signed operand as unsigned will not
2132 // change the result of the comparison.
John McCalld1b47bf2010-03-11 19:43:18 +00002133 if (BinOpc &&
2134 (*BinOpc == BinaryOperator::EQ || *BinOpc == BinaryOperator::NE) &&
2135 unsignedRange.Width < unsignedWidth)
John McCallba26e582010-01-04 23:21:16 +00002136 return;
2137
John McCalld1b47bf2010-03-11 19:43:18 +00002138 Diag(OpLoc, BinOpc ? diag::warn_mixed_sign_comparison
2139 : diag::warn_mixed_sign_conditional)
John McCallf2370c92010-01-06 05:24:50 +00002140 << lt << rt << lex->getSourceRange() << rex->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00002141}
2142
John McCall51313c32010-01-04 23:31:57 +00002143/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
2144static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, unsigned diag) {
2145 S.Diag(E->getExprLoc(), diag) << E->getType() << T << E->getSourceRange();
2146}
2147
2148/// Implements -Wconversion.
2149void Sema::CheckImplicitConversion(Expr *E, QualType T) {
2150 // Don't diagnose in unevaluated contexts.
2151 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
2152 return;
2153
2154 // Don't diagnose for value-dependent expressions.
2155 if (E->isValueDependent())
2156 return;
2157
2158 const Type *Source = Context.getCanonicalType(E->getType()).getTypePtr();
2159 const Type *Target = Context.getCanonicalType(T).getTypePtr();
2160
2161 // Never diagnose implicit casts to bool.
2162 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
2163 return;
2164
2165 // Strip vector types.
2166 if (isa<VectorType>(Source)) {
2167 if (!isa<VectorType>(Target))
2168 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_vector_scalar);
2169
2170 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
2171 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
2172 }
2173
2174 // Strip complex types.
2175 if (isa<ComplexType>(Source)) {
2176 if (!isa<ComplexType>(Target))
2177 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_complex_scalar);
2178
2179 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
2180 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
2181 }
2182
2183 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
2184 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
2185
2186 // If the source is floating point...
2187 if (SourceBT && SourceBT->isFloatingPoint()) {
2188 // ...and the target is floating point...
2189 if (TargetBT && TargetBT->isFloatingPoint()) {
2190 // ...then warn if we're dropping FP rank.
2191
2192 // Builtin FP kinds are ordered by increasing FP rank.
2193 if (SourceBT->getKind() > TargetBT->getKind()) {
2194 // Don't warn about float constants that are precisely
2195 // representable in the target type.
2196 Expr::EvalResult result;
2197 if (E->Evaluate(result, Context)) {
2198 // Value might be a float, a float vector, or a float complex.
2199 if (IsSameFloatAfterCast(result.Val,
2200 Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
2201 Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
2202 return;
2203 }
2204
2205 DiagnoseImpCast(*this, E, T, diag::warn_impcast_float_precision);
2206 }
2207 return;
2208 }
2209
2210 // If the target is integral, always warn.
2211 if ((TargetBT && TargetBT->isInteger()))
2212 // TODO: don't warn for integer values?
2213 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_float_integer);
2214
2215 return;
2216 }
2217
John McCallf2370c92010-01-06 05:24:50 +00002218 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00002219 return;
2220
John McCallf2370c92010-01-06 05:24:50 +00002221 IntRange SourceRange = GetExprRange(Context, E, Context.getIntWidth(E->getType()));
2222 IntRange TargetRange = IntRange::forCanonicalType(Context, Target);
John McCall51313c32010-01-04 23:31:57 +00002223
John McCallf2370c92010-01-06 05:24:50 +00002224 // FIXME: also signed<->unsigned?
2225
2226 if (SourceRange.Width > TargetRange.Width) {
John McCall51313c32010-01-04 23:31:57 +00002227 // People want to build with -Wshorten-64-to-32 and not -Wconversion
2228 // and by god we'll let them.
John McCallf2370c92010-01-06 05:24:50 +00002229 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCall51313c32010-01-04 23:31:57 +00002230 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_integer_64_32);
2231 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_integer_precision);
2232 }
2233
2234 return;
2235}
2236
Mike Stumpf8c49212010-01-21 03:59:47 +00002237/// CheckParmsForFunctionDef - Check that the parameters of the given
2238/// function are appropriate for the definition of a function. This
2239/// takes care of any checks that cannot be performed on the
2240/// declaration itself, e.g., that the types of each of the function
2241/// parameters are complete.
2242bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
2243 bool HasInvalidParm = false;
2244 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2245 ParmVarDecl *Param = FD->getParamDecl(p);
2246
2247 // C99 6.7.5.3p4: the parameters in a parameter type list in a
2248 // function declarator that is part of a function definition of
2249 // that function shall not have incomplete type.
2250 //
2251 // This is also C++ [dcl.fct]p6.
2252 if (!Param->isInvalidDecl() &&
2253 RequireCompleteType(Param->getLocation(), Param->getType(),
2254 diag::err_typecheck_decl_incomplete_type)) {
2255 Param->setInvalidDecl();
2256 HasInvalidParm = true;
2257 }
2258
2259 // C99 6.9.1p5: If the declarator includes a parameter type list, the
2260 // declaration of each parameter shall include an identifier.
2261 if (Param->getIdentifier() == 0 &&
2262 !Param->isImplicit() &&
2263 !getLangOptions().CPlusPlus)
2264 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00002265
2266 // C99 6.7.5.3p12:
2267 // If the function declarator is not part of a definition of that
2268 // function, parameters may have incomplete type and may use the [*]
2269 // notation in their sequences of declarator specifiers to specify
2270 // variable length array types.
2271 QualType PType = Param->getOriginalType();
2272 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
2273 if (AT->getSizeModifier() == ArrayType::Star) {
2274 // FIXME: This diagnosic should point the the '[*]' if source-location
2275 // information is added for it.
2276 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
2277 }
2278 }
Mike Stumpf8c49212010-01-21 03:59:47 +00002279 }
2280
2281 return HasInvalidParm;
2282}