blob: 30a6ab4655388ae654dd218befa86020b2a15e03 [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 Kremenek1309f9a2010-01-25 04:41:41 +000016#include "clang/Analysis/AnalysisContext.h"
Ted Kremenek3d2eed82010-02-23 02:39:16 +000017#include "clang/Analysis/CFG.h"
18#include "clang/Analysis/Analyses/ReachableCode.h"
Ted Kremeneke0e53132010-01-28 23:39:18 +000019#include "clang/Analysis/Analyses/PrintfFormatString.h"
Chris Lattner59907c42007-08-10 20:18:51 +000020#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000021#include "clang/AST/CharUnits.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000022#include "clang/AST/DeclObjC.h"
Ted Kremenek23245122007-08-20 16:18:38 +000023#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000024#include "clang/AST/ExprObjC.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000025#include "clang/AST/DeclObjC.h"
26#include "clang/AST/StmtCXX.h"
27#include "clang/AST/StmtObjC.h"
Chris Lattner719e6152009-02-18 19:21:10 +000028#include "clang/Lex/LiteralSupport.h"
Chris Lattner59907c42007-08-10 20:18:51 +000029#include "clang/Lex/Preprocessor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000030#include "llvm/ADT/BitVector.h"
31#include "llvm/ADT/STLExtras.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000032#include <limits>
Mike Stumpf8c49212010-01-21 03:59:47 +000033#include <queue>
Chris Lattner59907c42007-08-10 20:18:51 +000034using namespace clang;
35
Chris Lattner60800082009-02-18 17:49:48 +000036/// getLocationOfStringLiteralByte - Return a source location that points to the
37/// specified byte of the specified string literal.
38///
39/// Strings are amazingly complex. They can be formed from multiple tokens and
40/// can have escape sequences in them in addition to the usual trigraph and
41/// escaped newline business. This routine handles this complexity.
42///
43SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
44 unsigned ByteNo) const {
45 assert(!SL->isWide() && "This doesn't work for wide strings yet");
Mike Stump1eb44332009-09-09 15:08:12 +000046
Chris Lattner60800082009-02-18 17:49:48 +000047 // Loop over all of the tokens in this string until we find the one that
48 // contains the byte we're looking for.
49 unsigned TokNo = 0;
50 while (1) {
51 assert(TokNo < SL->getNumConcatenated() && "Invalid byte number!");
52 SourceLocation StrTokLoc = SL->getStrTokenLoc(TokNo);
Mike Stump1eb44332009-09-09 15:08:12 +000053
Chris Lattner60800082009-02-18 17:49:48 +000054 // Get the spelling of the string so that we can get the data that makes up
55 // the string literal, not the identifier for the macro it is potentially
56 // expanded through.
57 SourceLocation StrTokSpellingLoc = SourceMgr.getSpellingLoc(StrTokLoc);
58
59 // Re-lex the token to get its length and original spelling.
60 std::pair<FileID, unsigned> LocInfo =
61 SourceMgr.getDecomposedLoc(StrTokSpellingLoc);
62 std::pair<const char *,const char *> Buffer =
63 SourceMgr.getBufferData(LocInfo.first);
64 const char *StrData = Buffer.first+LocInfo.second;
Mike Stump1eb44332009-09-09 15:08:12 +000065
Chris Lattner60800082009-02-18 17:49:48 +000066 // Create a langops struct and enable trigraphs. This is sufficient for
67 // relexing tokens.
68 LangOptions LangOpts;
69 LangOpts.Trigraphs = true;
Mike Stump1eb44332009-09-09 15:08:12 +000070
Chris Lattner60800082009-02-18 17:49:48 +000071 // Create a lexer starting at the beginning of this token.
72 Lexer TheLexer(StrTokSpellingLoc, LangOpts, Buffer.first, StrData,
73 Buffer.second);
74 Token TheTok;
75 TheLexer.LexFromRawLexer(TheTok);
Mike Stump1eb44332009-09-09 15:08:12 +000076
Chris Lattner443e53c2009-02-18 19:26:42 +000077 // Use the StringLiteralParser to compute the length of the string in bytes.
78 StringLiteralParser SLP(&TheTok, 1, PP);
79 unsigned TokNumBytes = SLP.GetStringLength();
Mike Stump1eb44332009-09-09 15:08:12 +000080
Chris Lattner2197c962009-02-18 18:52:52 +000081 // If the byte is in this token, return the location of the byte.
Chris Lattner60800082009-02-18 17:49:48 +000082 if (ByteNo < TokNumBytes ||
83 (ByteNo == TokNumBytes && TokNo == SL->getNumConcatenated())) {
Mike Stump1eb44332009-09-09 15:08:12 +000084 unsigned Offset =
Chris Lattner719e6152009-02-18 19:21:10 +000085 StringLiteralParser::getOffsetOfStringByte(TheTok, ByteNo, PP);
Mike Stump1eb44332009-09-09 15:08:12 +000086
Chris Lattner719e6152009-02-18 19:21:10 +000087 // Now that we know the offset of the token in the spelling, use the
88 // preprocessor to get the offset in the original source.
89 return PP.AdvanceToTokenCharacter(StrTokLoc, Offset);
Chris Lattner60800082009-02-18 17:49:48 +000090 }
Mike Stump1eb44332009-09-09 15:08:12 +000091
Chris Lattner60800082009-02-18 17:49:48 +000092 // Move to the next string token.
93 ++TokNo;
94 ByteNo -= TokNumBytes;
95 }
96}
97
Ryan Flynn4403a5e2009-08-06 03:00:50 +000098/// CheckablePrintfAttr - does a function call have a "printf" attribute
99/// and arguments that merit checking?
100bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) {
101 if (Format->getType() == "printf") return true;
102 if (Format->getType() == "printf0") {
103 // printf0 allows null "format" string; if so don't check format/args
104 unsigned format_idx = Format->getFormatIdx() - 1;
Sebastian Redl4a2614e2009-11-17 18:02:24 +0000105 // Does the index refer to the implicit object argument?
106 if (isa<CXXMemberCallExpr>(TheCall)) {
107 if (format_idx == 0)
108 return false;
109 --format_idx;
110 }
Ryan Flynn4403a5e2009-08-06 03:00:50 +0000111 if (format_idx < TheCall->getNumArgs()) {
112 Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts();
Ted Kremenekefaff192010-02-27 01:41:03 +0000113 if (!Format->isNullPointerConstant(Context,
114 Expr::NPC_ValueDependentIsNull))
Ryan Flynn4403a5e2009-08-06 03:00:50 +0000115 return true;
116 }
117 }
118 return false;
119}
Chris Lattner60800082009-02-18 17:49:48 +0000120
Sebastian Redl0eb23302009-01-19 00:08:26 +0000121Action::OwningExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +0000122Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Sebastian Redl0eb23302009-01-19 00:08:26 +0000123 OwningExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +0000124
Anders Carlssond406bf02009-08-16 01:56:34 +0000125 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000126 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000127 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000128 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000129 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000130 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000131 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000132 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000133 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000134 if (SemaBuiltinVAStart(TheCall))
135 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000136 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000137 case Builtin::BI__builtin_isgreater:
138 case Builtin::BI__builtin_isgreaterequal:
139 case Builtin::BI__builtin_isless:
140 case Builtin::BI__builtin_islessequal:
141 case Builtin::BI__builtin_islessgreater:
142 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000143 if (SemaBuiltinUnorderedCompare(TheCall))
144 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000145 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000146 case Builtin::BI__builtin_fpclassify:
147 if (SemaBuiltinFPClassification(TheCall, 6))
148 return ExprError();
149 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000150 case Builtin::BI__builtin_isfinite:
151 case Builtin::BI__builtin_isinf:
152 case Builtin::BI__builtin_isinf_sign:
153 case Builtin::BI__builtin_isnan:
154 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000155 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000156 return ExprError();
157 break;
Eli Friedman6cfda232008-05-20 08:23:37 +0000158 case Builtin::BI__builtin_return_address:
159 case Builtin::BI__builtin_frame_address:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000160 if (SemaBuiltinStackAddress(TheCall))
161 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000162 break;
Chris Lattner21fb98e2009-09-23 06:06:36 +0000163 case Builtin::BI__builtin_eh_return_data_regno:
164 if (SemaBuiltinEHReturnDataRegNo(TheCall))
165 return ExprError();
166 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000167 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000168 return SemaBuiltinShuffleVector(TheCall);
169 // TheCall will be freed by the smart pointer here, but that's fine, since
170 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000171 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000172 if (SemaBuiltinPrefetch(TheCall))
173 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000174 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000175 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000176 if (SemaBuiltinObjectSize(TheCall))
177 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000178 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000179 case Builtin::BI__builtin_longjmp:
180 if (SemaBuiltinLongjmp(TheCall))
181 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000182 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000183 case Builtin::BI__sync_fetch_and_add:
184 case Builtin::BI__sync_fetch_and_sub:
185 case Builtin::BI__sync_fetch_and_or:
186 case Builtin::BI__sync_fetch_and_and:
187 case Builtin::BI__sync_fetch_and_xor:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000188 case Builtin::BI__sync_fetch_and_nand:
Chris Lattner5caa3702009-05-08 06:58:22 +0000189 case Builtin::BI__sync_add_and_fetch:
190 case Builtin::BI__sync_sub_and_fetch:
191 case Builtin::BI__sync_and_and_fetch:
192 case Builtin::BI__sync_or_and_fetch:
193 case Builtin::BI__sync_xor_and_fetch:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000194 case Builtin::BI__sync_nand_and_fetch:
Chris Lattner5caa3702009-05-08 06:58:22 +0000195 case Builtin::BI__sync_val_compare_and_swap:
196 case Builtin::BI__sync_bool_compare_and_swap:
197 case Builtin::BI__sync_lock_test_and_set:
198 case Builtin::BI__sync_lock_release:
199 if (SemaBuiltinAtomicOverloaded(TheCall))
200 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000201 break;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000202 }
Mike Stump1eb44332009-09-09 15:08:12 +0000203
Anders Carlssond406bf02009-08-16 01:56:34 +0000204 return move(TheCallResult);
205}
Daniel Dunbarde454282008-10-02 18:44:07 +0000206
Anders Carlssond406bf02009-08-16 01:56:34 +0000207/// CheckFunctionCall - Check a direct function call for various correctness
208/// and safety properties not strictly enforced by the C type system.
209bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
210 // Get the IdentifierInfo* for the called function.
211 IdentifierInfo *FnInfo = FDecl->getIdentifier();
212
213 // None of the checks below are needed for functions that don't have
214 // simple names (e.g., C++ conversion functions).
215 if (!FnInfo)
216 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000217
Daniel Dunbarde454282008-10-02 18:44:07 +0000218 // FIXME: This mechanism should be abstracted to be less fragile and
219 // more efficient. For example, just map function ids to custom
220 // handlers.
221
Chris Lattner59907c42007-08-10 20:18:51 +0000222 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000223 if (const FormatAttr *Format = FDecl->getAttr<FormatAttr>()) {
Ryan Flynn4403a5e2009-08-06 03:00:50 +0000224 if (CheckablePrintfAttr(Format, TheCall)) {
Ted Kremenek3d692df2009-02-27 17:58:43 +0000225 bool HasVAListArg = Format->getFirstArg() == 0;
226 if (!HasVAListArg) {
Mike Stump1eb44332009-09-09 15:08:12 +0000227 if (const FunctionProtoType *Proto
John McCall183700f2009-09-21 23:43:11 +0000228 = FDecl->getType()->getAs<FunctionProtoType>())
Sebastian Redl4a2614e2009-11-17 18:02:24 +0000229 HasVAListArg = !Proto->isVariadic();
Ted Kremenek3d692df2009-02-27 17:58:43 +0000230 }
Douglas Gregor3c385e52009-02-14 18:57:46 +0000231 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
Ted Kremenek3d692df2009-02-27 17:58:43 +0000232 HasVAListArg ? 0 : Format->getFirstArg() - 1);
Douglas Gregor3c385e52009-02-14 18:57:46 +0000233 }
Chris Lattner59907c42007-08-10 20:18:51 +0000234 }
Mike Stump1eb44332009-09-09 15:08:12 +0000235
236 for (const NonNullAttr *NonNull = FDecl->getAttr<NonNullAttr>(); NonNull;
Anders Carlssond406bf02009-08-16 01:56:34 +0000237 NonNull = NonNull->getNext<NonNullAttr>())
238 CheckNonNullArguments(NonNull, TheCall);
Sebastian Redl0eb23302009-01-19 00:08:26 +0000239
Anders Carlssond406bf02009-08-16 01:56:34 +0000240 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000241}
242
Anders Carlssond406bf02009-08-16 01:56:34 +0000243bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000244 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000245 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000246 if (!Format)
Anders Carlssond406bf02009-08-16 01:56:34 +0000247 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000248
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000249 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
250 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000251 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000252
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000253 QualType Ty = V->getType();
254 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000255 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000256
Anders Carlssond406bf02009-08-16 01:56:34 +0000257 if (!CheckablePrintfAttr(Format, TheCall))
258 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000259
Anders Carlssond406bf02009-08-16 01:56:34 +0000260 bool HasVAListArg = Format->getFirstArg() == 0;
261 if (!HasVAListArg) {
Mike Stump1eb44332009-09-09 15:08:12 +0000262 const FunctionType *FT =
John McCall183700f2009-09-21 23:43:11 +0000263 Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
Anders Carlssond406bf02009-08-16 01:56:34 +0000264 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT))
265 HasVAListArg = !Proto->isVariadic();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000266 }
Anders Carlssond406bf02009-08-16 01:56:34 +0000267 CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
268 HasVAListArg ? 0 : Format->getFirstArg() - 1);
269
270 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000271}
272
Chris Lattner5caa3702009-05-08 06:58:22 +0000273/// SemaBuiltinAtomicOverloaded - We have a call to a function like
274/// __sync_fetch_and_add, which is an overloaded function based on the pointer
275/// type of its first argument. The main ActOnCallExpr routines have already
276/// promoted the types of arguments because all of these calls are prototyped as
277/// void(...).
278///
279/// This function goes through and does final semantic checking for these
280/// builtins,
281bool Sema::SemaBuiltinAtomicOverloaded(CallExpr *TheCall) {
282 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
283 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
284
285 // Ensure that we have at least one argument to do type inference from.
286 if (TheCall->getNumArgs() < 1)
287 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
288 << 0 << TheCall->getCallee()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000289
Chris Lattner5caa3702009-05-08 06:58:22 +0000290 // Inspect the first argument of the atomic builtin. This should always be
291 // a pointer type, whose element is an integral scalar or pointer type.
292 // Because it is a pointer type, we don't have to worry about any implicit
293 // casts here.
294 Expr *FirstArg = TheCall->getArg(0);
295 if (!FirstArg->getType()->isPointerType())
296 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
297 << FirstArg->getType() << FirstArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000298
Ted Kremenek6217b802009-07-29 21:53:49 +0000299 QualType ValType = FirstArg->getType()->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000300 if (!ValType->isIntegerType() && !ValType->isPointerType() &&
Chris Lattner5caa3702009-05-08 06:58:22 +0000301 !ValType->isBlockPointerType())
302 return Diag(DRE->getLocStart(),
303 diag::err_atomic_builtin_must_be_pointer_intptr)
304 << FirstArg->getType() << FirstArg->getSourceRange();
305
306 // We need to figure out which concrete builtin this maps onto. For example,
307 // __sync_fetch_and_add with a 2 byte object turns into
308 // __sync_fetch_and_add_2.
309#define BUILTIN_ROW(x) \
310 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
311 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000312
Chris Lattner5caa3702009-05-08 06:58:22 +0000313 static const unsigned BuiltinIndices[][5] = {
314 BUILTIN_ROW(__sync_fetch_and_add),
315 BUILTIN_ROW(__sync_fetch_and_sub),
316 BUILTIN_ROW(__sync_fetch_and_or),
317 BUILTIN_ROW(__sync_fetch_and_and),
318 BUILTIN_ROW(__sync_fetch_and_xor),
Chris Lattnereebd9d22009-05-13 04:37:52 +0000319 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump1eb44332009-09-09 15:08:12 +0000320
Chris Lattner5caa3702009-05-08 06:58:22 +0000321 BUILTIN_ROW(__sync_add_and_fetch),
322 BUILTIN_ROW(__sync_sub_and_fetch),
323 BUILTIN_ROW(__sync_and_and_fetch),
324 BUILTIN_ROW(__sync_or_and_fetch),
325 BUILTIN_ROW(__sync_xor_and_fetch),
Chris Lattnereebd9d22009-05-13 04:37:52 +0000326 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000327
Chris Lattner5caa3702009-05-08 06:58:22 +0000328 BUILTIN_ROW(__sync_val_compare_and_swap),
329 BUILTIN_ROW(__sync_bool_compare_and_swap),
330 BUILTIN_ROW(__sync_lock_test_and_set),
331 BUILTIN_ROW(__sync_lock_release)
332 };
Mike Stump1eb44332009-09-09 15:08:12 +0000333#undef BUILTIN_ROW
334
Chris Lattner5caa3702009-05-08 06:58:22 +0000335 // Determine the index of the size.
336 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000337 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000338 case 1: SizeIndex = 0; break;
339 case 2: SizeIndex = 1; break;
340 case 4: SizeIndex = 2; break;
341 case 8: SizeIndex = 3; break;
342 case 16: SizeIndex = 4; break;
343 default:
344 return Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
345 << FirstArg->getType() << FirstArg->getSourceRange();
346 }
Mike Stump1eb44332009-09-09 15:08:12 +0000347
Chris Lattner5caa3702009-05-08 06:58:22 +0000348 // Each of these builtins has one pointer argument, followed by some number of
349 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
350 // that we ignore. Find out which row of BuiltinIndices to read from as well
351 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000352 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000353 unsigned BuiltinIndex, NumFixed = 1;
354 switch (BuiltinID) {
355 default: assert(0 && "Unknown overloaded atomic builtin!");
356 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
357 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
358 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
359 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
360 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Chris Lattnereebd9d22009-05-13 04:37:52 +0000361 case Builtin::BI__sync_fetch_and_nand:BuiltinIndex = 5; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000362
Chris Lattnereebd9d22009-05-13 04:37:52 +0000363 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 6; break;
364 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 7; break;
365 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 8; break;
366 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 9; break;
367 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex =10; break;
368 case Builtin::BI__sync_nand_and_fetch:BuiltinIndex =11; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000369
Chris Lattner5caa3702009-05-08 06:58:22 +0000370 case Builtin::BI__sync_val_compare_and_swap:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000371 BuiltinIndex = 12;
Chris Lattner5caa3702009-05-08 06:58:22 +0000372 NumFixed = 2;
373 break;
374 case Builtin::BI__sync_bool_compare_and_swap:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000375 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000376 NumFixed = 2;
377 break;
Chris Lattnereebd9d22009-05-13 04:37:52 +0000378 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 14; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000379 case Builtin::BI__sync_lock_release:
Chris Lattnereebd9d22009-05-13 04:37:52 +0000380 BuiltinIndex = 15;
Chris Lattner5caa3702009-05-08 06:58:22 +0000381 NumFixed = 0;
382 break;
383 }
Mike Stump1eb44332009-09-09 15:08:12 +0000384
Chris Lattner5caa3702009-05-08 06:58:22 +0000385 // Now that we know how many fixed arguments we expect, first check that we
386 // have at least that many.
387 if (TheCall->getNumArgs() < 1+NumFixed)
388 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
389 << 0 << TheCall->getCallee()->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000390
391
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000392 // Get the decl for the concrete builtin from this, we can tell what the
393 // concrete integer type we should convert to is.
394 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
395 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
396 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +0000397 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000398 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
399 TUScope, false, DRE->getLocStart()));
400 const FunctionProtoType *BuiltinFT =
John McCall183700f2009-09-21 23:43:11 +0000401 NewBuiltinDecl->getType()->getAs<FunctionProtoType>();
Ted Kremenek6217b802009-07-29 21:53:49 +0000402 ValType = BuiltinFT->getArgType(0)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +0000403
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000404 // If the first type needs to be converted (e.g. void** -> int*), do it now.
405 if (BuiltinFT->getArgType(0) != FirstArg->getType()) {
Eli Friedman73c39ab2009-10-20 08:27:19 +0000406 ImpCastExprToType(FirstArg, BuiltinFT->getArgType(0), CastExpr::CK_BitCast);
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000407 TheCall->setArg(0, FirstArg);
408 }
Mike Stump1eb44332009-09-09 15:08:12 +0000409
Chris Lattner5caa3702009-05-08 06:58:22 +0000410 // Next, walk the valid ones promoting to the right type.
411 for (unsigned i = 0; i != NumFixed; ++i) {
412 Expr *Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +0000413
Chris Lattner5caa3702009-05-08 06:58:22 +0000414 // If the argument is an implicit cast, then there was a promotion due to
415 // "...", just remove it now.
416 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
417 Arg = ICE->getSubExpr();
418 ICE->setSubExpr(0);
419 ICE->Destroy(Context);
420 TheCall->setArg(i+1, Arg);
421 }
Mike Stump1eb44332009-09-09 15:08:12 +0000422
Chris Lattner5caa3702009-05-08 06:58:22 +0000423 // GCC does an implicit conversion to the pointer or integer ValType. This
424 // can fail in some cases (1i -> int**), check for this error case now.
Anders Carlssoncdb61972009-08-07 22:21:05 +0000425 CastExpr::CastKind Kind = CastExpr::CK_Unknown;
Fariborz Jahaniane9f42082009-08-26 18:55:36 +0000426 CXXMethodDecl *ConversionDecl = 0;
427 if (CheckCastTypes(Arg->getSourceRange(), ValType, Arg, Kind,
428 ConversionDecl))
Chris Lattner5caa3702009-05-08 06:58:22 +0000429 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000430
Chris Lattner5caa3702009-05-08 06:58:22 +0000431 // Okay, we have something that *can* be converted to the right type. Check
432 // to see if there is a potentially weird extension going on here. This can
433 // happen when you do an atomic operation on something like an char* and
434 // pass in 42. The 42 gets converted to char. This is even more strange
435 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +0000436 // FIXME: Do this check.
Anders Carlssoncdb61972009-08-07 22:21:05 +0000437 ImpCastExprToType(Arg, ValType, Kind, /*isLvalue=*/false);
Chris Lattner5caa3702009-05-08 06:58:22 +0000438 TheCall->setArg(i+1, Arg);
439 }
Mike Stump1eb44332009-09-09 15:08:12 +0000440
Chris Lattner5caa3702009-05-08 06:58:22 +0000441 // Switch the DeclRefExpr to refer to the new decl.
442 DRE->setDecl(NewBuiltinDecl);
443 DRE->setType(NewBuiltinDecl->getType());
Mike Stump1eb44332009-09-09 15:08:12 +0000444
Chris Lattner5caa3702009-05-08 06:58:22 +0000445 // Set the callee in the CallExpr.
446 // FIXME: This leaks the original parens and implicit casts.
447 Expr *PromotedCall = DRE;
448 UsualUnaryConversions(PromotedCall);
449 TheCall->setCallee(PromotedCall);
Mike Stump1eb44332009-09-09 15:08:12 +0000450
Chris Lattner5caa3702009-05-08 06:58:22 +0000451
452 // Change the result type of the call to match the result type of the decl.
453 TheCall->setType(NewBuiltinDecl->getResultType());
454 return false;
455}
456
457
Chris Lattner69039812009-02-18 06:01:06 +0000458/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000459/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +0000460/// FIXME: GCC currently emits the following warning:
Mike Stump1eb44332009-09-09 15:08:12 +0000461/// "warning: input conversion stopped due to an input byte that does not
Steve Narofffd942622009-04-13 20:26:29 +0000462/// belong to the input codeset UTF-8"
463/// Note: It might also make sense to do the UTF-16 conversion here (would
464/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +0000465bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000466 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000467 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
468
469 if (!Literal || Literal->isWide()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000470 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
471 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000472 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000473 }
Mike Stump1eb44332009-09-09 15:08:12 +0000474
Daniel Dunbarf015b032009-09-22 10:03:52 +0000475 const char *Data = Literal->getStrData();
476 unsigned Length = Literal->getByteLength();
Mike Stump1eb44332009-09-09 15:08:12 +0000477
Daniel Dunbarf015b032009-09-22 10:03:52 +0000478 for (unsigned i = 0; i < Length; ++i) {
479 if (!Data[i]) {
480 Diag(getLocationOfStringLiteralByte(Literal, i),
481 diag::warn_cfstring_literal_contains_nul_character)
482 << Arg->getSourceRange();
483 break;
484 }
485 }
Mike Stump1eb44332009-09-09 15:08:12 +0000486
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000487 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000488}
489
Chris Lattnerc27c6652007-12-20 00:05:45 +0000490/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
491/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000492bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
493 Expr *Fn = TheCall->getCallee();
494 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000495 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000496 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000497 << 0 /*function call*/ << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +0000498 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000499 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000500 return true;
501 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000502
503 if (TheCall->getNumArgs() < 2) {
504 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
505 << 0 /*function call*/;
506 }
507
Chris Lattnerc27c6652007-12-20 00:05:45 +0000508 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000509 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +0000510 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000511 if (CurBlock)
512 isVariadic = CurBlock->isVariadic;
513 else if (getCurFunctionDecl()) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000514 if (FunctionProtoType* FTP =
515 dyn_cast<FunctionProtoType>(getCurFunctionDecl()->getType()))
Eli Friedman56f20ae2008-12-15 22:05:35 +0000516 isVariadic = FTP->isVariadic();
517 else
518 isVariadic = false;
519 } else {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000520 isVariadic = getCurMethodDecl()->isVariadic();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000521 }
Mike Stump1eb44332009-09-09 15:08:12 +0000522
Chris Lattnerc27c6652007-12-20 00:05:45 +0000523 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000524 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
525 return true;
526 }
Mike Stump1eb44332009-09-09 15:08:12 +0000527
Chris Lattner30ce3442007-12-19 23:59:04 +0000528 // Verify that the second argument to the builtin is the last argument of the
529 // current function or method.
530 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000531 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +0000532
Anders Carlsson88cf2262008-02-11 04:20:54 +0000533 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
534 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000535 // FIXME: This isn't correct for methods (results in bogus warning).
536 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000537 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000538 if (CurBlock)
539 LastArg = *(CurBlock->TheDecl->param_end()-1);
540 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +0000541 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000542 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000543 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000544 SecondArgIsLastNamedArgument = PV == LastArg;
545 }
546 }
Mike Stump1eb44332009-09-09 15:08:12 +0000547
Chris Lattner30ce3442007-12-19 23:59:04 +0000548 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +0000549 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000550 diag::warn_second_parameter_of_va_start_not_last_named_argument);
551 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000552}
Chris Lattner30ce3442007-12-19 23:59:04 +0000553
Chris Lattner1b9a0792007-12-20 00:26:33 +0000554/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
555/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000556bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
557 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000558 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
559 << 0 /*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000560 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +0000561 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000562 diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000563 << 0 /*function call*/
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000564 << SourceRange(TheCall->getArg(2)->getLocStart(),
565 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000566
Chris Lattner925e60d2007-12-28 05:29:59 +0000567 Expr *OrigArg0 = TheCall->getArg(0);
568 Expr *OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000569
Chris Lattner1b9a0792007-12-20 00:26:33 +0000570 // Do standard promotions between the two arguments, returning their common
571 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000572 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Daniel Dunbar403bc2b2009-02-19 19:28:43 +0000573
574 // Make sure any conversions are pushed back into the call; this is
575 // type safe since unordered compare builtins are declared as "_Bool
576 // foo(...)".
577 TheCall->setArg(0, OrigArg0);
578 TheCall->setArg(1, OrigArg1);
Mike Stump1eb44332009-09-09 15:08:12 +0000579
Douglas Gregorcde01732009-05-19 22:10:17 +0000580 if (OrigArg0->isTypeDependent() || OrigArg1->isTypeDependent())
581 return false;
582
Chris Lattner1b9a0792007-12-20 00:26:33 +0000583 // If the common type isn't a real floating type, then the arguments were
584 // invalid for this operation.
585 if (!Res->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000586 return Diag(OrigArg0->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000587 diag::err_typecheck_call_invalid_ordered_compare)
Chris Lattnerd1625842008-11-24 06:25:27 +0000588 << OrigArg0->getType() << OrigArg1->getType()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000589 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000590
Chris Lattner1b9a0792007-12-20 00:26:33 +0000591 return false;
592}
593
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000594/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
595/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000596/// to check everything. We expect the last argument to be a floating point
597/// value.
598bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
599 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +0000600 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
601 << 0 /*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000602 if (TheCall->getNumArgs() > NumArgs)
603 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000604 diag::err_typecheck_call_too_many_args)
605 << 0 /*function call*/
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000606 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000607 (*(TheCall->arg_end()-1))->getLocEnd());
608
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000609 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +0000610
Eli Friedman9ac6f622009-08-31 20:06:00 +0000611 if (OrigArg->isTypeDependent())
612 return false;
613
614 // This operation requires a floating-point number
615 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000616 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000617 diag::err_typecheck_call_invalid_unary_fp)
618 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000619
Eli Friedman9ac6f622009-08-31 20:06:00 +0000620 return false;
621}
622
Eli Friedman6cfda232008-05-20 08:23:37 +0000623bool Sema::SemaBuiltinStackAddress(CallExpr *TheCall) {
624 // The signature for these builtins is exact; the only thing we need
625 // to check is that the argument is a constant.
626 SourceLocation Loc;
Douglas Gregorcde01732009-05-19 22:10:17 +0000627 if (!TheCall->getArg(0)->isTypeDependent() &&
628 !TheCall->getArg(0)->isValueDependent() &&
629 !TheCall->getArg(0)->isIntegerConstantExpr(Context, &Loc))
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000630 return Diag(Loc, diag::err_stack_const_level) << TheCall->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000631
Eli Friedman6cfda232008-05-20 08:23:37 +0000632 return false;
633}
634
Eli Friedmand38617c2008-05-14 19:38:39 +0000635/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
636// This is declared to take (...), so we have to check everything.
Sebastian Redl0eb23302009-01-19 00:08:26 +0000637Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000638 if (TheCall->getNumArgs() < 3)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000639 return ExprError(Diag(TheCall->getLocEnd(),
640 diag::err_typecheck_call_too_few_args)
641 << 0 /*function call*/ << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000642
Douglas Gregorcde01732009-05-19 22:10:17 +0000643 unsigned numElements = std::numeric_limits<unsigned>::max();
644 if (!TheCall->getArg(0)->isTypeDependent() &&
645 !TheCall->getArg(1)->isTypeDependent()) {
646 QualType FAType = TheCall->getArg(0)->getType();
647 QualType SAType = TheCall->getArg(1)->getType();
Mike Stump1eb44332009-09-09 15:08:12 +0000648
Douglas Gregorcde01732009-05-19 22:10:17 +0000649 if (!FAType->isVectorType() || !SAType->isVectorType()) {
650 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000651 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000652 TheCall->getArg(1)->getLocEnd());
653 return ExprError();
654 }
Mike Stump1eb44332009-09-09 15:08:12 +0000655
Douglas Gregora4923eb2009-11-16 21:35:15 +0000656 if (!Context.hasSameUnqualifiedType(FAType, SAType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000657 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000658 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000659 TheCall->getArg(1)->getLocEnd());
660 return ExprError();
661 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000662
John McCall183700f2009-09-21 23:43:11 +0000663 numElements = FAType->getAs<VectorType>()->getNumElements();
Douglas Gregorcde01732009-05-19 22:10:17 +0000664 if (TheCall->getNumArgs() != numElements+2) {
665 if (TheCall->getNumArgs() < numElements+2)
666 return ExprError(Diag(TheCall->getLocEnd(),
667 diag::err_typecheck_call_too_few_args)
668 << 0 /*function call*/ << TheCall->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000669 return ExprError(Diag(TheCall->getLocEnd(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000670 diag::err_typecheck_call_too_many_args)
671 << 0 /*function call*/ << TheCall->getSourceRange());
672 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000673 }
674
675 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000676 if (TheCall->getArg(i)->isTypeDependent() ||
677 TheCall->getArg(i)->isValueDependent())
678 continue;
679
Eli Friedmand38617c2008-05-14 19:38:39 +0000680 llvm::APSInt Result(32);
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000681 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000682 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000683 diag::err_shufflevector_nonconstant_argument)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000684 << TheCall->getArg(i)->getSourceRange());
685
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000686 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000687 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000688 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000689 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000690 }
691
692 llvm::SmallVector<Expr*, 32> exprs;
693
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000694 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000695 exprs.push_back(TheCall->getArg(i));
696 TheCall->setArg(i, 0);
697 }
698
Nate Begemana88dc302009-08-12 02:10:25 +0000699 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
700 exprs.size(), exprs[0]->getType(),
Ted Kremenek8189cde2009-02-07 01:47:29 +0000701 TheCall->getCallee()->getLocStart(),
702 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000703}
Chris Lattner30ce3442007-12-19 23:59:04 +0000704
Daniel Dunbar4493f792008-07-21 22:59:13 +0000705/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
706// This is declared to take (const void*, ...) and can take two
707// optional constant int args.
708bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000709 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000710
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000711 if (NumArgs > 3)
712 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_many_args)
Chris Lattner2c21a072008-11-21 18:44:24 +0000713 << 0 /*function call*/ << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000714
715 // Argument 0 is checked for us and the remaining arguments must be
716 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000717 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000718 Expr *Arg = TheCall->getArg(i);
Douglas Gregorcde01732009-05-19 22:10:17 +0000719 if (Arg->isTypeDependent())
720 continue;
721
Eli Friedman9aef7262009-12-04 00:30:06 +0000722 if (!Arg->getType()->isIntegralType())
723 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_arg_type)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000724 << Arg->getSourceRange();
Douglas Gregorcde01732009-05-19 22:10:17 +0000725
Eli Friedman9aef7262009-12-04 00:30:06 +0000726 ImpCastExprToType(Arg, Context.IntTy, CastExpr::CK_IntegralCast);
727 TheCall->setArg(i, Arg);
728
Douglas Gregorcde01732009-05-19 22:10:17 +0000729 if (Arg->isValueDependent())
730 continue;
731
Eli Friedman9aef7262009-12-04 00:30:06 +0000732 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +0000733 if (!Arg->isIntegerConstantExpr(Result, Context))
Eli Friedman9aef7262009-12-04 00:30:06 +0000734 return Diag(TheCall->getLocStart(), diag::err_prefetch_invalid_arg_ice)
Douglas Gregorcde01732009-05-19 22:10:17 +0000735 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000736
Daniel Dunbar4493f792008-07-21 22:59:13 +0000737 // FIXME: gcc issues a warning and rewrites these to 0. These
738 // seems especially odd for the third argument since the default
739 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000740 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +0000741 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000742 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000743 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000744 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +0000745 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000746 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000747 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000748 }
749 }
750
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000751 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000752}
753
Chris Lattner21fb98e2009-09-23 06:06:36 +0000754/// SemaBuiltinEHReturnDataRegNo - Handle __builtin_eh_return_data_regno, the
755/// operand must be an integer constant.
756bool Sema::SemaBuiltinEHReturnDataRegNo(CallExpr *TheCall) {
757 llvm::APSInt Result;
758 if (!TheCall->getArg(0)->isIntegerConstantExpr(Result, Context))
759 return Diag(TheCall->getLocStart(), diag::err_expr_not_ice)
760 << TheCall->getArg(0)->getSourceRange();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +0000761
Chris Lattner21fb98e2009-09-23 06:06:36 +0000762 return false;
763}
764
765
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000766/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
767/// int type). This simply type checks that type is one of the defined
768/// constants (0-3).
Eric Christopherfee667f2009-12-23 03:49:37 +0000769// For compatability check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000770bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
771 Expr *Arg = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000772 if (Arg->isTypeDependent())
773 return false;
774
Mike Stump1eb44332009-09-09 15:08:12 +0000775 QualType ArgType = Arg->getType();
John McCall183700f2009-09-21 23:43:11 +0000776 const BuiltinType *BT = ArgType->getAs<BuiltinType>();
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000777 llvm::APSInt Result(32);
Douglas Gregorcde01732009-05-19 22:10:17 +0000778 if (!BT || BT->getKind() != BuiltinType::Int)
779 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
780 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
781
782 if (Arg->isValueDependent())
783 return false;
784
785 if (!Arg->isIntegerConstantExpr(Result, Context)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000786 return Diag(TheCall->getLocStart(), diag::err_object_size_invalid_argument)
787 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000788 }
789
790 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000791 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
792 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000793 }
794
795 return false;
796}
797
Eli Friedman586d6a82009-05-03 06:04:26 +0000798/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +0000799/// This checks that val is a constant 1.
800bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
801 Expr *Arg = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000802 if (Arg->isTypeDependent() || Arg->isValueDependent())
803 return false;
804
Eli Friedmand875fed2009-05-03 04:46:36 +0000805 llvm::APSInt Result(32);
806 if (!Arg->isIntegerConstantExpr(Result, Context) || Result != 1)
807 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
808 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
809
810 return false;
811}
812
Ted Kremenekd30ef872009-01-12 23:09:09 +0000813// Handle i > 1 ? "x" : "y", recursivelly
Ted Kremenek082d9362009-03-20 21:35:28 +0000814bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
815 bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000816 unsigned format_idx, unsigned firstDataArg) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000817 if (E->isTypeDependent() || E->isValueDependent())
818 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000819
820 switch (E->getStmtClass()) {
821 case Stmt::ConditionalOperatorClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000822 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Chris Lattner813b70d2009-12-22 06:00:13 +0000823 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000824 HasVAListArg, format_idx, firstDataArg)
Ted Kremenekd30ef872009-01-12 23:09:09 +0000825 && SemaCheckStringLiteral(C->getRHS(), TheCall,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000826 HasVAListArg, format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000827 }
828
829 case Stmt::ImplicitCastExprClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000830 const ImplicitCastExpr *Expr = cast<ImplicitCastExpr>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000831 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000832 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000833 }
834
835 case Stmt::ParenExprClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000836 const ParenExpr *Expr = cast<ParenExpr>(E);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000837 return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000838 format_idx, firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000839 }
Mike Stump1eb44332009-09-09 15:08:12 +0000840
Ted Kremenek082d9362009-03-20 21:35:28 +0000841 case Stmt::DeclRefExprClass: {
842 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000843
Ted Kremenek082d9362009-03-20 21:35:28 +0000844 // As an exception, do not flag errors for variables binding to
845 // const string literals.
846 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
847 bool isConstant = false;
848 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +0000849
Ted Kremenek082d9362009-03-20 21:35:28 +0000850 if (const ArrayType *AT = Context.getAsArrayType(T)) {
851 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000852 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000853 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +0000854 PT->getPointeeType().isConstant(Context);
855 }
Mike Stump1eb44332009-09-09 15:08:12 +0000856
Ted Kremenek082d9362009-03-20 21:35:28 +0000857 if (isConstant) {
Sebastian Redl31310a22010-02-01 20:16:42 +0000858 if (const Expr *Init = VD->getAnyInitializer())
Ted Kremenek082d9362009-03-20 21:35:28 +0000859 return SemaCheckStringLiteral(Init, TheCall,
860 HasVAListArg, format_idx, firstDataArg);
861 }
Mike Stump1eb44332009-09-09 15:08:12 +0000862
Anders Carlssond966a552009-06-28 19:55:58 +0000863 // For vprintf* functions (i.e., HasVAListArg==true), we add a
864 // special check to see if the format string is a function parameter
865 // of the function calling the printf function. If the function
866 // has an attribute indicating it is a printf-like function, then we
867 // should suppress warnings concerning non-literals being used in a call
868 // to a vprintf function. For example:
869 //
870 // void
871 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
872 // va_list ap;
873 // va_start(ap, fmt);
874 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
875 // ...
876 //
877 //
878 // FIXME: We don't have full attribute support yet, so just check to see
879 // if the argument is a DeclRefExpr that references a parameter. We'll
880 // add proper support for checking the attribute later.
881 if (HasVAListArg)
882 if (isa<ParmVarDecl>(VD))
883 return true;
Ted Kremenek082d9362009-03-20 21:35:28 +0000884 }
Mike Stump1eb44332009-09-09 15:08:12 +0000885
Ted Kremenek082d9362009-03-20 21:35:28 +0000886 return false;
887 }
Ted Kremenekd30ef872009-01-12 23:09:09 +0000888
Anders Carlsson8f031b32009-06-27 04:05:33 +0000889 case Stmt::CallExprClass: {
890 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000891 if (const ImplicitCastExpr *ICE
Anders Carlsson8f031b32009-06-27 04:05:33 +0000892 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
893 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
894 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000895 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlsson8f031b32009-06-27 04:05:33 +0000896 unsigned ArgIndex = FA->getFormatIdx();
897 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +0000898
899 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Anders Carlsson8f031b32009-06-27 04:05:33 +0000900 format_idx, firstDataArg);
901 }
902 }
903 }
904 }
Mike Stump1eb44332009-09-09 15:08:12 +0000905
Anders Carlsson8f031b32009-06-27 04:05:33 +0000906 return false;
907 }
Ted Kremenek082d9362009-03-20 21:35:28 +0000908 case Stmt::ObjCStringLiteralClass:
909 case Stmt::StringLiteralClass: {
910 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +0000911
Ted Kremenek082d9362009-03-20 21:35:28 +0000912 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +0000913 StrE = ObjCFExpr->getString();
914 else
Ted Kremenek082d9362009-03-20 21:35:28 +0000915 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000916
Ted Kremenekd30ef872009-01-12 23:09:09 +0000917 if (StrE) {
Mike Stump1eb44332009-09-09 15:08:12 +0000918 CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000919 firstDataArg);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000920 return true;
921 }
Mike Stump1eb44332009-09-09 15:08:12 +0000922
Ted Kremenekd30ef872009-01-12 23:09:09 +0000923 return false;
924 }
Mike Stump1eb44332009-09-09 15:08:12 +0000925
Ted Kremenek082d9362009-03-20 21:35:28 +0000926 default:
927 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000928 }
929}
930
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +0000931void
Mike Stump1eb44332009-09-09 15:08:12 +0000932Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
933 const CallExpr *TheCall) {
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +0000934 for (NonNullAttr::iterator i = NonNull->begin(), e = NonNull->end();
935 i != e; ++i) {
Chris Lattner12b97ff2009-05-25 18:23:36 +0000936 const Expr *ArgExpr = TheCall->getArg(*i);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +0000937 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +0000938 Expr::NPC_ValueDependentIsNotNull))
Chris Lattner12b97ff2009-05-25 18:23:36 +0000939 Diag(TheCall->getCallee()->getLocStart(), diag::warn_null_arg)
940 << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +0000941 }
942}
Ted Kremenekd30ef872009-01-12 23:09:09 +0000943
Chris Lattner59907c42007-08-10 20:18:51 +0000944/// CheckPrintfArguments - Check calls to printf (and similar functions) for
Mike Stump1eb44332009-09-09 15:08:12 +0000945/// correct use of format strings.
Ted Kremenek71895b92007-08-14 17:39:48 +0000946///
947/// HasVAListArg - A predicate indicating whether the printf-like
948/// function is passed an explicit va_arg argument (e.g., vprintf)
949///
950/// format_idx - The index into Args for the format string.
951///
952/// Improper format strings to functions in the printf family can be
953/// the source of bizarre bugs and very serious security holes. A
954/// good source of information is available in the following paper
955/// (which includes additional references):
Chris Lattner59907c42007-08-10 20:18:51 +0000956///
957/// FormatGuard: Automatic Protection From printf Format String
958/// Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
Ted Kremenek71895b92007-08-14 17:39:48 +0000959///
Ted Kremenek7f70dc82010-02-26 19:18:41 +0000960/// TODO:
Ted Kremenek71895b92007-08-14 17:39:48 +0000961/// Functionality implemented:
962///
963/// We can statically check the following properties for string
964/// literal format strings for non v.*printf functions (where the
965/// arguments are passed directly):
966//
967/// (1) Are the number of format conversions equal to the number of
968/// data arguments?
969///
970/// (2) Does each format conversion correctly match the type of the
Ted Kremenek7f70dc82010-02-26 19:18:41 +0000971/// corresponding data argument?
Ted Kremenek71895b92007-08-14 17:39:48 +0000972///
973/// Moreover, for all printf functions we can:
974///
975/// (3) Check for a missing format string (when not caught by type checking).
976///
977/// (4) Check for no-operation flags; e.g. using "#" with format
978/// conversion 'c' (TODO)
979///
980/// (5) Check the use of '%n', a major source of security holes.
981///
982/// (6) Check for malformed format conversions that don't specify anything.
983///
984/// (7) Check for empty format strings. e.g: printf("");
985///
986/// (8) Check that the format string is a wide literal.
987///
988/// All of these checks can be done by parsing the format string.
989///
Chris Lattner59907c42007-08-10 20:18:51 +0000990void
Mike Stump1eb44332009-09-09 15:08:12 +0000991Sema::CheckPrintfArguments(const CallExpr *TheCall, bool HasVAListArg,
Douglas Gregor3c385e52009-02-14 18:57:46 +0000992 unsigned format_idx, unsigned firstDataArg) {
Ted Kremenek082d9362009-03-20 21:35:28 +0000993 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +0000994
Sebastian Redl4a2614e2009-11-17 18:02:24 +0000995 // The way the format attribute works in GCC, the implicit this argument
996 // of member functions is counted. However, it doesn't appear in our own
997 // lists, so decrement format_idx in that case.
998 if (isa<CXXMemberCallExpr>(TheCall)) {
999 // Catch a format attribute mistakenly referring to the object argument.
1000 if (format_idx == 0)
1001 return;
1002 --format_idx;
1003 if(firstDataArg != 0)
1004 --firstDataArg;
1005 }
1006
Mike Stump1eb44332009-09-09 15:08:12 +00001007 // CHECK: printf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +00001008 if (format_idx >= TheCall->getNumArgs()) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001009 Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string)
1010 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001011 return;
1012 }
Mike Stump1eb44332009-09-09 15:08:12 +00001013
Ted Kremenek082d9362009-03-20 21:35:28 +00001014 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001015
Chris Lattner59907c42007-08-10 20:18:51 +00001016 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001017 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001018 // Dynamically generated format strings are difficult to
1019 // automatically vet at compile time. Requiring that format strings
1020 // are string literals: (1) permits the checking of format strings by
1021 // the compiler and thereby (2) can practically remove the source of
1022 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001023
Mike Stump1eb44332009-09-09 15:08:12 +00001024 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001025 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001026 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001027 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001028 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
1029 firstDataArg))
1030 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001031
Chris Lattner655f1412009-04-29 04:59:47 +00001032 // If there are no arguments specified, warn with -Wformat-security, otherwise
1033 // warn only with -Wformat-nonliteral.
1034 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump1eb44332009-09-09 15:08:12 +00001035 Diag(TheCall->getArg(format_idx)->getLocStart(),
Chris Lattner655f1412009-04-29 04:59:47 +00001036 diag::warn_printf_nonliteral_noargs)
1037 << OrigFormatExpr->getSourceRange();
1038 else
Mike Stump1eb44332009-09-09 15:08:12 +00001039 Diag(TheCall->getArg(format_idx)->getLocStart(),
Chris Lattner655f1412009-04-29 04:59:47 +00001040 diag::warn_printf_nonliteral)
1041 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001042}
Ted Kremenek71895b92007-08-14 17:39:48 +00001043
Ted Kremeneke0e53132010-01-28 23:39:18 +00001044namespace {
Ted Kremenek74d56a12010-02-04 20:46:58 +00001045class CheckPrintfHandler : public analyze_printf::FormatStringHandler {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001046 Sema &S;
1047 const StringLiteral *FExpr;
1048 const Expr *OrigFormatExpr;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001049 const unsigned NumDataArgs;
1050 const bool IsObjCLiteral;
1051 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001052 const bool HasVAListArg;
1053 const CallExpr *TheCall;
1054 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001055 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001056 bool usesPositionalArgs;
1057 bool atFirstArg;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001058public:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001059 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1060 const Expr *origFormatExpr,
1061 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001062 const char *beg, bool hasVAListArg,
1063 const CallExpr *theCall, unsigned formatIdx)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001064 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001065 NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001066 IsObjCLiteral(isObjCLiteral), Beg(beg),
1067 HasVAListArg(hasVAListArg),
Ted Kremenekefaff192010-02-27 01:41:03 +00001068 TheCall(theCall), FormatIdx(formatIdx),
1069 usesPositionalArgs(false), atFirstArg(true) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001070 CoveredArgs.resize(numDataArgs);
1071 CoveredArgs.reset();
1072 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001073
Ted Kremenek07d161f2010-01-29 01:50:07 +00001074 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001075
Ted Kremenek808015a2010-01-29 03:16:21 +00001076 void HandleIncompleteFormatSpecifier(const char *startSpecifier,
1077 unsigned specifierLen);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001078
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001079 bool
Ted Kremenek74d56a12010-02-04 20:46:58 +00001080 HandleInvalidConversionSpecifier(const analyze_printf::FormatSpecifier &FS,
1081 const char *startSpecifier,
1082 unsigned specifierLen);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001083
Ted Kremenekefaff192010-02-27 01:41:03 +00001084 virtual void HandleInvalidPosition(const char *startSpecifier,
1085 unsigned specifierLen,
1086 analyze_printf::PositionContext p);
1087
1088 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1089
Ted Kremeneke0e53132010-01-28 23:39:18 +00001090 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001091
Ted Kremeneke0e53132010-01-28 23:39:18 +00001092 bool HandleFormatSpecifier(const analyze_printf::FormatSpecifier &FS,
1093 const char *startSpecifier,
1094 unsigned specifierLen);
1095private:
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001096 SourceRange getFormatStringRange();
1097 SourceRange getFormatSpecifierRange(const char *startSpecifier,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001098 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001099 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001100
Ted Kremenekefaff192010-02-27 01:41:03 +00001101 bool HandleAmount(const analyze_printf::OptionalAmount &Amt, unsigned k,
1102 const char *startSpecifier, unsigned specifierLen);
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001103 void HandleFlags(const analyze_printf::FormatSpecifier &FS,
1104 llvm::StringRef flag, llvm::StringRef cspec,
1105 const char *startSpecifier, unsigned specifierLen);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001106
Ted Kremenek0d277352010-01-29 01:06:55 +00001107 const Expr *getDataArg(unsigned i) const;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001108};
1109}
1110
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001111SourceRange CheckPrintfHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001112 return OrigFormatExpr->getSourceRange();
1113}
1114
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001115SourceRange CheckPrintfHandler::
1116getFormatSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
1117 return SourceRange(getLocationOfByte(startSpecifier),
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001118 getLocationOfByte(startSpecifier+specifierLen-1));
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001119}
1120
Ted Kremeneke0e53132010-01-28 23:39:18 +00001121SourceLocation CheckPrintfHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001122 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001123}
1124
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001125void CheckPrintfHandler::
Ted Kremenek808015a2010-01-29 03:16:21 +00001126HandleIncompleteFormatSpecifier(const char *startSpecifier,
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001127 unsigned specifierLen) {
Ted Kremenek808015a2010-01-29 03:16:21 +00001128 SourceLocation Loc = getLocationOfByte(startSpecifier);
1129 S.Diag(Loc, diag::warn_printf_incomplete_specifier)
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001130 << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek808015a2010-01-29 03:16:21 +00001131}
1132
Ted Kremenekefaff192010-02-27 01:41:03 +00001133void
1134CheckPrintfHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1135 analyze_printf::PositionContext p) {
1136 SourceLocation Loc = getLocationOfByte(startPos);
1137 S.Diag(Loc, diag::warn_printf_invalid_positional_specifier)
1138 << (unsigned) p << getFormatSpecifierRange(startPos, posLen);
1139}
1140
1141void CheckPrintfHandler::HandleZeroPosition(const char *startPos,
1142 unsigned posLen) {
1143 SourceLocation Loc = getLocationOfByte(startPos);
1144 S.Diag(Loc, diag::warn_printf_zero_positional_specifier)
1145 << getFormatSpecifierRange(startPos, posLen);
1146}
1147
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001148bool CheckPrintfHandler::
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001149HandleInvalidConversionSpecifier(const analyze_printf::FormatSpecifier &FS,
1150 const char *startSpecifier,
1151 unsigned specifierLen) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001152
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001153 unsigned argIndex = FS.getArgIndex();
1154 bool keepGoing = true;
1155 if (argIndex < NumDataArgs) {
1156 // Consider the argument coverered, even though the specifier doesn't
1157 // make sense.
1158 CoveredArgs.set(argIndex);
1159 }
1160 else {
1161 // If argIndex exceeds the number of data arguments we
1162 // don't issue a warning because that is just a cascade of warnings (and
1163 // they may have intended '%%' anyway). We don't want to continue processing
1164 // the format string after this point, however, as we will like just get
1165 // gibberish when trying to match arguments.
1166 keepGoing = false;
1167 }
1168
Ted Kremenek808015a2010-01-29 03:16:21 +00001169 const analyze_printf::ConversionSpecifier &CS =
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001170 FS.getConversionSpecifier();
Ted Kremenek808015a2010-01-29 03:16:21 +00001171 SourceLocation Loc = getLocationOfByte(CS.getStart());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001172 S.Diag(Loc, diag::warn_printf_invalid_conversion)
Ted Kremenek808015a2010-01-29 03:16:21 +00001173 << llvm::StringRef(CS.getStart(), CS.getLength())
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001174 << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001175
1176 return keepGoing;
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001177}
1178
Ted Kremeneke0e53132010-01-28 23:39:18 +00001179void CheckPrintfHandler::HandleNullChar(const char *nullCharacter) {
1180 // The presence of a null character is likely an error.
1181 S.Diag(getLocationOfByte(nullCharacter),
1182 diag::warn_printf_format_string_contains_null_char)
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001183 << getFormatStringRange();
Ted Kremeneke0e53132010-01-28 23:39:18 +00001184}
1185
Ted Kremenek0d277352010-01-29 01:06:55 +00001186const Expr *CheckPrintfHandler::getDataArg(unsigned i) const {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001187 return TheCall->getArg(FormatIdx + i + 1);
Ted Kremenek0d277352010-01-29 01:06:55 +00001188}
1189
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001190
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001191
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001192void CheckPrintfHandler::HandleFlags(const analyze_printf::FormatSpecifier &FS,
1193 llvm::StringRef flag,
1194 llvm::StringRef cspec,
1195 const char *startSpecifier,
1196 unsigned specifierLen) {
1197 const analyze_printf::ConversionSpecifier &CS = FS.getConversionSpecifier();
1198 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_nonsensical_flag)
1199 << flag << cspec << getFormatSpecifierRange(startSpecifier, specifierLen);
1200}
1201
Ted Kremenek0d277352010-01-29 01:06:55 +00001202bool
1203CheckPrintfHandler::HandleAmount(const analyze_printf::OptionalAmount &Amt,
Ted Kremenekefaff192010-02-27 01:41:03 +00001204 unsigned k, const char *startSpecifier,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001205 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001206
1207 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001208 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001209 unsigned argIndex = Amt.getArgIndex();
1210 if (argIndex >= NumDataArgs) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001211 S.Diag(getLocationOfByte(Amt.getStart()),
1212 diag::warn_printf_asterisk_missing_arg)
1213 << k << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek0d277352010-01-29 01:06:55 +00001214 // Don't do any more checking. We will just emit
1215 // spurious errors.
1216 return false;
1217 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001218
Ted Kremenek0d277352010-01-29 01:06:55 +00001219 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00001220 // Although not in conformance with C99, we also allow the argument to be
1221 // an 'unsigned int' as that is a reasonably safe case. GCC also
1222 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001223 CoveredArgs.set(argIndex);
1224 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00001225 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001226
1227 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1228 assert(ATR.isValid());
1229
1230 if (!ATR.matchesType(S.Context, T)) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001231 S.Diag(getLocationOfByte(Amt.getStart()),
1232 diag::warn_printf_asterisk_wrong_type)
1233 << k
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001234 << ATR.getRepresentativeType(S.Context) << T
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001235 << getFormatSpecifierRange(startSpecifier, specifierLen)
1236 << Arg->getSourceRange();
Ted Kremenek0d277352010-01-29 01:06:55 +00001237 // Don't do any more checking. We will just emit
1238 // spurious errors.
1239 return false;
1240 }
1241 }
1242 }
1243 return true;
1244}
Ted Kremenek0d277352010-01-29 01:06:55 +00001245
Ted Kremeneke0e53132010-01-28 23:39:18 +00001246bool
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001247CheckPrintfHandler::HandleFormatSpecifier(const analyze_printf::FormatSpecifier
1248 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001249 const char *startSpecifier,
1250 unsigned specifierLen) {
1251
Ted Kremenekefaff192010-02-27 01:41:03 +00001252 using namespace analyze_printf;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001253 const ConversionSpecifier &CS = FS.getConversionSpecifier();
1254
Ted Kremenekefaff192010-02-27 01:41:03 +00001255 if (atFirstArg) {
1256 atFirstArg = false;
1257 usesPositionalArgs = FS.usesPositionalArg();
1258 }
1259 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1260 // Cannot mix-and-match positional and non-positional arguments.
1261 S.Diag(getLocationOfByte(CS.getStart()),
1262 diag::warn_printf_mix_positional_nonpositional_args)
1263 << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek0d277352010-01-29 01:06:55 +00001264 return false;
1265 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001266
Ted Kremenekefaff192010-02-27 01:41:03 +00001267 // First check if the field width, precision, and conversion specifier
1268 // have matching data arguments.
1269 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1270 startSpecifier, specifierLen)) {
1271 return false;
1272 }
1273
1274 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1275 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001276 return false;
1277 }
1278
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001279 if (!CS.consumesDataArgument()) {
1280 // FIXME: Technically specifying a precision or field width here
1281 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001282 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001283 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001284
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001285 // Consume the argument.
1286 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00001287 if (argIndex < NumDataArgs) {
1288 // The check to see if the argIndex is valid will come later.
1289 // We set the bit here because we may exit early from this
1290 // function if we encounter some other error.
1291 CoveredArgs.set(argIndex);
1292 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001293
1294 // Check for using an Objective-C specific conversion specifier
1295 // in a non-ObjC literal.
1296 if (!IsObjCLiteral && CS.isObjCArg()) {
1297 return HandleInvalidConversionSpecifier(FS, startSpecifier, specifierLen);
1298 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001299
Ted Kremeneke82d8042010-01-29 01:35:25 +00001300 // Are we using '%n'? Issue a warning about this being
1301 // a possible security issue.
1302 if (CS.getKind() == ConversionSpecifier::OutIntPtrArg) {
1303 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001304 << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremeneke82d8042010-01-29 01:35:25 +00001305 // Continue checking the other format specifiers.
1306 return true;
1307 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001308
1309 if (CS.getKind() == ConversionSpecifier::VoidPtrArg) {
1310 if (FS.getPrecision().getHowSpecified() != OptionalAmount::NotSpecified)
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001311 S.Diag(getLocationOfByte(CS.getStart()),
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001312 diag::warn_printf_nonsensical_precision)
1313 << CS.getCharacters()
1314 << getFormatSpecifierRange(startSpecifier, specifierLen);
1315 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001316 if (CS.getKind() == ConversionSpecifier::VoidPtrArg ||
1317 CS.getKind() == ConversionSpecifier::CStrArg) {
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001318 // FIXME: Instead of using "0", "+", etc., eventually get them from
1319 // the FormatSpecifier.
1320 if (FS.hasLeadingZeros())
1321 HandleFlags(FS, "0", CS.getCharacters(), startSpecifier, specifierLen);
1322 if (FS.hasPlusPrefix())
1323 HandleFlags(FS, "+", CS.getCharacters(), startSpecifier, specifierLen);
1324 if (FS.hasSpacePrefix())
1325 HandleFlags(FS, " ", CS.getCharacters(), startSpecifier, specifierLen);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001326 }
1327
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001328 // The remaining checks depend on the data arguments.
1329 if (HasVAListArg)
1330 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001331
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001332 if (argIndex >= NumDataArgs) {
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001333 S.Diag(getLocationOfByte(CS.getStart()),
1334 diag::warn_printf_insufficient_data_args)
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001335 << getFormatSpecifierRange(startSpecifier, specifierLen);
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001336 // Don't do any more checking.
1337 return false;
1338 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001339
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001340 // Now type check the data expression that matches the
1341 // format specifier.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001342 const Expr *Ex = getDataArg(argIndex);
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001343 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001344 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
1345 // Check if we didn't match because of an implicit cast from a 'char'
1346 // or 'short' to an 'int'. This is done because printf is a varargs
1347 // function.
1348 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
1349 if (ICE->getType() == S.Context.IntTy)
1350 if (ATR.matchesType(S.Context, ICE->getSubExpr()->getType()))
1351 return true;
Ted Kremenek105d41c2010-02-01 19:38:10 +00001352
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001353 S.Diag(getLocationOfByte(CS.getStart()),
1354 diag::warn_printf_conversion_argument_type_mismatch)
1355 << ATR.getRepresentativeType(S.Context) << Ex->getType()
Ted Kremenek1497bff2010-02-11 19:37:25 +00001356 << getFormatSpecifierRange(startSpecifier, specifierLen)
1357 << Ex->getSourceRange();
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001358 }
Ted Kremeneke0e53132010-01-28 23:39:18 +00001359
1360 return true;
1361}
1362
Ted Kremenek07d161f2010-01-29 01:50:07 +00001363void CheckPrintfHandler::DoneProcessing() {
1364 // Does the number of data arguments exceed the number of
1365 // format conversions in the format string?
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001366 if (!HasVAListArg) {
1367 // Find any arguments that weren't covered.
1368 CoveredArgs.flip();
1369 signed notCoveredArg = CoveredArgs.find_first();
1370 if (notCoveredArg >= 0) {
1371 assert((unsigned)notCoveredArg < NumDataArgs);
1372 S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(),
1373 diag::warn_printf_data_arg_not_used)
1374 << getFormatStringRange();
1375 }
1376 }
Ted Kremenek07d161f2010-01-29 01:50:07 +00001377}
Ted Kremeneke0e53132010-01-28 23:39:18 +00001378
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001379void Sema::CheckPrintfString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001380 const Expr *OrigFormatExpr,
1381 const CallExpr *TheCall, bool HasVAListArg,
1382 unsigned format_idx, unsigned firstDataArg) {
1383
Ted Kremeneke0e53132010-01-28 23:39:18 +00001384 // CHECK: is the format string a wide literal?
1385 if (FExpr->isWide()) {
1386 Diag(FExpr->getLocStart(),
1387 diag::warn_printf_format_string_is_wide_literal)
1388 << OrigFormatExpr->getSourceRange();
1389 return;
1390 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001391
Ted Kremeneke0e53132010-01-28 23:39:18 +00001392 // Str - The format string. NOTE: this is NOT null-terminated!
1393 const char *Str = FExpr->getStrData();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001394
Ted Kremeneke0e53132010-01-28 23:39:18 +00001395 // CHECK: empty format string?
1396 unsigned StrLen = FExpr->getByteLength();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001397
Ted Kremeneke0e53132010-01-28 23:39:18 +00001398 if (StrLen == 0) {
1399 Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string)
1400 << OrigFormatExpr->getSourceRange();
1401 return;
1402 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001403
Ted Kremeneke0e53132010-01-28 23:39:18 +00001404 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr,
1405 TheCall->getNumArgs() - firstDataArg,
Ted Kremenek0d277352010-01-29 01:06:55 +00001406 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1407 HasVAListArg, TheCall, format_idx);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001408
Ted Kremenek74d56a12010-02-04 20:46:58 +00001409 if (!analyze_printf::ParseFormatString(H, Str, Str + StrLen))
Ted Kremenek808015a2010-01-29 03:16:21 +00001410 H.DoneProcessing();
Ted Kremenekce7024e2010-01-28 01:18:22 +00001411}
1412
Ted Kremenek06de2762007-08-17 16:46:58 +00001413//===--- CHECK: Return Address of Stack Variable --------------------------===//
1414
1415static DeclRefExpr* EvalVal(Expr *E);
1416static DeclRefExpr* EvalAddr(Expr* E);
1417
1418/// CheckReturnStackAddr - Check if a return statement returns the address
1419/// of a stack variable.
1420void
1421Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1422 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00001423
Ted Kremenek06de2762007-08-17 16:46:58 +00001424 // Perform checking for returned stack addresses.
Steve Naroffdd972f22008-09-05 22:11:13 +00001425 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Ted Kremenek06de2762007-08-17 16:46:58 +00001426 if (DeclRefExpr *DR = EvalAddr(RetValExp))
Chris Lattner3c73c412008-11-19 08:23:25 +00001427 Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
Chris Lattner08631c52008-11-23 21:45:46 +00001428 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001429
Steve Naroffc50a4a52008-09-16 22:25:10 +00001430 // Skip over implicit cast expressions when checking for block expressions.
Chris Lattner4ca606e2009-09-08 00:36:37 +00001431 RetValExp = RetValExp->IgnoreParenCasts();
Steve Naroffc50a4a52008-09-16 22:25:10 +00001432
Chris Lattner9e6b37a2009-10-30 04:01:58 +00001433 if (BlockExpr *C = dyn_cast<BlockExpr>(RetValExp))
Mike Stump397195b2009-04-17 00:09:41 +00001434 if (C->hasBlockDeclRefExprs())
1435 Diag(C->getLocStart(), diag::err_ret_local_block)
1436 << C->getSourceRange();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001437
Chris Lattner9e6b37a2009-10-30 04:01:58 +00001438 if (AddrLabelExpr *ALE = dyn_cast<AddrLabelExpr>(RetValExp))
1439 Diag(ALE->getLocStart(), diag::warn_ret_addr_label)
1440 << ALE->getSourceRange();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001441
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001442 } else if (lhsType->isReferenceType()) {
1443 // Perform checking for stack values returned by reference.
Douglas Gregor49badde2008-10-27 19:41:14 +00001444 // Check for a reference to the stack
1445 if (DeclRefExpr *DR = EvalVal(RetValExp))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001446 Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
Chris Lattner08631c52008-11-23 21:45:46 +00001447 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +00001448 }
1449}
1450
1451/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1452/// check if the expression in a return statement evaluates to an address
1453/// to a location on the stack. The recursion is used to traverse the
1454/// AST of the return expression, with recursion backtracking when we
1455/// encounter a subexpression that (1) clearly does not lead to the address
1456/// of a stack variable or (2) is something we cannot determine leads to
1457/// the address of a stack variable based on such local checking.
1458///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001459/// EvalAddr processes expressions that are pointers that are used as
1460/// references (and not L-values). EvalVal handles all other values.
Mike Stump1eb44332009-09-09 15:08:12 +00001461/// At the base case of the recursion is a check for a DeclRefExpr* in
Ted Kremenek06de2762007-08-17 16:46:58 +00001462/// the refers to a stack variable.
1463///
1464/// This implementation handles:
1465///
1466/// * pointer-to-pointer casts
1467/// * implicit conversions from array references to pointers
1468/// * taking the address of fields
1469/// * arbitrary interplay between "&" and "*" operators
1470/// * pointer arithmetic from an address of a stack variable
1471/// * taking the address of an array element where the array is on the stack
1472static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek06de2762007-08-17 16:46:58 +00001473 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00001474 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00001475 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001476 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001477 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00001478
Ted Kremenek06de2762007-08-17 16:46:58 +00001479 // Our "symbolic interpreter" is just a dispatch off the currently
1480 // viewed AST node. We then recursively traverse the AST by calling
1481 // EvalAddr and EvalVal appropriately.
1482 switch (E->getStmtClass()) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001483 case Stmt::ParenExprClass:
1484 // Ignore parentheses.
1485 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek06de2762007-08-17 16:46:58 +00001486
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001487 case Stmt::UnaryOperatorClass: {
1488 // The only unary operator that make sense to handle here
1489 // is AddrOf. All others don't make sense as pointers.
1490 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001491
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001492 if (U->getOpcode() == UnaryOperator::AddrOf)
1493 return EvalVal(U->getSubExpr());
1494 else
Ted Kremenek06de2762007-08-17 16:46:58 +00001495 return NULL;
1496 }
Mike Stump1eb44332009-09-09 15:08:12 +00001497
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001498 case Stmt::BinaryOperatorClass: {
1499 // Handle pointer arithmetic. All other binary operators are not valid
1500 // in this context.
1501 BinaryOperator *B = cast<BinaryOperator>(E);
1502 BinaryOperator::Opcode op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00001503
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001504 if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
1505 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001506
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001507 Expr *Base = B->getLHS();
1508
1509 // Determine which argument is the real pointer base. It could be
1510 // the RHS argument instead of the LHS.
1511 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00001512
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001513 assert (Base->getType()->isPointerType());
1514 return EvalAddr(Base);
1515 }
Steve Naroff61f40a22008-09-10 19:17:48 +00001516
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001517 // For conditional operators we need to see if either the LHS or RHS are
1518 // valid DeclRefExpr*s. If one of them is valid, we return it.
1519 case Stmt::ConditionalOperatorClass: {
1520 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001521
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001522 // Handle the GNU extension for missing LHS.
1523 if (Expr *lhsExpr = C->getLHS())
1524 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
1525 return LHS;
1526
1527 return EvalAddr(C->getRHS());
1528 }
Mike Stump1eb44332009-09-09 15:08:12 +00001529
Ted Kremenek54b52742008-08-07 00:49:01 +00001530 // For casts, we need to handle conversions from arrays to
1531 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00001532 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001533 case Stmt::CStyleCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001534 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001535 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00001536 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001537
Steve Naroffdd972f22008-09-05 22:11:13 +00001538 if (SubExpr->getType()->isPointerType() ||
1539 SubExpr->getType()->isBlockPointerType() ||
1540 SubExpr->getType()->isObjCQualifiedIdType())
Ted Kremenek54b52742008-08-07 00:49:01 +00001541 return EvalAddr(SubExpr);
1542 else if (T->isArrayType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001543 return EvalVal(SubExpr);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001544 else
Ted Kremenek54b52742008-08-07 00:49:01 +00001545 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001546 }
Mike Stump1eb44332009-09-09 15:08:12 +00001547
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001548 // C++ casts. For dynamic casts, static casts, and const casts, we
1549 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00001550 // through the cast. In the case the dynamic cast doesn't fail (and
1551 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001552 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00001553 // FIXME: The comment about is wrong; we're not always converting
1554 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00001555 // handle references to objects.
1556 case Stmt::CXXStaticCastExprClass:
1557 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001558 case Stmt::CXXConstCastExprClass:
1559 case Stmt::CXXReinterpretCastExprClass: {
1560 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00001561 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001562 return EvalAddr(S);
1563 else
1564 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001565 }
Mike Stump1eb44332009-09-09 15:08:12 +00001566
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001567 // Everything else: we simply don't reason about them.
1568 default:
1569 return NULL;
1570 }
Ted Kremenek06de2762007-08-17 16:46:58 +00001571}
Mike Stump1eb44332009-09-09 15:08:12 +00001572
Ted Kremenek06de2762007-08-17 16:46:58 +00001573
1574/// EvalVal - This function is complements EvalAddr in the mutual recursion.
1575/// See the comments for EvalAddr for more details.
1576static DeclRefExpr* EvalVal(Expr *E) {
Mike Stump1eb44332009-09-09 15:08:12 +00001577
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001578 // We should only be called for evaluating non-pointer expressions, or
1579 // expressions with a pointer type that are not used as references but instead
1580 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00001581
Ted Kremenek06de2762007-08-17 16:46:58 +00001582 // Our "symbolic interpreter" is just a dispatch off the currently
1583 // viewed AST node. We then recursively traverse the AST by calling
1584 // EvalAddr and EvalVal appropriately.
1585 switch (E->getStmtClass()) {
Douglas Gregora2813ce2009-10-23 18:54:35 +00001586 case Stmt::DeclRefExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00001587 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
1588 // at code that refers to a variable's name. We check if it has local
1589 // storage within the function, and if so, return the expression.
1590 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001591
Ted Kremenek06de2762007-08-17 16:46:58 +00001592 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Mike Stump1eb44332009-09-09 15:08:12 +00001593 if (V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
1594
Ted Kremenek06de2762007-08-17 16:46:58 +00001595 return NULL;
1596 }
Mike Stump1eb44332009-09-09 15:08:12 +00001597
Ted Kremenek06de2762007-08-17 16:46:58 +00001598 case Stmt::ParenExprClass:
1599 // Ignore parentheses.
1600 return EvalVal(cast<ParenExpr>(E)->getSubExpr());
Mike Stump1eb44332009-09-09 15:08:12 +00001601
Ted Kremenek06de2762007-08-17 16:46:58 +00001602 case Stmt::UnaryOperatorClass: {
1603 // The only unary operator that make sense to handle here
1604 // is Deref. All others don't resolve to a "name." This includes
1605 // handling all sorts of rvalues passed to a unary operator.
1606 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001607
Ted Kremenek06de2762007-08-17 16:46:58 +00001608 if (U->getOpcode() == UnaryOperator::Deref)
1609 return EvalAddr(U->getSubExpr());
1610
1611 return NULL;
1612 }
Mike Stump1eb44332009-09-09 15:08:12 +00001613
Ted Kremenek06de2762007-08-17 16:46:58 +00001614 case Stmt::ArraySubscriptExprClass: {
1615 // Array subscripts are potential references to data on the stack. We
1616 // retrieve the DeclRefExpr* for the array variable if it indeed
1617 // has local storage.
Ted Kremenek23245122007-08-20 16:18:38 +00001618 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek06de2762007-08-17 16:46:58 +00001619 }
Mike Stump1eb44332009-09-09 15:08:12 +00001620
Ted Kremenek06de2762007-08-17 16:46:58 +00001621 case Stmt::ConditionalOperatorClass: {
1622 // For conditional operators we need to see if either the LHS or RHS are
1623 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
1624 ConditionalOperator *C = cast<ConditionalOperator>(E);
1625
Anders Carlsson39073232007-11-30 19:04:31 +00001626 // Handle the GNU extension for missing LHS.
1627 if (Expr *lhsExpr = C->getLHS())
1628 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
1629 return LHS;
1630
1631 return EvalVal(C->getRHS());
Ted Kremenek06de2762007-08-17 16:46:58 +00001632 }
Mike Stump1eb44332009-09-09 15:08:12 +00001633
Ted Kremenek06de2762007-08-17 16:46:58 +00001634 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00001635 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00001636 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001637
Ted Kremenek06de2762007-08-17 16:46:58 +00001638 // Check for indirect access. We only want direct field accesses.
1639 if (!M->isArrow())
1640 return EvalVal(M->getBase());
1641 else
1642 return NULL;
1643 }
Mike Stump1eb44332009-09-09 15:08:12 +00001644
Ted Kremenek06de2762007-08-17 16:46:58 +00001645 // Everything else: we simply don't reason about them.
1646 default:
1647 return NULL;
1648 }
1649}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001650
1651//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
1652
1653/// Check for comparisons of floating point operands using != and ==.
1654/// Issue a warning if these are no self-comparisons, as they are not likely
1655/// to do what the programmer intended.
1656void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
1657 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001658
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00001659 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek32e97b62008-01-17 17:55:13 +00001660 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001661
1662 // Special case: check for x == x (which is OK).
1663 // Do not emit warnings for such cases.
1664 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
1665 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
1666 if (DRL->getDecl() == DRR->getDecl())
1667 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001668
1669
Ted Kremenek1b500bb2007-11-29 00:59:04 +00001670 // Special case: check for comparisons against literals that can be exactly
1671 // represented by APFloat. In such cases, do not emit a warning. This
1672 // is a heuristic: often comparison against such literals are used to
1673 // detect if a value in a variable has not changed. This clearly can
1674 // lead to false negatives.
1675 if (EmitWarning) {
1676 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
1677 if (FLL->isExact())
1678 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001679 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00001680 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
1681 if (FLR->isExact())
1682 EmitWarning = false;
1683 }
1684 }
Mike Stump1eb44332009-09-09 15:08:12 +00001685
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001686 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00001687 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001688 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001689 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001690 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001691
Sebastian Redl0eb23302009-01-19 00:08:26 +00001692 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001693 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00001694 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001695 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001696
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001697 // Emit the diagnostic.
1698 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001699 Diag(loc, diag::warn_floatingpoint_eq)
1700 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00001701}
John McCallba26e582010-01-04 23:21:16 +00001702
John McCallf2370c92010-01-06 05:24:50 +00001703//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
1704//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00001705
John McCallf2370c92010-01-06 05:24:50 +00001706namespace {
John McCallba26e582010-01-04 23:21:16 +00001707
John McCallf2370c92010-01-06 05:24:50 +00001708/// Structure recording the 'active' range of an integer-valued
1709/// expression.
1710struct IntRange {
1711 /// The number of bits active in the int.
1712 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00001713
John McCallf2370c92010-01-06 05:24:50 +00001714 /// True if the int is known not to have negative values.
1715 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00001716
John McCallf2370c92010-01-06 05:24:50 +00001717 IntRange() {}
1718 IntRange(unsigned Width, bool NonNegative)
1719 : Width(Width), NonNegative(NonNegative)
1720 {}
John McCallba26e582010-01-04 23:21:16 +00001721
John McCallf2370c92010-01-06 05:24:50 +00001722 // Returns the range of the bool type.
1723 static IntRange forBoolType() {
1724 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00001725 }
1726
John McCallf2370c92010-01-06 05:24:50 +00001727 // Returns the range of an integral type.
1728 static IntRange forType(ASTContext &C, QualType T) {
1729 return forCanonicalType(C, T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00001730 }
1731
John McCallf2370c92010-01-06 05:24:50 +00001732 // Returns the range of an integeral type based on its canonical
1733 // representation.
1734 static IntRange forCanonicalType(ASTContext &C, const Type *T) {
1735 assert(T->isCanonicalUnqualified());
1736
1737 if (const VectorType *VT = dyn_cast<VectorType>(T))
1738 T = VT->getElementType().getTypePtr();
1739 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
1740 T = CT->getElementType().getTypePtr();
1741 if (const EnumType *ET = dyn_cast<EnumType>(T))
1742 T = ET->getDecl()->getIntegerType().getTypePtr();
1743
1744 const BuiltinType *BT = cast<BuiltinType>(T);
1745 assert(BT->isInteger());
1746
1747 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
1748 }
1749
1750 // Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00001751 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00001752 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00001753 L.NonNegative && R.NonNegative);
1754 }
1755
1756 // Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00001757 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00001758 return IntRange(std::min(L.Width, R.Width),
1759 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00001760 }
1761};
1762
1763IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
1764 if (value.isSigned() && value.isNegative())
1765 return IntRange(value.getMinSignedBits(), false);
1766
1767 if (value.getBitWidth() > MaxWidth)
1768 value.trunc(MaxWidth);
1769
1770 // isNonNegative() just checks the sign bit without considering
1771 // signedness.
1772 return IntRange(value.getActiveBits(), true);
1773}
1774
John McCall0acc3112010-01-06 22:57:21 +00001775IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCallf2370c92010-01-06 05:24:50 +00001776 unsigned MaxWidth) {
1777 if (result.isInt())
1778 return GetValueRange(C, result.getInt(), MaxWidth);
1779
1780 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00001781 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
1782 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
1783 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
1784 R = IntRange::join(R, El);
1785 }
John McCallf2370c92010-01-06 05:24:50 +00001786 return R;
1787 }
1788
1789 if (result.isComplexInt()) {
1790 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
1791 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
1792 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00001793 }
1794
1795 // This can happen with lossless casts to intptr_t of "based" lvalues.
1796 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00001797 // FIXME: The only reason we need to pass the type in here is to get
1798 // the sign right on this one case. It would be nice if APValue
1799 // preserved this.
John McCallf2370c92010-01-06 05:24:50 +00001800 assert(result.isLValue());
John McCall0acc3112010-01-06 22:57:21 +00001801 return IntRange(MaxWidth, Ty->isUnsignedIntegerType());
John McCall51313c32010-01-04 23:31:57 +00001802}
John McCallf2370c92010-01-06 05:24:50 +00001803
1804/// Pseudo-evaluate the given integer expression, estimating the
1805/// range of values it might take.
1806///
1807/// \param MaxWidth - the width to which the value will be truncated
1808IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
1809 E = E->IgnoreParens();
1810
1811 // Try a full evaluation first.
1812 Expr::EvalResult result;
1813 if (E->Evaluate(result, C))
John McCall0acc3112010-01-06 22:57:21 +00001814 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00001815
1816 // I think we only want to look through implicit casts here; if the
1817 // user has an explicit widening cast, we should treat the value as
1818 // being of the new, wider type.
1819 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
1820 if (CE->getCastKind() == CastExpr::CK_NoOp)
1821 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
1822
1823 IntRange OutputTypeRange = IntRange::forType(C, CE->getType());
1824
John McCall60fad452010-01-06 22:07:33 +00001825 bool isIntegerCast = (CE->getCastKind() == CastExpr::CK_IntegralCast);
1826 if (!isIntegerCast && CE->getCastKind() == CastExpr::CK_Unknown)
1827 isIntegerCast = CE->getSubExpr()->getType()->isIntegerType();
1828
John McCallf2370c92010-01-06 05:24:50 +00001829 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00001830 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00001831 return OutputTypeRange;
1832
1833 IntRange SubRange
1834 = GetExprRange(C, CE->getSubExpr(),
1835 std::min(MaxWidth, OutputTypeRange.Width));
1836
1837 // Bail out if the subexpr's range is as wide as the cast type.
1838 if (SubRange.Width >= OutputTypeRange.Width)
1839 return OutputTypeRange;
1840
1841 // Otherwise, we take the smaller width, and we're non-negative if
1842 // either the output type or the subexpr is.
1843 return IntRange(SubRange.Width,
1844 SubRange.NonNegative || OutputTypeRange.NonNegative);
1845 }
1846
1847 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1848 // If we can fold the condition, just take that operand.
1849 bool CondResult;
1850 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
1851 return GetExprRange(C, CondResult ? CO->getTrueExpr()
1852 : CO->getFalseExpr(),
1853 MaxWidth);
1854
1855 // Otherwise, conservatively merge.
1856 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
1857 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
1858 return IntRange::join(L, R);
1859 }
1860
1861 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
1862 switch (BO->getOpcode()) {
1863
1864 // Boolean-valued operations are single-bit and positive.
1865 case BinaryOperator::LAnd:
1866 case BinaryOperator::LOr:
1867 case BinaryOperator::LT:
1868 case BinaryOperator::GT:
1869 case BinaryOperator::LE:
1870 case BinaryOperator::GE:
1871 case BinaryOperator::EQ:
1872 case BinaryOperator::NE:
1873 return IntRange::forBoolType();
1874
John McCallc0cd21d2010-02-23 19:22:29 +00001875 // The type of these compound assignments is the type of the LHS,
1876 // so the RHS is not necessarily an integer.
1877 case BinaryOperator::MulAssign:
1878 case BinaryOperator::DivAssign:
1879 case BinaryOperator::RemAssign:
1880 case BinaryOperator::AddAssign:
1881 case BinaryOperator::SubAssign:
1882 return IntRange::forType(C, E->getType());
1883
John McCallf2370c92010-01-06 05:24:50 +00001884 // Operations with opaque sources are black-listed.
1885 case BinaryOperator::PtrMemD:
1886 case BinaryOperator::PtrMemI:
1887 return IntRange::forType(C, E->getType());
1888
John McCall60fad452010-01-06 22:07:33 +00001889 // Bitwise-and uses the *infinum* of the two source ranges.
1890 case BinaryOperator::And:
John McCallc0cd21d2010-02-23 19:22:29 +00001891 case BinaryOperator::AndAssign:
John McCall60fad452010-01-06 22:07:33 +00001892 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
1893 GetExprRange(C, BO->getRHS(), MaxWidth));
1894
John McCallf2370c92010-01-06 05:24:50 +00001895 // Left shift gets black-listed based on a judgement call.
1896 case BinaryOperator::Shl:
John McCallc0cd21d2010-02-23 19:22:29 +00001897 case BinaryOperator::ShlAssign:
John McCallf2370c92010-01-06 05:24:50 +00001898 return IntRange::forType(C, E->getType());
1899
John McCall60fad452010-01-06 22:07:33 +00001900 // Right shift by a constant can narrow its left argument.
John McCallc0cd21d2010-02-23 19:22:29 +00001901 case BinaryOperator::Shr:
1902 case BinaryOperator::ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00001903 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
1904
1905 // If the shift amount is a positive constant, drop the width by
1906 // that much.
1907 llvm::APSInt shift;
1908 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
1909 shift.isNonNegative()) {
1910 unsigned zext = shift.getZExtValue();
1911 if (zext >= L.Width)
1912 L.Width = (L.NonNegative ? 0 : 1);
1913 else
1914 L.Width -= zext;
1915 }
1916
1917 return L;
1918 }
1919
1920 // Comma acts as its right operand.
John McCallf2370c92010-01-06 05:24:50 +00001921 case BinaryOperator::Comma:
1922 return GetExprRange(C, BO->getRHS(), MaxWidth);
1923
John McCall60fad452010-01-06 22:07:33 +00001924 // Black-list pointer subtractions.
John McCallf2370c92010-01-06 05:24:50 +00001925 case BinaryOperator::Sub:
1926 if (BO->getLHS()->getType()->isPointerType())
1927 return IntRange::forType(C, E->getType());
1928 // fallthrough
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001929
John McCallf2370c92010-01-06 05:24:50 +00001930 default:
1931 break;
1932 }
1933
1934 // Treat every other operator as if it were closed on the
1935 // narrowest type that encompasses both operands.
1936 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
1937 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
1938 return IntRange::join(L, R);
1939 }
1940
1941 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1942 switch (UO->getOpcode()) {
1943 // Boolean-valued operations are white-listed.
1944 case UnaryOperator::LNot:
1945 return IntRange::forBoolType();
1946
1947 // Operations with opaque sources are black-listed.
1948 case UnaryOperator::Deref:
1949 case UnaryOperator::AddrOf: // should be impossible
1950 case UnaryOperator::OffsetOf:
1951 return IntRange::forType(C, E->getType());
1952
1953 default:
1954 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
1955 }
1956 }
1957
1958 FieldDecl *BitField = E->getBitField();
1959 if (BitField) {
1960 llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C);
1961 unsigned BitWidth = BitWidthAP.getZExtValue();
1962
1963 return IntRange(BitWidth, BitField->getType()->isUnsignedIntegerType());
1964 }
1965
1966 return IntRange::forType(C, E->getType());
1967}
John McCall51313c32010-01-04 23:31:57 +00001968
1969/// Checks whether the given value, which currently has the given
1970/// source semantics, has the same value when coerced through the
1971/// target semantics.
John McCallf2370c92010-01-06 05:24:50 +00001972bool IsSameFloatAfterCast(const llvm::APFloat &value,
1973 const llvm::fltSemantics &Src,
1974 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00001975 llvm::APFloat truncated = value;
1976
1977 bool ignored;
1978 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
1979 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
1980
1981 return truncated.bitwiseIsEqual(value);
1982}
1983
1984/// Checks whether the given value, which currently has the given
1985/// source semantics, has the same value when coerced through the
1986/// target semantics.
1987///
1988/// The value might be a vector of floats (or a complex number).
John McCallf2370c92010-01-06 05:24:50 +00001989bool IsSameFloatAfterCast(const APValue &value,
1990 const llvm::fltSemantics &Src,
1991 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00001992 if (value.isFloat())
1993 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
1994
1995 if (value.isVector()) {
1996 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
1997 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
1998 return false;
1999 return true;
2000 }
2001
2002 assert(value.isComplexFloat());
2003 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
2004 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
2005}
2006
John McCallf2370c92010-01-06 05:24:50 +00002007} // end anonymous namespace
John McCall51313c32010-01-04 23:31:57 +00002008
John McCallba26e582010-01-04 23:21:16 +00002009/// \brief Implements -Wsign-compare.
2010///
2011/// \param lex the left-hand expression
2012/// \param rex the right-hand expression
2013/// \param OpLoc the location of the joining operator
2014/// \param Equality whether this is an "equality-like" join, which
2015/// suppresses the warning in some cases
2016void Sema::CheckSignCompare(Expr *lex, Expr *rex, SourceLocation OpLoc,
2017 const PartialDiagnostic &PD, bool Equality) {
2018 // Don't warn if we're in an unevaluated context.
2019 if (ExprEvalContexts.back().Context == Unevaluated)
2020 return;
2021
John McCallf2370c92010-01-06 05:24:50 +00002022 // If either expression is value-dependent, don't warn. We'll get another
2023 // chance at instantiation time.
2024 if (lex->isValueDependent() || rex->isValueDependent())
2025 return;
2026
John McCallba26e582010-01-04 23:21:16 +00002027 QualType lt = lex->getType(), rt = rex->getType();
2028
2029 // Only warn if both operands are integral.
2030 if (!lt->isIntegerType() || !rt->isIntegerType())
2031 return;
2032
John McCallf2370c92010-01-06 05:24:50 +00002033 // In C, the width of a bitfield determines its type, and the
2034 // declared type only contributes the signedness. This duplicates
2035 // the work that will later be done by UsualUnaryConversions.
2036 // Eventually, this check will be reorganized in a way that avoids
2037 // this duplication.
2038 if (!getLangOptions().CPlusPlus) {
2039 QualType tmp;
2040 tmp = Context.isPromotableBitField(lex);
2041 if (!tmp.isNull()) lt = tmp;
2042 tmp = Context.isPromotableBitField(rex);
2043 if (!tmp.isNull()) rt = tmp;
2044 }
John McCallba26e582010-01-04 23:21:16 +00002045
2046 // The rule is that the signed operand becomes unsigned, so isolate the
2047 // signed operand.
John McCallf2370c92010-01-06 05:24:50 +00002048 Expr *signedOperand = lex, *unsignedOperand = rex;
2049 QualType signedType = lt, unsignedType = rt;
John McCallba26e582010-01-04 23:21:16 +00002050 if (lt->isSignedIntegerType()) {
2051 if (rt->isSignedIntegerType()) return;
John McCallba26e582010-01-04 23:21:16 +00002052 } else {
2053 if (!rt->isSignedIntegerType()) return;
John McCallf2370c92010-01-06 05:24:50 +00002054 std::swap(signedOperand, unsignedOperand);
2055 std::swap(signedType, unsignedType);
John McCallba26e582010-01-04 23:21:16 +00002056 }
2057
John McCallf2370c92010-01-06 05:24:50 +00002058 unsigned unsignedWidth = Context.getIntWidth(unsignedType);
2059 unsigned signedWidth = Context.getIntWidth(signedType);
2060
John McCallba26e582010-01-04 23:21:16 +00002061 // If the unsigned type is strictly smaller than the signed type,
2062 // then (1) the result type will be signed and (2) the unsigned
2063 // value will fit fully within the signed type, and thus the result
2064 // of the comparison will be exact.
John McCallf2370c92010-01-06 05:24:50 +00002065 if (signedWidth > unsignedWidth)
John McCallba26e582010-01-04 23:21:16 +00002066 return;
2067
John McCallf2370c92010-01-06 05:24:50 +00002068 // Otherwise, calculate the effective ranges.
2069 IntRange signedRange = GetExprRange(Context, signedOperand, signedWidth);
2070 IntRange unsignedRange = GetExprRange(Context, unsignedOperand, unsignedWidth);
2071
2072 // We should never be unable to prove that the unsigned operand is
2073 // non-negative.
2074 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
2075
2076 // If the signed operand is non-negative, then the signed->unsigned
2077 // conversion won't change it.
2078 if (signedRange.NonNegative)
John McCallba26e582010-01-04 23:21:16 +00002079 return;
2080
2081 // For (in)equality comparisons, if the unsigned operand is a
2082 // constant which cannot collide with a overflowed signed operand,
2083 // then reinterpreting the signed operand as unsigned will not
2084 // change the result of the comparison.
John McCallf2370c92010-01-06 05:24:50 +00002085 if (Equality && unsignedRange.Width < unsignedWidth)
John McCallba26e582010-01-04 23:21:16 +00002086 return;
2087
2088 Diag(OpLoc, PD)
John McCallf2370c92010-01-06 05:24:50 +00002089 << lt << rt << lex->getSourceRange() << rex->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00002090}
2091
John McCall51313c32010-01-04 23:31:57 +00002092/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
2093static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, unsigned diag) {
2094 S.Diag(E->getExprLoc(), diag) << E->getType() << T << E->getSourceRange();
2095}
2096
2097/// Implements -Wconversion.
2098void Sema::CheckImplicitConversion(Expr *E, QualType T) {
2099 // Don't diagnose in unevaluated contexts.
2100 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
2101 return;
2102
2103 // Don't diagnose for value-dependent expressions.
2104 if (E->isValueDependent())
2105 return;
2106
2107 const Type *Source = Context.getCanonicalType(E->getType()).getTypePtr();
2108 const Type *Target = Context.getCanonicalType(T).getTypePtr();
2109
2110 // Never diagnose implicit casts to bool.
2111 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
2112 return;
2113
2114 // Strip vector types.
2115 if (isa<VectorType>(Source)) {
2116 if (!isa<VectorType>(Target))
2117 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_vector_scalar);
2118
2119 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
2120 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
2121 }
2122
2123 // Strip complex types.
2124 if (isa<ComplexType>(Source)) {
2125 if (!isa<ComplexType>(Target))
2126 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_complex_scalar);
2127
2128 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
2129 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
2130 }
2131
2132 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
2133 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
2134
2135 // If the source is floating point...
2136 if (SourceBT && SourceBT->isFloatingPoint()) {
2137 // ...and the target is floating point...
2138 if (TargetBT && TargetBT->isFloatingPoint()) {
2139 // ...then warn if we're dropping FP rank.
2140
2141 // Builtin FP kinds are ordered by increasing FP rank.
2142 if (SourceBT->getKind() > TargetBT->getKind()) {
2143 // Don't warn about float constants that are precisely
2144 // representable in the target type.
2145 Expr::EvalResult result;
2146 if (E->Evaluate(result, Context)) {
2147 // Value might be a float, a float vector, or a float complex.
2148 if (IsSameFloatAfterCast(result.Val,
2149 Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
2150 Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
2151 return;
2152 }
2153
2154 DiagnoseImpCast(*this, E, T, diag::warn_impcast_float_precision);
2155 }
2156 return;
2157 }
2158
2159 // If the target is integral, always warn.
2160 if ((TargetBT && TargetBT->isInteger()))
2161 // TODO: don't warn for integer values?
2162 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_float_integer);
2163
2164 return;
2165 }
2166
John McCallf2370c92010-01-06 05:24:50 +00002167 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00002168 return;
2169
John McCallf2370c92010-01-06 05:24:50 +00002170 IntRange SourceRange = GetExprRange(Context, E, Context.getIntWidth(E->getType()));
2171 IntRange TargetRange = IntRange::forCanonicalType(Context, Target);
John McCall51313c32010-01-04 23:31:57 +00002172
John McCallf2370c92010-01-06 05:24:50 +00002173 // FIXME: also signed<->unsigned?
2174
2175 if (SourceRange.Width > TargetRange.Width) {
John McCall51313c32010-01-04 23:31:57 +00002176 // People want to build with -Wshorten-64-to-32 and not -Wconversion
2177 // and by god we'll let them.
John McCallf2370c92010-01-06 05:24:50 +00002178 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCall51313c32010-01-04 23:31:57 +00002179 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_integer_64_32);
2180 return DiagnoseImpCast(*this, E, T, diag::warn_impcast_integer_precision);
2181 }
2182
2183 return;
2184}
2185
Mike Stumpe5fba702010-01-21 19:44:04 +00002186
Mike Stumpf8c49212010-01-21 03:59:47 +00002187
Mike Stump4a415672010-01-21 23:49:01 +00002188namespace {
Ted Kremenek72919a32010-02-23 05:59:20 +00002189class UnreachableCodeHandler : public reachable_code::Callback {
2190 Sema &S;
2191public:
2192 UnreachableCodeHandler(Sema *s) : S(*s) {}
2193
2194 void HandleUnreachable(SourceLocation L, SourceRange R1, SourceRange R2) {
2195 S.Diag(L, diag::warn_unreachable) << R1 << R2;
2196 }
2197};
Mike Stump4a415672010-01-21 23:49:01 +00002198}
2199
Mike Stumpf8c49212010-01-21 03:59:47 +00002200/// CheckUnreachable - Check for unreachable code.
2201void Sema::CheckUnreachable(AnalysisContext &AC) {
Mike Stumpf8c49212010-01-21 03:59:47 +00002202 // We avoid checking when there are errors, as the CFG won't faithfully match
2203 // the user's code.
Ted Kremenekf067d8e2010-02-23 01:39:04 +00002204 if (getDiagnostics().hasErrorOccurred() ||
2205 Diags.getDiagnosticLevel(diag::warn_unreachable) == Diagnostic::Ignored)
Mike Stumpf8c49212010-01-21 03:59:47 +00002206 return;
2207
Ted Kremenek72919a32010-02-23 05:59:20 +00002208 UnreachableCodeHandler UC(this);
2209 reachable_code::FindUnreachableCode(AC, UC);
Mike Stumpf8c49212010-01-21 03:59:47 +00002210}
2211
2212/// CheckFallThrough - Check that we don't fall off the end of a
2213/// Statement that should return a value.
2214///
2215/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
2216/// MaybeFallThrough iff we might or might not fall off the end,
2217/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
2218/// return. We assume NeverFallThrough iff we never fall off the end of the
2219/// statement but we may return. We assume that functions not marked noreturn
2220/// will return.
2221Sema::ControlFlowKind Sema::CheckFallThrough(AnalysisContext &AC) {
2222 CFG *cfg = AC.getCFG();
2223 if (cfg == 0)
2224 // FIXME: This should be NeverFallThrough
2225 return NeverFallThroughOrReturn;
2226
Mike Stump4c45aa12010-01-21 15:20:48 +00002227 // The CFG leaves in dead things, and we don't want the dead code paths to
Mike Stumpf8c49212010-01-21 03:59:47 +00002228 // confuse us, so we mark all live things first.
2229 std::queue<CFGBlock*> workq;
2230 llvm::BitVector live(cfg->getNumBlockIDs());
Ted Kremenek72919a32010-02-23 05:59:20 +00002231 unsigned count = reachable_code::ScanReachableFromBlock(cfg->getEntry(),
2232 live);
Mike Stump4c45aa12010-01-21 15:20:48 +00002233
2234 bool AddEHEdges = AC.getAddEHEdges();
2235 if (!AddEHEdges && count != cfg->getNumBlockIDs())
2236 // When there are things remaining dead, and we didn't add EH edges
2237 // from CallExprs to the catch clauses, we have to go back and
2238 // mark them as live.
2239 for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
2240 CFGBlock &b = **I;
2241 if (!live[b.getBlockID()]) {
2242 if (b.pred_begin() == b.pred_end()) {
2243 if (b.getTerminator() && isa<CXXTryStmt>(b.getTerminator()))
2244 // When not adding EH edges from calls, catch clauses
2245 // can otherwise seem dead. Avoid noting them as dead.
Ted Kremenek72919a32010-02-23 05:59:20 +00002246 count += reachable_code::ScanReachableFromBlock(b, live);
Mike Stump4c45aa12010-01-21 15:20:48 +00002247 continue;
2248 }
2249 }
2250 }
Mike Stumpf8c49212010-01-21 03:59:47 +00002251
2252 // Now we know what is live, we check the live precessors of the exit block
2253 // and look for fall through paths, being careful to ignore normal returns,
2254 // and exceptional paths.
2255 bool HasLiveReturn = false;
2256 bool HasFakeEdge = false;
2257 bool HasPlainEdge = false;
2258 bool HasAbnormalEdge = false;
2259 for (CFGBlock::pred_iterator I=cfg->getExit().pred_begin(),
2260 E = cfg->getExit().pred_end();
2261 I != E;
2262 ++I) {
2263 CFGBlock& B = **I;
2264 if (!live[B.getBlockID()])
2265 continue;
2266 if (B.size() == 0) {
Mike Stump4c45aa12010-01-21 15:20:48 +00002267 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
2268 HasAbnormalEdge = true;
2269 continue;
2270 }
2271
Mike Stumpf8c49212010-01-21 03:59:47 +00002272 // A labeled empty statement, or the entry block...
2273 HasPlainEdge = true;
2274 continue;
2275 }
2276 Stmt *S = B[B.size()-1];
2277 if (isa<ReturnStmt>(S)) {
2278 HasLiveReturn = true;
2279 continue;
2280 }
2281 if (isa<ObjCAtThrowStmt>(S)) {
2282 HasFakeEdge = true;
2283 continue;
2284 }
2285 if (isa<CXXThrowExpr>(S)) {
2286 HasFakeEdge = true;
2287 continue;
2288 }
2289 if (const AsmStmt *AS = dyn_cast<AsmStmt>(S)) {
2290 if (AS->isMSAsm()) {
2291 HasFakeEdge = true;
2292 HasLiveReturn = true;
2293 continue;
2294 }
2295 }
2296 if (isa<CXXTryStmt>(S)) {
2297 HasAbnormalEdge = true;
2298 continue;
2299 }
2300
2301 bool NoReturnEdge = false;
2302 if (CallExpr *C = dyn_cast<CallExpr>(S)) {
2303 if (B.succ_begin()[0] != &cfg->getExit()) {
2304 HasAbnormalEdge = true;
2305 continue;
2306 }
2307 Expr *CEE = C->getCallee()->IgnoreParenCasts();
2308 if (CEE->getType().getNoReturnAttr()) {
2309 NoReturnEdge = true;
2310 HasFakeEdge = true;
2311 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CEE)) {
2312 ValueDecl *VD = DRE->getDecl();
2313 if (VD->hasAttr<NoReturnAttr>()) {
2314 NoReturnEdge = true;
2315 HasFakeEdge = true;
2316 }
2317 }
2318 }
2319 // FIXME: Add noreturn message sends.
2320 if (NoReturnEdge == false)
2321 HasPlainEdge = true;
2322 }
2323 if (!HasPlainEdge) {
2324 if (HasLiveReturn)
2325 return NeverFallThrough;
2326 return NeverFallThroughOrReturn;
2327 }
2328 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
2329 return MaybeFallThrough;
2330 // This says AlwaysFallThrough for calls to functions that are not marked
2331 // noreturn, that don't return. If people would like this warning to be more
2332 // accurate, such functions should be marked as noreturn.
2333 return AlwaysFallThrough;
2334}
2335
2336/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
2337/// function that should return a value. Check that we don't fall off the end
2338/// of a noreturn function. We assume that functions and blocks not marked
2339/// noreturn will return.
2340void Sema::CheckFallThroughForFunctionDef(Decl *D, Stmt *Body,
2341 AnalysisContext &AC) {
2342 // FIXME: Would be nice if we had a better way to control cascading errors,
2343 // but for now, avoid them. The problem is that when Parse sees:
2344 // int foo() { return a; }
2345 // The return is eaten and the Sema code sees just:
2346 // int foo() { }
2347 // which this code would then warn about.
2348 if (getDiagnostics().hasErrorOccurred())
2349 return;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002350
Mike Stumpf8c49212010-01-21 03:59:47 +00002351 bool ReturnsVoid = false;
2352 bool HasNoReturn = false;
Ted Kremenek1e025f22010-02-23 01:19:11 +00002353
Mike Stumpf8c49212010-01-21 03:59:47 +00002354 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Anders Carlsson4855a522010-02-06 05:31:15 +00002355 // For function templates, class templates and member function templates
2356 // we'll do the analysis at instantiation time.
2357 if (FD->isDependentContext())
Mike Stumpf8c49212010-01-21 03:59:47 +00002358 return;
Anders Carlsson4855a522010-02-06 05:31:15 +00002359
Ted Kremenek1e025f22010-02-23 01:19:11 +00002360 ReturnsVoid = FD->getResultType()->isVoidType();
2361 HasNoReturn = FD->hasAttr<NoReturnAttr>() ||
2362 FD->getType()->getAs<FunctionType>()->getNoReturnAttr();
2363
Mike Stumpf8c49212010-01-21 03:59:47 +00002364 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Ted Kremenek1e025f22010-02-23 01:19:11 +00002365 ReturnsVoid = MD->getResultType()->isVoidType();
2366 HasNoReturn = MD->hasAttr<NoReturnAttr>();
Mike Stumpf8c49212010-01-21 03:59:47 +00002367 }
2368
2369 // Short circuit for compilation speed.
2370 if ((Diags.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function)
2371 == Diagnostic::Ignored || ReturnsVoid)
2372 && (Diags.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr)
2373 == Diagnostic::Ignored || !HasNoReturn)
2374 && (Diags.getDiagnosticLevel(diag::warn_suggest_noreturn_block)
2375 == Diagnostic::Ignored || !ReturnsVoid))
2376 return;
2377 // FIXME: Function try block
2378 if (CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
2379 switch (CheckFallThrough(AC)) {
2380 case MaybeFallThrough:
2381 if (HasNoReturn)
2382 Diag(Compound->getRBracLoc(), diag::warn_falloff_noreturn_function);
2383 else if (!ReturnsVoid)
2384 Diag(Compound->getRBracLoc(),diag::warn_maybe_falloff_nonvoid_function);
2385 break;
2386 case AlwaysFallThrough:
2387 if (HasNoReturn)
2388 Diag(Compound->getRBracLoc(), diag::warn_falloff_noreturn_function);
2389 else if (!ReturnsVoid)
2390 Diag(Compound->getRBracLoc(), diag::warn_falloff_nonvoid_function);
2391 break;
2392 case NeverFallThroughOrReturn:
2393 if (ReturnsVoid && !HasNoReturn)
2394 Diag(Compound->getLBracLoc(), diag::warn_suggest_noreturn_function);
2395 break;
2396 case NeverFallThrough:
2397 break;
2398 }
2399 }
2400}
2401
2402/// CheckFallThroughForBlock - Check that we don't fall off the end of a block
2403/// that should return a value. Check that we don't fall off the end of a
2404/// noreturn block. We assume that functions and blocks not marked noreturn
2405/// will return.
2406void Sema::CheckFallThroughForBlock(QualType BlockTy, Stmt *Body,
2407 AnalysisContext &AC) {
2408 // FIXME: Would be nice if we had a better way to control cascading errors,
2409 // but for now, avoid them. The problem is that when Parse sees:
2410 // int foo() { return a; }
2411 // The return is eaten and the Sema code sees just:
2412 // int foo() { }
2413 // which this code would then warn about.
2414 if (getDiagnostics().hasErrorOccurred())
2415 return;
2416 bool ReturnsVoid = false;
2417 bool HasNoReturn = false;
2418 if (const FunctionType *FT =BlockTy->getPointeeType()->getAs<FunctionType>()){
2419 if (FT->getResultType()->isVoidType())
2420 ReturnsVoid = true;
2421 if (FT->getNoReturnAttr())
2422 HasNoReturn = true;
2423 }
2424
2425 // Short circuit for compilation speed.
2426 if (ReturnsVoid
2427 && !HasNoReturn
2428 && (Diags.getDiagnosticLevel(diag::warn_suggest_noreturn_block)
2429 == Diagnostic::Ignored || !ReturnsVoid))
2430 return;
2431 // FIXME: Funtion try block
2432 if (CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
2433 switch (CheckFallThrough(AC)) {
2434 case MaybeFallThrough:
2435 if (HasNoReturn)
2436 Diag(Compound->getRBracLoc(), diag::err_noreturn_block_has_return_expr);
2437 else if (!ReturnsVoid)
2438 Diag(Compound->getRBracLoc(), diag::err_maybe_falloff_nonvoid_block);
2439 break;
2440 case AlwaysFallThrough:
2441 if (HasNoReturn)
2442 Diag(Compound->getRBracLoc(), diag::err_noreturn_block_has_return_expr);
2443 else if (!ReturnsVoid)
2444 Diag(Compound->getRBracLoc(), diag::err_falloff_nonvoid_block);
2445 break;
2446 case NeverFallThroughOrReturn:
2447 if (ReturnsVoid)
2448 Diag(Compound->getLBracLoc(), diag::warn_suggest_noreturn_block);
2449 break;
2450 case NeverFallThrough:
2451 break;
2452 }
2453 }
2454}
2455
2456/// CheckParmsForFunctionDef - Check that the parameters of the given
2457/// function are appropriate for the definition of a function. This
2458/// takes care of any checks that cannot be performed on the
2459/// declaration itself, e.g., that the types of each of the function
2460/// parameters are complete.
2461bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
2462 bool HasInvalidParm = false;
2463 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2464 ParmVarDecl *Param = FD->getParamDecl(p);
2465
2466 // C99 6.7.5.3p4: the parameters in a parameter type list in a
2467 // function declarator that is part of a function definition of
2468 // that function shall not have incomplete type.
2469 //
2470 // This is also C++ [dcl.fct]p6.
2471 if (!Param->isInvalidDecl() &&
2472 RequireCompleteType(Param->getLocation(), Param->getType(),
2473 diag::err_typecheck_decl_incomplete_type)) {
2474 Param->setInvalidDecl();
2475 HasInvalidParm = true;
2476 }
2477
2478 // C99 6.9.1p5: If the declarator includes a parameter type list, the
2479 // declaration of each parameter shall include an identifier.
2480 if (Param->getIdentifier() == 0 &&
2481 !Param->isImplicit() &&
2482 !getLangOptions().CPlusPlus)
2483 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00002484
2485 // C99 6.7.5.3p12:
2486 // If the function declarator is not part of a definition of that
2487 // function, parameters may have incomplete type and may use the [*]
2488 // notation in their sequences of declarator specifiers to specify
2489 // variable length array types.
2490 QualType PType = Param->getOriginalType();
2491 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
2492 if (AT->getSizeModifier() == ArrayType::Star) {
2493 // FIXME: This diagnosic should point the the '[*]' if source-location
2494 // information is added for it.
2495 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
2496 }
2497 }
John McCall4f9506a2010-02-02 08:45:54 +00002498
John McCall68c6c9a2010-02-02 09:10:11 +00002499 if (getLangOptions().CPlusPlus)
2500 if (const RecordType *RT = Param->getType()->getAs<RecordType>())
2501 FinalizeVarWithDestructor(Param, RT);
Mike Stumpf8c49212010-01-21 03:59:47 +00002502 }
2503
2504 return HasInvalidParm;
2505}