blob: d3332f7b56094c04b36e7f33747a5858b42f3f87 [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
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Sema.h"
John McCall2d887082010-08-25 22:03:47 +000016#include "clang/Sema/SemaInternal.h"
John McCall781472f2010-08-25 08:40:02 +000017#include "clang/Sema/ScopeInfo.h"
Ted Kremenek826a3452010-07-16 02:11:22 +000018#include "clang/Analysis/Analyses/FormatString.h"
Chris Lattner59907c42007-08-10 20:18:51 +000019#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000020#include "clang/AST/CharUnits.h"
John McCall384aff82010-08-25 07:42:41 +000021#include "clang/AST/DeclCXX.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"
John McCallf85e1932011-06-15 23:02:42 +000025#include "clang/AST/EvaluatedExprVisitor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000026#include "clang/AST/DeclObjC.h"
27#include "clang/AST/StmtCXX.h"
28#include "clang/AST/StmtObjC.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"
Tom Care3bfc5f42010-06-09 04:11:11 +000032#include "llvm/Support/raw_ostream.h"
Eric Christopher691ebc32010-04-17 02:26:23 +000033#include "clang/Basic/TargetBuiltins.h"
Nate Begeman26a31422010-06-08 02:47:44 +000034#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian7da71022010-09-07 19:38:13 +000035#include "clang/Basic/ConvertUTF.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000036#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000037using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000038using namespace sema;
Chris Lattner59907c42007-08-10 20:18:51 +000039
Chris Lattner60800082009-02-18 17:49:48 +000040SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
41 unsigned ByteNo) const {
Chris Lattner08f92e32010-11-17 07:37:15 +000042 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
43 PP.getLangOptions(), PP.getTargetInfo());
Chris Lattner60800082009-02-18 17:49:48 +000044}
Chris Lattner08f92e32010-11-17 07:37:15 +000045
Chris Lattner60800082009-02-18 17:49:48 +000046
Ryan Flynn4403a5e2009-08-06 03:00:50 +000047/// CheckablePrintfAttr - does a function call have a "printf" attribute
48/// and arguments that merit checking?
49bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) {
50 if (Format->getType() == "printf") return true;
51 if (Format->getType() == "printf0") {
52 // printf0 allows null "format" string; if so don't check format/args
53 unsigned format_idx = Format->getFormatIdx() - 1;
Sebastian Redl4a2614e2009-11-17 18:02:24 +000054 // Does the index refer to the implicit object argument?
55 if (isa<CXXMemberCallExpr>(TheCall)) {
56 if (format_idx == 0)
57 return false;
58 --format_idx;
59 }
Ryan Flynn4403a5e2009-08-06 03:00:50 +000060 if (format_idx < TheCall->getNumArgs()) {
61 Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts();
Ted Kremenekefaff192010-02-27 01:41:03 +000062 if (!Format->isNullPointerConstant(Context,
63 Expr::NPC_ValueDependentIsNull))
Ryan Flynn4403a5e2009-08-06 03:00:50 +000064 return true;
65 }
66 }
67 return false;
68}
Chris Lattner60800082009-02-18 17:49:48 +000069
John McCall8e10f3b2011-02-26 05:39:39 +000070/// Checks that a call expression's argument count is the desired number.
71/// This is useful when doing custom type-checking. Returns true on error.
72static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
73 unsigned argCount = call->getNumArgs();
74 if (argCount == desiredArgCount) return false;
75
76 if (argCount < desiredArgCount)
77 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
78 << 0 /*function call*/ << desiredArgCount << argCount
79 << call->getSourceRange();
80
81 // Highlight all the excess arguments.
82 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
83 call->getArg(argCount - 1)->getLocEnd());
84
85 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
86 << 0 /*function call*/ << desiredArgCount << argCount
87 << call->getArg(1)->getSourceRange();
88}
89
John McCall60d7b3a2010-08-24 06:29:42 +000090ExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +000091Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCall60d7b3a2010-08-24 06:29:42 +000092 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +000093
Chris Lattner946928f2010-10-01 23:23:24 +000094 // Find out if any arguments are required to be integer constant expressions.
95 unsigned ICEArguments = 0;
96 ASTContext::GetBuiltinTypeError Error;
97 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
98 if (Error != ASTContext::GE_None)
99 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
100
101 // If any arguments are required to be ICE's, check and diagnose.
102 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
103 // Skip arguments not required to be ICE's.
104 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
105
106 llvm::APSInt Result;
107 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
108 return true;
109 ICEArguments &= ~(1 << ArgNo);
110 }
111
Anders Carlssond406bf02009-08-16 01:56:34 +0000112 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000113 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000114 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000115 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000116 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000117 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000118 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000119 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000120 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000121 if (SemaBuiltinVAStart(TheCall))
122 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000123 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000124 case Builtin::BI__builtin_isgreater:
125 case Builtin::BI__builtin_isgreaterequal:
126 case Builtin::BI__builtin_isless:
127 case Builtin::BI__builtin_islessequal:
128 case Builtin::BI__builtin_islessgreater:
129 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000130 if (SemaBuiltinUnorderedCompare(TheCall))
131 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000132 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000133 case Builtin::BI__builtin_fpclassify:
134 if (SemaBuiltinFPClassification(TheCall, 6))
135 return ExprError();
136 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000137 case Builtin::BI__builtin_isfinite:
138 case Builtin::BI__builtin_isinf:
139 case Builtin::BI__builtin_isinf_sign:
140 case Builtin::BI__builtin_isnan:
141 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000142 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000143 return ExprError();
144 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000145 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000146 return SemaBuiltinShuffleVector(TheCall);
147 // TheCall will be freed by the smart pointer here, but that's fine, since
148 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000149 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000150 if (SemaBuiltinPrefetch(TheCall))
151 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000152 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000153 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000154 if (SemaBuiltinObjectSize(TheCall))
155 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000156 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000157 case Builtin::BI__builtin_longjmp:
158 if (SemaBuiltinLongjmp(TheCall))
159 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000160 break;
John McCall8e10f3b2011-02-26 05:39:39 +0000161
162 case Builtin::BI__builtin_classify_type:
163 if (checkArgCount(*this, TheCall, 1)) return true;
164 TheCall->setType(Context.IntTy);
165 break;
Chris Lattner75c29a02010-10-12 17:47:42 +0000166 case Builtin::BI__builtin_constant_p:
John McCall8e10f3b2011-02-26 05:39:39 +0000167 if (checkArgCount(*this, TheCall, 1)) return true;
168 TheCall->setType(Context.IntTy);
Chris Lattner75c29a02010-10-12 17:47:42 +0000169 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000170 case Builtin::BI__sync_fetch_and_add:
171 case Builtin::BI__sync_fetch_and_sub:
172 case Builtin::BI__sync_fetch_and_or:
173 case Builtin::BI__sync_fetch_and_and:
174 case Builtin::BI__sync_fetch_and_xor:
175 case Builtin::BI__sync_add_and_fetch:
176 case Builtin::BI__sync_sub_and_fetch:
177 case Builtin::BI__sync_and_and_fetch:
178 case Builtin::BI__sync_or_and_fetch:
179 case Builtin::BI__sync_xor_and_fetch:
180 case Builtin::BI__sync_val_compare_and_swap:
181 case Builtin::BI__sync_bool_compare_and_swap:
182 case Builtin::BI__sync_lock_test_and_set:
183 case Builtin::BI__sync_lock_release:
Chris Lattner23aa9c82011-04-09 03:57:26 +0000184 case Builtin::BI__sync_swap:
Chandler Carruthd2014572010-07-09 18:59:35 +0000185 return SemaBuiltinAtomicOverloaded(move(TheCallResult));
Nate Begeman26a31422010-06-08 02:47:44 +0000186 }
187
188 // Since the target specific builtins for each arch overlap, only check those
189 // of the arch we are compiling for.
190 if (BuiltinID >= Builtin::FirstTSBuiltin) {
191 switch (Context.Target.getTriple().getArch()) {
192 case llvm::Triple::arm:
193 case llvm::Triple::thumb:
194 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
195 return ExprError();
196 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000197 default:
198 break;
199 }
200 }
201
202 return move(TheCallResult);
203}
204
Nate Begeman61eecf52010-06-14 05:21:25 +0000205// Get the valid immediate range for the specified NEON type code.
206static unsigned RFT(unsigned t, bool shift = false) {
207 bool quad = t & 0x10;
208
209 switch (t & 0x7) {
210 case 0: // i8
Nate Begemand69ec162010-06-17 02:26:59 +0000211 return shift ? 7 : (8 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000212 case 1: // i16
Nate Begemand69ec162010-06-17 02:26:59 +0000213 return shift ? 15 : (4 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000214 case 2: // i32
Nate Begemand69ec162010-06-17 02:26:59 +0000215 return shift ? 31 : (2 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000216 case 3: // i64
Nate Begemand69ec162010-06-17 02:26:59 +0000217 return shift ? 63 : (1 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000218 case 4: // f32
219 assert(!shift && "cannot shift float types!");
Nate Begemand69ec162010-06-17 02:26:59 +0000220 return (2 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000221 case 5: // poly8
Bob Wilson42499f92010-12-10 19:45:06 +0000222 return shift ? 7 : (8 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000223 case 6: // poly16
Bob Wilson42499f92010-12-10 19:45:06 +0000224 return shift ? 15 : (4 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000225 case 7: // float16
226 assert(!shift && "cannot shift float types!");
Nate Begemand69ec162010-06-17 02:26:59 +0000227 return (4 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000228 }
229 return 0;
230}
231
Nate Begeman26a31422010-06-08 02:47:44 +0000232bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000233 llvm::APSInt Result;
234
Nate Begeman0d15c532010-06-13 04:47:52 +0000235 unsigned mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000236 unsigned TV = 0;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000237 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000238#define GET_NEON_OVERLOAD_CHECK
239#include "clang/Basic/arm_neon.inc"
240#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000241 }
242
Nate Begeman0d15c532010-06-13 04:47:52 +0000243 // For NEON intrinsics which are overloaded on vector element type, validate
244 // the immediate which specifies which variant to emit.
245 if (mask) {
246 unsigned ArgNo = TheCall->getNumArgs()-1;
247 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
248 return true;
249
Nate Begeman61eecf52010-06-14 05:21:25 +0000250 TV = Result.getLimitedValue(32);
251 if ((TV > 31) || (mask & (1 << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000252 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
253 << TheCall->getArg(ArgNo)->getSourceRange();
254 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000255
Nate Begeman0d15c532010-06-13 04:47:52 +0000256 // For NEON intrinsics which take an immediate value as part of the
257 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000258 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000259 switch (BuiltinID) {
260 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000261 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
262 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000263 case ARM::BI__builtin_arm_vcvtr_f:
264 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000265#define GET_NEON_IMMEDIATE_CHECK
266#include "clang/Basic/arm_neon.inc"
267#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000268 };
269
Nate Begeman61eecf52010-06-14 05:21:25 +0000270 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000271 if (SemaBuiltinConstantArg(TheCall, i, Result))
272 return true;
273
Nate Begeman61eecf52010-06-14 05:21:25 +0000274 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000275 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000276 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000277 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000278 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000279
Nate Begeman99c40bb2010-08-03 21:32:34 +0000280 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000281 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000282}
Daniel Dunbarde454282008-10-02 18:44:07 +0000283
Anders Carlssond406bf02009-08-16 01:56:34 +0000284/// CheckFunctionCall - Check a direct function call for various correctness
285/// and safety properties not strictly enforced by the C type system.
286bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
287 // Get the IdentifierInfo* for the called function.
288 IdentifierInfo *FnInfo = FDecl->getIdentifier();
289
290 // None of the checks below are needed for functions that don't have
291 // simple names (e.g., C++ conversion functions).
292 if (!FnInfo)
293 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000294
Daniel Dunbarde454282008-10-02 18:44:07 +0000295 // FIXME: This mechanism should be abstracted to be less fragile and
296 // more efficient. For example, just map function ids to custom
297 // handlers.
298
Ted Kremenekc82faca2010-09-09 04:33:05 +0000299 // Printf and scanf checking.
300 for (specific_attr_iterator<FormatAttr>
301 i = FDecl->specific_attr_begin<FormatAttr>(),
302 e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
303
304 const FormatAttr *Format = *i;
Ted Kremenek826a3452010-07-16 02:11:22 +0000305 const bool b = Format->getType() == "scanf";
306 if (b || CheckablePrintfAttr(Format, TheCall)) {
Ted Kremenek3d692df2009-02-27 17:58:43 +0000307 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek826a3452010-07-16 02:11:22 +0000308 CheckPrintfScanfArguments(TheCall, HasVAListArg,
309 Format->getFormatIdx() - 1,
310 HasVAListArg ? 0 : Format->getFirstArg() - 1,
311 !b);
Douglas Gregor3c385e52009-02-14 18:57:46 +0000312 }
Chris Lattner59907c42007-08-10 20:18:51 +0000313 }
Mike Stump1eb44332009-09-09 15:08:12 +0000314
Ted Kremenekc82faca2010-09-09 04:33:05 +0000315 for (specific_attr_iterator<NonNullAttr>
316 i = FDecl->specific_attr_begin<NonNullAttr>(),
317 e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +0000318 CheckNonNullArguments(*i, TheCall->getArgs(),
319 TheCall->getCallee()->getLocStart());
Ted Kremenekc82faca2010-09-09 04:33:05 +0000320 }
Sebastian Redl0eb23302009-01-19 00:08:26 +0000321
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +0000322 // Memset/memcpy/memmove/memcmp handling
Douglas Gregor707a23e2011-06-16 17:56:04 +0000323 int CMF = -1;
324 switch (FDecl->getBuiltinID()) {
325 case Builtin::BI__builtin_memset:
326 case Builtin::BI__builtin___memset_chk:
327 case Builtin::BImemset:
328 CMF = CMF_Memset;
329 break;
330
331 case Builtin::BI__builtin_memcpy:
332 case Builtin::BI__builtin___memcpy_chk:
333 case Builtin::BImemcpy:
334 CMF = CMF_Memcpy;
335 break;
336
337 case Builtin::BI__builtin_memmove:
338 case Builtin::BI__builtin___memmove_chk:
339 case Builtin::BImemmove:
340 CMF = CMF_Memmove;
341 break;
342
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +0000343 case Builtin::BI__builtin_memcmp:
344 CMF = CMF_Memcmp;
345 break;
346
Douglas Gregor707a23e2011-06-16 17:56:04 +0000347 default:
348 if (FDecl->getLinkage() == ExternalLinkage &&
349 (!getLangOptions().CPlusPlus || FDecl->isExternC())) {
350 if (FnInfo->isStr("memset"))
351 CMF = CMF_Memset;
352 else if (FnInfo->isStr("memcpy"))
353 CMF = CMF_Memcpy;
354 else if (FnInfo->isStr("memmove"))
355 CMF = CMF_Memmove;
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +0000356 else if (FnInfo->isStr("memcmp"))
357 CMF = CMF_Memcmp;
Douglas Gregor707a23e2011-06-16 17:56:04 +0000358 }
359 break;
Douglas Gregor06bc9eb2011-05-03 20:37:33 +0000360 }
Douglas Gregor707a23e2011-06-16 17:56:04 +0000361
362 if (CMF != -1)
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +0000363 CheckMemaccessArguments(TheCall, CheckedMemoryFunction(CMF), FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000364
Anders Carlssond406bf02009-08-16 01:56:34 +0000365 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000366}
367
Anders Carlssond406bf02009-08-16 01:56:34 +0000368bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000369 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000370 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000371 if (!Format)
Anders Carlssond406bf02009-08-16 01:56:34 +0000372 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000373
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000374 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
375 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000376 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000377
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000378 QualType Ty = V->getType();
379 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000380 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000381
Ted Kremenek826a3452010-07-16 02:11:22 +0000382 const bool b = Format->getType() == "scanf";
383 if (!b && !CheckablePrintfAttr(Format, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +0000384 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000385
Anders Carlssond406bf02009-08-16 01:56:34 +0000386 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek826a3452010-07-16 02:11:22 +0000387 CheckPrintfScanfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
388 HasVAListArg ? 0 : Format->getFirstArg() - 1, !b);
Anders Carlssond406bf02009-08-16 01:56:34 +0000389
390 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000391}
392
Chris Lattner5caa3702009-05-08 06:58:22 +0000393/// SemaBuiltinAtomicOverloaded - We have a call to a function like
394/// __sync_fetch_and_add, which is an overloaded function based on the pointer
395/// type of its first argument. The main ActOnCallExpr routines have already
396/// promoted the types of arguments because all of these calls are prototyped as
397/// void(...).
398///
399/// This function goes through and does final semantic checking for these
400/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000401ExprResult
402Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000403 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000404 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
405 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
406
407 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000408 if (TheCall->getNumArgs() < 1) {
409 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
410 << 0 << 1 << TheCall->getNumArgs()
411 << TheCall->getCallee()->getSourceRange();
412 return ExprError();
413 }
Mike Stump1eb44332009-09-09 15:08:12 +0000414
Chris Lattner5caa3702009-05-08 06:58:22 +0000415 // Inspect the first argument of the atomic builtin. This should always be
416 // a pointer type, whose element is an integral scalar or pointer type.
417 // Because it is a pointer type, we don't have to worry about any implicit
418 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000419 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000420 Expr *FirstArg = TheCall->getArg(0);
John McCallf85e1932011-06-15 23:02:42 +0000421 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
422 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000423 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
424 << FirstArg->getType() << FirstArg->getSourceRange();
425 return ExprError();
426 }
Mike Stump1eb44332009-09-09 15:08:12 +0000427
John McCallf85e1932011-06-15 23:02:42 +0000428 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000429 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000430 !ValType->isBlockPointerType()) {
431 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
432 << FirstArg->getType() << FirstArg->getSourceRange();
433 return ExprError();
434 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000435
John McCallf85e1932011-06-15 23:02:42 +0000436 switch (ValType.getObjCLifetime()) {
437 case Qualifiers::OCL_None:
438 case Qualifiers::OCL_ExplicitNone:
439 // okay
440 break;
441
442 case Qualifiers::OCL_Weak:
443 case Qualifiers::OCL_Strong:
444 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000445 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +0000446 << ValType << FirstArg->getSourceRange();
447 return ExprError();
448 }
449
Chandler Carruth8d13d222010-07-18 20:54:12 +0000450 // The majority of builtins return a value, but a few have special return
451 // types, so allow them to override appropriately below.
452 QualType ResultType = ValType;
453
Chris Lattner5caa3702009-05-08 06:58:22 +0000454 // We need to figure out which concrete builtin this maps onto. For example,
455 // __sync_fetch_and_add with a 2 byte object turns into
456 // __sync_fetch_and_add_2.
457#define BUILTIN_ROW(x) \
458 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
459 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000460
Chris Lattner5caa3702009-05-08 06:58:22 +0000461 static const unsigned BuiltinIndices[][5] = {
462 BUILTIN_ROW(__sync_fetch_and_add),
463 BUILTIN_ROW(__sync_fetch_and_sub),
464 BUILTIN_ROW(__sync_fetch_and_or),
465 BUILTIN_ROW(__sync_fetch_and_and),
466 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +0000467
Chris Lattner5caa3702009-05-08 06:58:22 +0000468 BUILTIN_ROW(__sync_add_and_fetch),
469 BUILTIN_ROW(__sync_sub_and_fetch),
470 BUILTIN_ROW(__sync_and_and_fetch),
471 BUILTIN_ROW(__sync_or_and_fetch),
472 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000473
Chris Lattner5caa3702009-05-08 06:58:22 +0000474 BUILTIN_ROW(__sync_val_compare_and_swap),
475 BUILTIN_ROW(__sync_bool_compare_and_swap),
476 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +0000477 BUILTIN_ROW(__sync_lock_release),
478 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +0000479 };
Mike Stump1eb44332009-09-09 15:08:12 +0000480#undef BUILTIN_ROW
481
Chris Lattner5caa3702009-05-08 06:58:22 +0000482 // Determine the index of the size.
483 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000484 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000485 case 1: SizeIndex = 0; break;
486 case 2: SizeIndex = 1; break;
487 case 4: SizeIndex = 2; break;
488 case 8: SizeIndex = 3; break;
489 case 16: SizeIndex = 4; break;
490 default:
Chandler Carruthd2014572010-07-09 18:59:35 +0000491 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
492 << FirstArg->getType() << FirstArg->getSourceRange();
493 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +0000494 }
Mike Stump1eb44332009-09-09 15:08:12 +0000495
Chris Lattner5caa3702009-05-08 06:58:22 +0000496 // Each of these builtins has one pointer argument, followed by some number of
497 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
498 // that we ignore. Find out which row of BuiltinIndices to read from as well
499 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000500 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000501 unsigned BuiltinIndex, NumFixed = 1;
502 switch (BuiltinID) {
503 default: assert(0 && "Unknown overloaded atomic builtin!");
504 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
505 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
506 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
507 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
508 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000509
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000510 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
511 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
512 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
513 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 8; break;
514 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000515
Chris Lattner5caa3702009-05-08 06:58:22 +0000516 case Builtin::BI__sync_val_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000517 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +0000518 NumFixed = 2;
519 break;
520 case Builtin::BI__sync_bool_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000521 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +0000522 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000523 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000524 break;
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000525 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000526 case Builtin::BI__sync_lock_release:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000527 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000528 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000529 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000530 break;
Chris Lattner23aa9c82011-04-09 03:57:26 +0000531 case Builtin::BI__sync_swap: BuiltinIndex = 14; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000532 }
Mike Stump1eb44332009-09-09 15:08:12 +0000533
Chris Lattner5caa3702009-05-08 06:58:22 +0000534 // Now that we know how many fixed arguments we expect, first check that we
535 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +0000536 if (TheCall->getNumArgs() < 1+NumFixed) {
537 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
538 << 0 << 1+NumFixed << TheCall->getNumArgs()
539 << TheCall->getCallee()->getSourceRange();
540 return ExprError();
541 }
Mike Stump1eb44332009-09-09 15:08:12 +0000542
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000543 // Get the decl for the concrete builtin from this, we can tell what the
544 // concrete integer type we should convert to is.
545 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
546 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
547 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +0000548 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000549 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
550 TUScope, false, DRE->getLocStart()));
Chandler Carruthd2014572010-07-09 18:59:35 +0000551
John McCallf871d0c2010-08-07 06:22:56 +0000552 // The first argument --- the pointer --- has a fixed type; we
553 // deduce the types of the rest of the arguments accordingly. Walk
554 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +0000555 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +0000556 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +0000557
Chris Lattner5caa3702009-05-08 06:58:22 +0000558 // If the argument is an implicit cast, then there was a promotion due to
559 // "...", just remove it now.
John Wiegley429bb272011-04-08 18:41:53 +0000560 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg.get())) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000561 Arg = ICE->getSubExpr();
562 ICE->setSubExpr(0);
John Wiegley429bb272011-04-08 18:41:53 +0000563 TheCall->setArg(i+1, Arg.get());
Chris Lattner5caa3702009-05-08 06:58:22 +0000564 }
Mike Stump1eb44332009-09-09 15:08:12 +0000565
Chris Lattner5caa3702009-05-08 06:58:22 +0000566 // GCC does an implicit conversion to the pointer or integer ValType. This
567 // can fail in some cases (1i -> int**), check for this error case now.
John McCalldaa8e4e2010-11-15 09:13:47 +0000568 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +0000569 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +0000570 CXXCastPath BasePath;
John McCallf85e1932011-06-15 23:02:42 +0000571 Arg = CheckCastTypes(Arg.get()->getLocStart(), Arg.get()->getSourceRange(),
572 ValType, Arg.take(), Kind, VK, BasePath);
John Wiegley429bb272011-04-08 18:41:53 +0000573 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +0000574 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000575
Chris Lattner5caa3702009-05-08 06:58:22 +0000576 // Okay, we have something that *can* be converted to the right type. Check
577 // to see if there is a potentially weird extension going on here. This can
578 // happen when you do an atomic operation on something like an char* and
579 // pass in 42. The 42 gets converted to char. This is even more strange
580 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +0000581 // FIXME: Do this check.
John Wiegley429bb272011-04-08 18:41:53 +0000582 Arg = ImpCastExprToType(Arg.take(), ValType, Kind, VK, &BasePath);
583 TheCall->setArg(i+1, Arg.get());
Chris Lattner5caa3702009-05-08 06:58:22 +0000584 }
Mike Stump1eb44332009-09-09 15:08:12 +0000585
Chris Lattner5caa3702009-05-08 06:58:22 +0000586 // Switch the DeclRefExpr to refer to the new decl.
587 DRE->setDecl(NewBuiltinDecl);
588 DRE->setType(NewBuiltinDecl->getType());
Mike Stump1eb44332009-09-09 15:08:12 +0000589
Chris Lattner5caa3702009-05-08 06:58:22 +0000590 // Set the callee in the CallExpr.
591 // FIXME: This leaks the original parens and implicit casts.
John Wiegley429bb272011-04-08 18:41:53 +0000592 ExprResult PromotedCall = UsualUnaryConversions(DRE);
593 if (PromotedCall.isInvalid())
594 return ExprError();
595 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +0000596
Chandler Carruthdb4325b2010-07-18 07:23:17 +0000597 // Change the result type of the call to match the original value type. This
598 // is arbitrary, but the codegen for these builtins ins design to handle it
599 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +0000600 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +0000601
602 return move(TheCallResult);
Chris Lattner5caa3702009-05-08 06:58:22 +0000603}
604
605
Chris Lattner69039812009-02-18 06:01:06 +0000606/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000607/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +0000608/// Note: It might also make sense to do the UTF-16 conversion here (would
609/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +0000610bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000611 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000612 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
613
Douglas Gregor5cee1192011-07-27 05:40:30 +0000614 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000615 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
616 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000617 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000618 }
Mike Stump1eb44332009-09-09 15:08:12 +0000619
Fariborz Jahanian7da71022010-09-07 19:38:13 +0000620 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000621 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +0000622 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000623 SmallVector<UTF16, 128> ToBuf(NumBytes);
Fariborz Jahanian7da71022010-09-07 19:38:13 +0000624 const UTF8 *FromPtr = (UTF8 *)String.data();
625 UTF16 *ToPtr = &ToBuf[0];
626
627 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
628 &ToPtr, ToPtr + NumBytes,
629 strictConversion);
630 // Check for conversion failure.
631 if (Result != conversionOK)
632 Diag(Arg->getLocStart(),
633 diag::warn_cfstring_truncated) << Arg->getSourceRange();
634 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000635 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000636}
637
Chris Lattnerc27c6652007-12-20 00:05:45 +0000638/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
639/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000640bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
641 Expr *Fn = TheCall->getCallee();
642 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000643 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000644 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000645 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
646 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +0000647 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000648 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000649 return true;
650 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000651
652 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +0000653 return Diag(TheCall->getLocEnd(),
654 diag::err_typecheck_call_too_few_args_at_least)
655 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000656 }
657
Chris Lattnerc27c6652007-12-20 00:05:45 +0000658 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000659 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +0000660 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000661 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +0000662 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +0000663 else if (FunctionDecl *FD = getCurFunctionDecl())
664 isVariadic = FD->isVariadic();
665 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000666 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +0000667
Chris Lattnerc27c6652007-12-20 00:05:45 +0000668 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000669 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
670 return true;
671 }
Mike Stump1eb44332009-09-09 15:08:12 +0000672
Chris Lattner30ce3442007-12-19 23:59:04 +0000673 // Verify that the second argument to the builtin is the last argument of the
674 // current function or method.
675 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000676 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +0000677
Anders Carlsson88cf2262008-02-11 04:20:54 +0000678 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
679 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000680 // FIXME: This isn't correct for methods (results in bogus warning).
681 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000682 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000683 if (CurBlock)
684 LastArg = *(CurBlock->TheDecl->param_end()-1);
685 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +0000686 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000687 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000688 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000689 SecondArgIsLastNamedArgument = PV == LastArg;
690 }
691 }
Mike Stump1eb44332009-09-09 15:08:12 +0000692
Chris Lattner30ce3442007-12-19 23:59:04 +0000693 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +0000694 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000695 diag::warn_second_parameter_of_va_start_not_last_named_argument);
696 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000697}
Chris Lattner30ce3442007-12-19 23:59:04 +0000698
Chris Lattner1b9a0792007-12-20 00:26:33 +0000699/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
700/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000701bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
702 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000703 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000704 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000705 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +0000706 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000707 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000708 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000709 << SourceRange(TheCall->getArg(2)->getLocStart(),
710 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000711
John Wiegley429bb272011-04-08 18:41:53 +0000712 ExprResult OrigArg0 = TheCall->getArg(0);
713 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000714
Chris Lattner1b9a0792007-12-20 00:26:33 +0000715 // Do standard promotions between the two arguments, returning their common
716 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000717 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +0000718 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
719 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +0000720
721 // Make sure any conversions are pushed back into the call; this is
722 // type safe since unordered compare builtins are declared as "_Bool
723 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +0000724 TheCall->setArg(0, OrigArg0.get());
725 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +0000726
John Wiegley429bb272011-04-08 18:41:53 +0000727 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +0000728 return false;
729
Chris Lattner1b9a0792007-12-20 00:26:33 +0000730 // If the common type isn't a real floating type, then the arguments were
731 // invalid for this operation.
732 if (!Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +0000733 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000734 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +0000735 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
736 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000737
Chris Lattner1b9a0792007-12-20 00:26:33 +0000738 return false;
739}
740
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000741/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
742/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000743/// to check everything. We expect the last argument to be a floating point
744/// value.
745bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
746 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +0000747 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000748 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000749 if (TheCall->getNumArgs() > NumArgs)
750 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000751 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000752 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000753 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000754 (*(TheCall->arg_end()-1))->getLocEnd());
755
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000756 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +0000757
Eli Friedman9ac6f622009-08-31 20:06:00 +0000758 if (OrigArg->isTypeDependent())
759 return false;
760
Chris Lattner81368fb2010-05-06 05:50:07 +0000761 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +0000762 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000763 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000764 diag::err_typecheck_call_invalid_unary_fp)
765 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000766
Chris Lattner81368fb2010-05-06 05:50:07 +0000767 // If this is an implicit conversion from float -> double, remove it.
768 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
769 Expr *CastArg = Cast->getSubExpr();
770 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
771 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
772 "promotion from float to double is the only expected cast here");
773 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +0000774 TheCall->setArg(NumArgs-1, CastArg);
775 OrigArg = CastArg;
776 }
777 }
778
Eli Friedman9ac6f622009-08-31 20:06:00 +0000779 return false;
780}
781
Eli Friedmand38617c2008-05-14 19:38:39 +0000782/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
783// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +0000784ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000785 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000786 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +0000787 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +0000788 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +0000789 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000790
Nate Begeman37b6a572010-06-08 00:16:34 +0000791 // Determine which of the following types of shufflevector we're checking:
792 // 1) unary, vector mask: (lhs, mask)
793 // 2) binary, vector mask: (lhs, rhs, mask)
794 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
795 QualType resType = TheCall->getArg(0)->getType();
796 unsigned numElements = 0;
797
Douglas Gregorcde01732009-05-19 22:10:17 +0000798 if (!TheCall->getArg(0)->isTypeDependent() &&
799 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000800 QualType LHSType = TheCall->getArg(0)->getType();
801 QualType RHSType = TheCall->getArg(1)->getType();
802
803 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000804 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000805 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000806 TheCall->getArg(1)->getLocEnd());
807 return ExprError();
808 }
Nate Begeman37b6a572010-06-08 00:16:34 +0000809
810 numElements = LHSType->getAs<VectorType>()->getNumElements();
811 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +0000812
Nate Begeman37b6a572010-06-08 00:16:34 +0000813 // Check to see if we have a call with 2 vector arguments, the unary shuffle
814 // with mask. If so, verify that RHS is an integer vector type with the
815 // same number of elts as lhs.
816 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +0000817 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +0000818 RHSType->getAs<VectorType>()->getNumElements() != numElements)
819 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
820 << SourceRange(TheCall->getArg(1)->getLocStart(),
821 TheCall->getArg(1)->getLocEnd());
822 numResElements = numElements;
823 }
824 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000825 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000826 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000827 TheCall->getArg(1)->getLocEnd());
828 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +0000829 } else if (numElements != numResElements) {
830 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +0000831 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +0000832 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +0000833 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000834 }
835
836 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000837 if (TheCall->getArg(i)->isTypeDependent() ||
838 TheCall->getArg(i)->isValueDependent())
839 continue;
840
Nate Begeman37b6a572010-06-08 00:16:34 +0000841 llvm::APSInt Result(32);
842 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
843 return ExprError(Diag(TheCall->getLocStart(),
844 diag::err_shufflevector_nonconstant_argument)
845 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000846
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000847 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000848 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000849 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000850 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000851 }
852
Chris Lattner5f9e2722011-07-23 10:55:15 +0000853 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +0000854
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000855 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000856 exprs.push_back(TheCall->getArg(i));
857 TheCall->setArg(i, 0);
858 }
859
Nate Begemana88dc302009-08-12 02:10:25 +0000860 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begeman37b6a572010-06-08 00:16:34 +0000861 exprs.size(), resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000862 TheCall->getCallee()->getLocStart(),
863 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000864}
Chris Lattner30ce3442007-12-19 23:59:04 +0000865
Daniel Dunbar4493f792008-07-21 22:59:13 +0000866/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
867// This is declared to take (const void*, ...) and can take two
868// optional constant int args.
869bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000870 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000871
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000872 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +0000873 return Diag(TheCall->getLocEnd(),
874 diag::err_typecheck_call_too_many_args_at_most)
875 << 0 /*function call*/ << 3 << NumArgs
876 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000877
878 // Argument 0 is checked for us and the remaining arguments must be
879 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000880 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000881 Expr *Arg = TheCall->getArg(i);
Eric Christopher691ebc32010-04-17 02:26:23 +0000882
Eli Friedman9aef7262009-12-04 00:30:06 +0000883 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +0000884 if (SemaBuiltinConstantArg(TheCall, i, Result))
885 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000886
Daniel Dunbar4493f792008-07-21 22:59:13 +0000887 // FIXME: gcc issues a warning and rewrites these to 0. These
888 // seems especially odd for the third argument since the default
889 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000890 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +0000891 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000892 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000893 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000894 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +0000895 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000896 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000897 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000898 }
899 }
900
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000901 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000902}
903
Eric Christopher691ebc32010-04-17 02:26:23 +0000904/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
905/// TheCall is a constant expression.
906bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
907 llvm::APSInt &Result) {
908 Expr *Arg = TheCall->getArg(ArgNum);
909 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
910 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
911
912 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
913
914 if (!Arg->isIntegerConstantExpr(Result, Context))
915 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +0000916 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +0000917
Chris Lattner21fb98e2009-09-23 06:06:36 +0000918 return false;
919}
920
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000921/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
922/// int type). This simply type checks that type is one of the defined
923/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000924// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000925bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +0000926 llvm::APSInt Result;
927
928 // Check constant-ness first.
929 if (SemaBuiltinConstantArg(TheCall, 1, Result))
930 return true;
931
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000932 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000933 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000934 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
935 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000936 }
937
938 return false;
939}
940
Eli Friedman586d6a82009-05-03 06:04:26 +0000941/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +0000942/// This checks that val is a constant 1.
943bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
944 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +0000945 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +0000946
Eric Christopher691ebc32010-04-17 02:26:23 +0000947 // TODO: This is less than ideal. Overload this to take a value.
948 if (SemaBuiltinConstantArg(TheCall, 1, Result))
949 return true;
950
951 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +0000952 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
953 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
954
955 return false;
956}
957
Ted Kremenekb43e8ad2011-02-24 23:03:04 +0000958// Handle i > 1 ? "x" : "y", recursively.
Ted Kremenek082d9362009-03-20 21:35:28 +0000959bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
960 bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +0000961 unsigned format_idx, unsigned firstDataArg,
962 bool isPrintf) {
Ted Kremenek4fe64412010-09-09 03:51:39 +0000963 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +0000964 if (E->isTypeDependent() || E->isValueDependent())
965 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000966
Peter Collingbournef111d932011-04-15 00:35:48 +0000967 E = E->IgnoreParens();
968
Ted Kremenekd30ef872009-01-12 23:09:09 +0000969 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +0000970 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +0000971 case Stmt::ConditionalOperatorClass: {
John McCall56ca35d2011-02-17 10:25:35 +0000972 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
Ted Kremenek826a3452010-07-16 02:11:22 +0000973 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg,
974 format_idx, firstDataArg, isPrintf)
John McCall56ca35d2011-02-17 10:25:35 +0000975 && SemaCheckStringLiteral(C->getFalseExpr(), TheCall, HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +0000976 format_idx, firstDataArg, isPrintf);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000977 }
978
Ted Kremenek95355bb2010-09-09 03:51:42 +0000979 case Stmt::IntegerLiteralClass:
980 // Technically -Wformat-nonliteral does not warn about this case.
981 // The behavior of printf and friends in this case is implementation
982 // dependent. Ideally if the format string cannot be null then
983 // it should have a 'nonnull' attribute in the function prototype.
984 return true;
985
Ted Kremenekd30ef872009-01-12 23:09:09 +0000986 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +0000987 E = cast<ImplicitCastExpr>(E)->getSubExpr();
988 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000989 }
990
John McCall56ca35d2011-02-17 10:25:35 +0000991 case Stmt::OpaqueValueExprClass:
992 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
993 E = src;
994 goto tryAgain;
995 }
996 return false;
997
Ted Kremenekb43e8ad2011-02-24 23:03:04 +0000998 case Stmt::PredefinedExprClass:
999 // While __func__, etc., are technically not string literals, they
1000 // cannot contain format specifiers and thus are not a security
1001 // liability.
1002 return true;
1003
Ted Kremenek082d9362009-03-20 21:35:28 +00001004 case Stmt::DeclRefExprClass: {
1005 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001006
Ted Kremenek082d9362009-03-20 21:35:28 +00001007 // As an exception, do not flag errors for variables binding to
1008 // const string literals.
1009 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1010 bool isConstant = false;
1011 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001012
Ted Kremenek082d9362009-03-20 21:35:28 +00001013 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1014 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001015 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001016 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001017 PT->getPointeeType().isConstant(Context);
1018 }
Mike Stump1eb44332009-09-09 15:08:12 +00001019
Ted Kremenek082d9362009-03-20 21:35:28 +00001020 if (isConstant) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001021 if (const Expr *Init = VD->getAnyInitializer())
Ted Kremenek082d9362009-03-20 21:35:28 +00001022 return SemaCheckStringLiteral(Init, TheCall,
Ted Kremenek826a3452010-07-16 02:11:22 +00001023 HasVAListArg, format_idx, firstDataArg,
1024 isPrintf);
Ted Kremenek082d9362009-03-20 21:35:28 +00001025 }
Mike Stump1eb44332009-09-09 15:08:12 +00001026
Anders Carlssond966a552009-06-28 19:55:58 +00001027 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1028 // special check to see if the format string is a function parameter
1029 // of the function calling the printf function. If the function
1030 // has an attribute indicating it is a printf-like function, then we
1031 // should suppress warnings concerning non-literals being used in a call
1032 // to a vprintf function. For example:
1033 //
1034 // void
1035 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1036 // va_list ap;
1037 // va_start(ap, fmt);
1038 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1039 // ...
1040 //
1041 //
1042 // FIXME: We don't have full attribute support yet, so just check to see
1043 // if the argument is a DeclRefExpr that references a parameter. We'll
1044 // add proper support for checking the attribute later.
1045 if (HasVAListArg)
1046 if (isa<ParmVarDecl>(VD))
1047 return true;
Ted Kremenek082d9362009-03-20 21:35:28 +00001048 }
Mike Stump1eb44332009-09-09 15:08:12 +00001049
Ted Kremenek082d9362009-03-20 21:35:28 +00001050 return false;
1051 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001052
Anders Carlsson8f031b32009-06-27 04:05:33 +00001053 case Stmt::CallExprClass: {
1054 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001055 if (const ImplicitCastExpr *ICE
Anders Carlsson8f031b32009-06-27 04:05:33 +00001056 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
1057 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
1058 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001059 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001060 unsigned ArgIndex = FA->getFormatIdx();
1061 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001062
1063 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001064 format_idx, firstDataArg, isPrintf);
Anders Carlsson8f031b32009-06-27 04:05:33 +00001065 }
1066 }
1067 }
1068 }
Mike Stump1eb44332009-09-09 15:08:12 +00001069
Anders Carlsson8f031b32009-06-27 04:05:33 +00001070 return false;
1071 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001072 case Stmt::ObjCStringLiteralClass:
1073 case Stmt::StringLiteralClass: {
1074 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001075
Ted Kremenek082d9362009-03-20 21:35:28 +00001076 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001077 StrE = ObjCFExpr->getString();
1078 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001079 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001080
Ted Kremenekd30ef872009-01-12 23:09:09 +00001081 if (StrE) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001082 CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx,
1083 firstDataArg, isPrintf);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001084 return true;
1085 }
Mike Stump1eb44332009-09-09 15:08:12 +00001086
Ted Kremenekd30ef872009-01-12 23:09:09 +00001087 return false;
1088 }
Mike Stump1eb44332009-09-09 15:08:12 +00001089
Ted Kremenek082d9362009-03-20 21:35:28 +00001090 default:
1091 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001092 }
1093}
1094
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001095void
Mike Stump1eb44332009-09-09 15:08:12 +00001096Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001097 const Expr * const *ExprArgs,
1098 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001099 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1100 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001101 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001102 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001103 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001104 Expr::NPC_ValueDependentIsNotNull))
Nick Lewycky909a70d2011-03-25 01:44:32 +00001105 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001106 }
1107}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001108
Ted Kremenek826a3452010-07-16 02:11:22 +00001109/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1110/// functions) for correct use of format strings.
Chris Lattner59907c42007-08-10 20:18:51 +00001111void
Ted Kremenek826a3452010-07-16 02:11:22 +00001112Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
1113 unsigned format_idx, unsigned firstDataArg,
1114 bool isPrintf) {
1115
Ted Kremenek082d9362009-03-20 21:35:28 +00001116 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +00001117
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001118 // The way the format attribute works in GCC, the implicit this argument
1119 // of member functions is counted. However, it doesn't appear in our own
1120 // lists, so decrement format_idx in that case.
1121 if (isa<CXXMemberCallExpr>(TheCall)) {
Chandler Carruth9263a302010-11-16 08:49:43 +00001122 const CXXMethodDecl *method_decl =
1123 dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl());
1124 if (method_decl && method_decl->isInstance()) {
1125 // Catch a format attribute mistakenly referring to the object argument.
1126 if (format_idx == 0)
1127 return;
1128 --format_idx;
1129 if(firstDataArg != 0)
1130 --firstDataArg;
1131 }
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001132 }
1133
Ted Kremenek826a3452010-07-16 02:11:22 +00001134 // CHECK: printf/scanf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +00001135 if (format_idx >= TheCall->getNumArgs()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001136 Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001137 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001138 return;
1139 }
Mike Stump1eb44332009-09-09 15:08:12 +00001140
Ted Kremenek082d9362009-03-20 21:35:28 +00001141 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001142
Chris Lattner59907c42007-08-10 20:18:51 +00001143 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001144 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001145 // Dynamically generated format strings are difficult to
1146 // automatically vet at compile time. Requiring that format strings
1147 // are string literals: (1) permits the checking of format strings by
1148 // the compiler and thereby (2) can practically remove the source of
1149 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001150
Mike Stump1eb44332009-09-09 15:08:12 +00001151 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001152 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001153 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001154 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001155 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
Ted Kremenek826a3452010-07-16 02:11:22 +00001156 firstDataArg, isPrintf))
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001157 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001158
Chris Lattner655f1412009-04-29 04:59:47 +00001159 // If there are no arguments specified, warn with -Wformat-security, otherwise
1160 // warn only with -Wformat-nonliteral.
1161 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump1eb44332009-09-09 15:08:12 +00001162 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001163 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001164 << OrigFormatExpr->getSourceRange();
1165 else
Mike Stump1eb44332009-09-09 15:08:12 +00001166 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001167 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001168 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001169}
Ted Kremenek71895b92007-08-14 17:39:48 +00001170
Ted Kremeneke0e53132010-01-28 23:39:18 +00001171namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001172class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1173protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001174 Sema &S;
1175 const StringLiteral *FExpr;
1176 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001177 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001178 const unsigned NumDataArgs;
1179 const bool IsObjCLiteral;
1180 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001181 const bool HasVAListArg;
1182 const CallExpr *TheCall;
1183 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001184 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001185 bool usesPositionalArgs;
1186 bool atFirstArg;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001187public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001188 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001189 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001190 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001191 const char *beg, bool hasVAListArg,
1192 const CallExpr *theCall, unsigned formatIdx)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001193 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek6ee76532010-03-25 03:59:12 +00001194 FirstDataArg(firstDataArg),
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001195 NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001196 IsObjCLiteral(isObjCLiteral), Beg(beg),
1197 HasVAListArg(hasVAListArg),
Ted Kremenekefaff192010-02-27 01:41:03 +00001198 TheCall(theCall), FormatIdx(formatIdx),
1199 usesPositionalArgs(false), atFirstArg(true) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001200 CoveredArgs.resize(numDataArgs);
1201 CoveredArgs.reset();
1202 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001203
Ted Kremenek07d161f2010-01-29 01:50:07 +00001204 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001205
Ted Kremenek826a3452010-07-16 02:11:22 +00001206 void HandleIncompleteSpecifier(const char *startSpecifier,
1207 unsigned specifierLen);
1208
Ted Kremenekefaff192010-02-27 01:41:03 +00001209 virtual void HandleInvalidPosition(const char *startSpecifier,
1210 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001211 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001212
1213 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1214
Ted Kremeneke0e53132010-01-28 23:39:18 +00001215 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001216
Ted Kremenek826a3452010-07-16 02:11:22 +00001217protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001218 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1219 const char *startSpec,
1220 unsigned specifierLen,
1221 const char *csStart, unsigned csLen);
1222
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001223 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00001224 CharSourceRange getSpecifierRange(const char *startSpecifier,
1225 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001226 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001227
Ted Kremenek0d277352010-01-29 01:06:55 +00001228 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00001229
1230 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1231 const analyze_format_string::ConversionSpecifier &CS,
1232 const char *startSpecifier, unsigned specifierLen,
1233 unsigned argIndex);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001234};
1235}
1236
Ted Kremenek826a3452010-07-16 02:11:22 +00001237SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001238 return OrigFormatExpr->getSourceRange();
1239}
1240
Ted Kremenek826a3452010-07-16 02:11:22 +00001241CharSourceRange CheckFormatHandler::
1242getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001243 SourceLocation Start = getLocationOfByte(startSpecifier);
1244 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1245
1246 // Advance the end SourceLocation by one due to half-open ranges.
1247 End = End.getFileLocWithOffset(1);
1248
1249 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001250}
1251
Ted Kremenek826a3452010-07-16 02:11:22 +00001252SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001253 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001254}
1255
Ted Kremenek826a3452010-07-16 02:11:22 +00001256void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1257 unsigned specifierLen){
Ted Kremenek808015a2010-01-29 03:16:21 +00001258 SourceLocation Loc = getLocationOfByte(startSpecifier);
1259 S.Diag(Loc, diag::warn_printf_incomplete_specifier)
Ted Kremenek826a3452010-07-16 02:11:22 +00001260 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek808015a2010-01-29 03:16:21 +00001261}
1262
Ted Kremenekefaff192010-02-27 01:41:03 +00001263void
Ted Kremenek826a3452010-07-16 02:11:22 +00001264CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1265 analyze_format_string::PositionContext p) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001266 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek826a3452010-07-16 02:11:22 +00001267 S.Diag(Loc, diag::warn_format_invalid_positional_specifier)
1268 << (unsigned) p << getSpecifierRange(startPos, posLen);
Ted Kremenekefaff192010-02-27 01:41:03 +00001269}
1270
Ted Kremenek826a3452010-07-16 02:11:22 +00001271void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00001272 unsigned posLen) {
1273 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek826a3452010-07-16 02:11:22 +00001274 S.Diag(Loc, diag::warn_format_zero_positional_specifier)
1275 << getSpecifierRange(startPos, posLen);
Ted Kremenekefaff192010-02-27 01:41:03 +00001276}
1277
Ted Kremenek826a3452010-07-16 02:11:22 +00001278void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Ted Kremenek0c069442011-03-15 21:18:48 +00001279 if (!IsObjCLiteral) {
1280 // The presence of a null character is likely an error.
1281 S.Diag(getLocationOfByte(nullCharacter),
1282 diag::warn_printf_format_string_contains_null_char)
1283 << getFormatStringRange();
1284 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001285}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001286
Ted Kremenek826a3452010-07-16 02:11:22 +00001287const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
1288 return TheCall->getArg(FirstDataArg + i);
1289}
1290
1291void CheckFormatHandler::DoneProcessing() {
1292 // Does the number of data arguments exceed the number of
1293 // format conversions in the format string?
1294 if (!HasVAListArg) {
1295 // Find any arguments that weren't covered.
1296 CoveredArgs.flip();
1297 signed notCoveredArg = CoveredArgs.find_first();
1298 if (notCoveredArg >= 0) {
1299 assert((unsigned)notCoveredArg < NumDataArgs);
1300 S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(),
1301 diag::warn_printf_data_arg_not_used)
1302 << getFormatStringRange();
1303 }
1304 }
1305}
1306
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001307bool
1308CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1309 SourceLocation Loc,
1310 const char *startSpec,
1311 unsigned specifierLen,
1312 const char *csStart,
1313 unsigned csLen) {
1314
1315 bool keepGoing = true;
1316 if (argIndex < NumDataArgs) {
1317 // Consider the argument coverered, even though the specifier doesn't
1318 // make sense.
1319 CoveredArgs.set(argIndex);
1320 }
1321 else {
1322 // If argIndex exceeds the number of data arguments we
1323 // don't issue a warning because that is just a cascade of warnings (and
1324 // they may have intended '%%' anyway). We don't want to continue processing
1325 // the format string after this point, however, as we will like just get
1326 // gibberish when trying to match arguments.
1327 keepGoing = false;
1328 }
1329
1330 S.Diag(Loc, diag::warn_format_invalid_conversion)
Chris Lattner5f9e2722011-07-23 10:55:15 +00001331 << StringRef(csStart, csLen)
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001332 << getSpecifierRange(startSpec, specifierLen);
1333
1334 return keepGoing;
1335}
1336
Ted Kremenek666a1972010-07-26 19:45:42 +00001337bool
1338CheckFormatHandler::CheckNumArgs(
1339 const analyze_format_string::FormatSpecifier &FS,
1340 const analyze_format_string::ConversionSpecifier &CS,
1341 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1342
1343 if (argIndex >= NumDataArgs) {
1344 if (FS.usesPositionalArg()) {
1345 S.Diag(getLocationOfByte(CS.getStart()),
1346 diag::warn_printf_positional_arg_exceeds_data_args)
1347 << (argIndex+1) << NumDataArgs
1348 << getSpecifierRange(startSpecifier, specifierLen);
1349 }
1350 else {
1351 S.Diag(getLocationOfByte(CS.getStart()),
1352 diag::warn_printf_insufficient_data_args)
1353 << getSpecifierRange(startSpecifier, specifierLen);
1354 }
1355
1356 return false;
1357 }
1358 return true;
1359}
1360
Ted Kremenek826a3452010-07-16 02:11:22 +00001361//===--- CHECK: Printf format string checking ------------------------------===//
1362
1363namespace {
1364class CheckPrintfHandler : public CheckFormatHandler {
1365public:
1366 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1367 const Expr *origFormatExpr, unsigned firstDataArg,
1368 unsigned numDataArgs, bool isObjCLiteral,
1369 const char *beg, bool hasVAListArg,
1370 const CallExpr *theCall, unsigned formatIdx)
1371 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1372 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1373 theCall, formatIdx) {}
1374
1375
1376 bool HandleInvalidPrintfConversionSpecifier(
1377 const analyze_printf::PrintfSpecifier &FS,
1378 const char *startSpecifier,
1379 unsigned specifierLen);
1380
1381 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1382 const char *startSpecifier,
1383 unsigned specifierLen);
1384
1385 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1386 const char *startSpecifier, unsigned specifierLen);
1387 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1388 const analyze_printf::OptionalAmount &Amt,
1389 unsigned type,
1390 const char *startSpecifier, unsigned specifierLen);
1391 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1392 const analyze_printf::OptionalFlag &flag,
1393 const char *startSpecifier, unsigned specifierLen);
1394 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1395 const analyze_printf::OptionalFlag &ignoredFlag,
1396 const analyze_printf::OptionalFlag &flag,
1397 const char *startSpecifier, unsigned specifierLen);
1398};
1399}
1400
1401bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1402 const analyze_printf::PrintfSpecifier &FS,
1403 const char *startSpecifier,
1404 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001405 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001406 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001407
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001408 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1409 getLocationOfByte(CS.getStart()),
1410 startSpecifier, specifierLen,
1411 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001412}
1413
Ted Kremenek826a3452010-07-16 02:11:22 +00001414bool CheckPrintfHandler::HandleAmount(
1415 const analyze_format_string::OptionalAmount &Amt,
1416 unsigned k, const char *startSpecifier,
1417 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001418
1419 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001420 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001421 unsigned argIndex = Amt.getArgIndex();
1422 if (argIndex >= NumDataArgs) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001423 S.Diag(getLocationOfByte(Amt.getStart()),
1424 diag::warn_printf_asterisk_missing_arg)
Ted Kremenek826a3452010-07-16 02:11:22 +00001425 << k << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek0d277352010-01-29 01:06:55 +00001426 // Don't do any more checking. We will just emit
1427 // spurious errors.
1428 return false;
1429 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001430
Ted Kremenek0d277352010-01-29 01:06:55 +00001431 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00001432 // Although not in conformance with C99, we also allow the argument to be
1433 // an 'unsigned int' as that is a reasonably safe case. GCC also
1434 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001435 CoveredArgs.set(argIndex);
1436 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00001437 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001438
1439 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1440 assert(ATR.isValid());
1441
1442 if (!ATR.matchesType(S.Context, T)) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001443 S.Diag(getLocationOfByte(Amt.getStart()),
1444 diag::warn_printf_asterisk_wrong_type)
1445 << k
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001446 << ATR.getRepresentativeType(S.Context) << T
Ted Kremenek826a3452010-07-16 02:11:22 +00001447 << getSpecifierRange(startSpecifier, specifierLen)
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001448 << Arg->getSourceRange();
Ted Kremenek0d277352010-01-29 01:06:55 +00001449 // Don't do any more checking. We will just emit
1450 // spurious errors.
1451 return false;
1452 }
1453 }
1454 }
1455 return true;
1456}
Ted Kremenek0d277352010-01-29 01:06:55 +00001457
Tom Caree4ee9662010-06-17 19:00:27 +00001458void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00001459 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001460 const analyze_printf::OptionalAmount &Amt,
1461 unsigned type,
1462 const char *startSpecifier,
1463 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001464 const analyze_printf::PrintfConversionSpecifier &CS =
1465 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001466 switch (Amt.getHowSpecified()) {
1467 case analyze_printf::OptionalAmount::Constant:
1468 S.Diag(getLocationOfByte(Amt.getStart()),
1469 diag::warn_printf_nonsensical_optional_amount)
1470 << type
1471 << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001472 << getSpecifierRange(startSpecifier, specifierLen)
1473 << FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
Tom Caree4ee9662010-06-17 19:00:27 +00001474 Amt.getConstantLength()));
1475 break;
1476
1477 default:
1478 S.Diag(getLocationOfByte(Amt.getStart()),
1479 diag::warn_printf_nonsensical_optional_amount)
1480 << type
1481 << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001482 << getSpecifierRange(startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001483 break;
1484 }
1485}
1486
Ted Kremenek826a3452010-07-16 02:11:22 +00001487void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001488 const analyze_printf::OptionalFlag &flag,
1489 const char *startSpecifier,
1490 unsigned specifierLen) {
1491 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001492 const analyze_printf::PrintfConversionSpecifier &CS =
1493 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001494 S.Diag(getLocationOfByte(flag.getPosition()),
1495 diag::warn_printf_nonsensical_flag)
1496 << flag.toString() << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001497 << getSpecifierRange(startSpecifier, specifierLen)
1498 << FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1));
Tom Caree4ee9662010-06-17 19:00:27 +00001499}
1500
1501void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00001502 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001503 const analyze_printf::OptionalFlag &ignoredFlag,
1504 const analyze_printf::OptionalFlag &flag,
1505 const char *startSpecifier,
1506 unsigned specifierLen) {
1507 // Warn about ignored flag with a fixit removal.
1508 S.Diag(getLocationOfByte(ignoredFlag.getPosition()),
1509 diag::warn_printf_ignored_flag)
1510 << ignoredFlag.toString() << flag.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001511 << getSpecifierRange(startSpecifier, specifierLen)
1512 << FixItHint::CreateRemoval(getSpecifierRange(
Tom Caree4ee9662010-06-17 19:00:27 +00001513 ignoredFlag.getPosition(), 1));
1514}
1515
Ted Kremeneke0e53132010-01-28 23:39:18 +00001516bool
Ted Kremenek826a3452010-07-16 02:11:22 +00001517CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001518 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001519 const char *startSpecifier,
1520 unsigned specifierLen) {
1521
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001522 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00001523 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001524 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00001525
Ted Kremenekbaa40062010-07-19 22:01:06 +00001526 if (FS.consumesDataArgument()) {
1527 if (atFirstArg) {
1528 atFirstArg = false;
1529 usesPositionalArgs = FS.usesPositionalArg();
1530 }
1531 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1532 // Cannot mix-and-match positional and non-positional arguments.
1533 S.Diag(getLocationOfByte(CS.getStart()),
1534 diag::warn_format_mix_positional_nonpositional_args)
1535 << getSpecifierRange(startSpecifier, specifierLen);
1536 return false;
1537 }
Ted Kremenek0d277352010-01-29 01:06:55 +00001538 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001539
Ted Kremenekefaff192010-02-27 01:41:03 +00001540 // First check if the field width, precision, and conversion specifier
1541 // have matching data arguments.
1542 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1543 startSpecifier, specifierLen)) {
1544 return false;
1545 }
1546
1547 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1548 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001549 return false;
1550 }
1551
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001552 if (!CS.consumesDataArgument()) {
1553 // FIXME: Technically specifying a precision or field width here
1554 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001555 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001556 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001557
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001558 // Consume the argument.
1559 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00001560 if (argIndex < NumDataArgs) {
1561 // The check to see if the argIndex is valid will come later.
1562 // We set the bit here because we may exit early from this
1563 // function if we encounter some other error.
1564 CoveredArgs.set(argIndex);
1565 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001566
1567 // Check for using an Objective-C specific conversion specifier
1568 // in a non-ObjC literal.
1569 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001570 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
1571 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001572 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001573
Tom Caree4ee9662010-06-17 19:00:27 +00001574 // Check for invalid use of field width
1575 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001576 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00001577 startSpecifier, specifierLen);
1578 }
1579
1580 // Check for invalid use of precision
1581 if (!FS.hasValidPrecision()) {
1582 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
1583 startSpecifier, specifierLen);
1584 }
1585
1586 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00001587 if (!FS.hasValidThousandsGroupingPrefix())
1588 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001589 if (!FS.hasValidLeadingZeros())
1590 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
1591 if (!FS.hasValidPlusPrefix())
1592 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00001593 if (!FS.hasValidSpacePrefix())
1594 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001595 if (!FS.hasValidAlternativeForm())
1596 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
1597 if (!FS.hasValidLeftJustified())
1598 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
1599
1600 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00001601 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
1602 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
1603 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001604 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
1605 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
1606 startSpecifier, specifierLen);
1607
1608 // Check the length modifier is valid with the given conversion specifier.
1609 const LengthModifier &LM = FS.getLengthModifier();
1610 if (!FS.hasValidLengthModifier())
1611 S.Diag(getLocationOfByte(LM.getStart()),
Ted Kremenek649aecf2010-07-20 20:03:43 +00001612 diag::warn_format_nonsensical_length)
Tom Caree4ee9662010-06-17 19:00:27 +00001613 << LM.toString() << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001614 << getSpecifierRange(startSpecifier, specifierLen)
1615 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
Tom Caree4ee9662010-06-17 19:00:27 +00001616 LM.getLength()));
1617
1618 // Are we using '%n'?
Ted Kremenek35d353b2010-07-20 20:04:10 +00001619 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Caree4ee9662010-06-17 19:00:27 +00001620 // Issue a warning about this being a possible security issue.
Ted Kremeneke82d8042010-01-29 01:35:25 +00001621 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
Ted Kremenek826a3452010-07-16 02:11:22 +00001622 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremeneke82d8042010-01-29 01:35:25 +00001623 // Continue checking the other format specifiers.
1624 return true;
1625 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001626
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001627 // The remaining checks depend on the data arguments.
1628 if (HasVAListArg)
1629 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001630
Ted Kremenek666a1972010-07-26 19:45:42 +00001631 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001632 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001633
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001634 // Now type check the data expression that matches the
1635 // format specifier.
1636 const Expr *Ex = getDataArg(argIndex);
1637 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
1638 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
1639 // Check if we didn't match because of an implicit cast from a 'char'
1640 // or 'short' to an 'int'. This is done because printf is a varargs
1641 // function.
1642 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00001643 if (ICE->getType() == S.Context.IntTy) {
1644 // All further checking is done on the subexpression.
1645 Ex = ICE->getSubExpr();
1646 if (ATR.matchesType(S.Context, Ex->getType()))
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001647 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00001648 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001649
1650 // We may be able to offer a FixItHint if it is a supported type.
1651 PrintfSpecifier fixedFS = FS;
1652 bool success = fixedFS.fixType(Ex->getType());
1653
1654 if (success) {
1655 // Get the fix string from the fixed format specifier
1656 llvm::SmallString<128> buf;
1657 llvm::raw_svector_ostream os(buf);
1658 fixedFS.toString(os);
1659
Ted Kremenek9325eaf2010-08-24 22:24:51 +00001660 // FIXME: getRepresentativeType() perhaps should return a string
1661 // instead of a QualType to better handle when the representative
1662 // type is 'wint_t' (which is defined in the system headers).
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001663 S.Diag(getLocationOfByte(CS.getStart()),
1664 diag::warn_printf_conversion_argument_type_mismatch)
1665 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1666 << getSpecifierRange(startSpecifier, specifierLen)
1667 << Ex->getSourceRange()
1668 << FixItHint::CreateReplacement(
1669 getSpecifierRange(startSpecifier, specifierLen),
1670 os.str());
1671 }
1672 else {
1673 S.Diag(getLocationOfByte(CS.getStart()),
1674 diag::warn_printf_conversion_argument_type_mismatch)
1675 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1676 << getSpecifierRange(startSpecifier, specifierLen)
1677 << Ex->getSourceRange();
1678 }
1679 }
1680
Ted Kremeneke0e53132010-01-28 23:39:18 +00001681 return true;
1682}
1683
Ted Kremenek826a3452010-07-16 02:11:22 +00001684//===--- CHECK: Scanf format string checking ------------------------------===//
1685
1686namespace {
1687class CheckScanfHandler : public CheckFormatHandler {
1688public:
1689 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
1690 const Expr *origFormatExpr, unsigned firstDataArg,
1691 unsigned numDataArgs, bool isObjCLiteral,
1692 const char *beg, bool hasVAListArg,
1693 const CallExpr *theCall, unsigned formatIdx)
1694 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1695 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1696 theCall, formatIdx) {}
1697
1698 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
1699 const char *startSpecifier,
1700 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001701
1702 bool HandleInvalidScanfConversionSpecifier(
1703 const analyze_scanf::ScanfSpecifier &FS,
1704 const char *startSpecifier,
1705 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00001706
1707 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00001708};
Ted Kremenek07d161f2010-01-29 01:50:07 +00001709}
Ted Kremeneke0e53132010-01-28 23:39:18 +00001710
Ted Kremenekb7c21012010-07-16 18:28:03 +00001711void CheckScanfHandler::HandleIncompleteScanList(const char *start,
1712 const char *end) {
1713 S.Diag(getLocationOfByte(end), diag::warn_scanf_scanlist_incomplete)
1714 << getSpecifierRange(start, end - start);
1715}
1716
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001717bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
1718 const analyze_scanf::ScanfSpecifier &FS,
1719 const char *startSpecifier,
1720 unsigned specifierLen) {
1721
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001722 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001723 FS.getConversionSpecifier();
1724
1725 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1726 getLocationOfByte(CS.getStart()),
1727 startSpecifier, specifierLen,
1728 CS.getStart(), CS.getLength());
1729}
1730
Ted Kremenek826a3452010-07-16 02:11:22 +00001731bool CheckScanfHandler::HandleScanfSpecifier(
1732 const analyze_scanf::ScanfSpecifier &FS,
1733 const char *startSpecifier,
1734 unsigned specifierLen) {
1735
1736 using namespace analyze_scanf;
1737 using namespace analyze_format_string;
1738
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001739 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001740
Ted Kremenekbaa40062010-07-19 22:01:06 +00001741 // Handle case where '%' and '*' don't consume an argument. These shouldn't
1742 // be used to decide if we are using positional arguments consistently.
1743 if (FS.consumesDataArgument()) {
1744 if (atFirstArg) {
1745 atFirstArg = false;
1746 usesPositionalArgs = FS.usesPositionalArg();
1747 }
1748 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1749 // Cannot mix-and-match positional and non-positional arguments.
1750 S.Diag(getLocationOfByte(CS.getStart()),
1751 diag::warn_format_mix_positional_nonpositional_args)
1752 << getSpecifierRange(startSpecifier, specifierLen);
1753 return false;
1754 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001755 }
1756
1757 // Check if the field with is non-zero.
1758 const OptionalAmount &Amt = FS.getFieldWidth();
1759 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
1760 if (Amt.getConstantAmount() == 0) {
1761 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
1762 Amt.getConstantLength());
1763 S.Diag(getLocationOfByte(Amt.getStart()),
1764 diag::warn_scanf_nonzero_width)
1765 << R << FixItHint::CreateRemoval(R);
1766 }
1767 }
1768
1769 if (!FS.consumesDataArgument()) {
1770 // FIXME: Technically specifying a precision or field width here
1771 // makes no sense. Worth issuing a warning at some point.
1772 return true;
1773 }
1774
1775 // Consume the argument.
1776 unsigned argIndex = FS.getArgIndex();
1777 if (argIndex < NumDataArgs) {
1778 // The check to see if the argIndex is valid will come later.
1779 // We set the bit here because we may exit early from this
1780 // function if we encounter some other error.
1781 CoveredArgs.set(argIndex);
1782 }
1783
Ted Kremenek1e51c202010-07-20 20:04:47 +00001784 // Check the length modifier is valid with the given conversion specifier.
1785 const LengthModifier &LM = FS.getLengthModifier();
1786 if (!FS.hasValidLengthModifier()) {
1787 S.Diag(getLocationOfByte(LM.getStart()),
1788 diag::warn_format_nonsensical_length)
1789 << LM.toString() << CS.toString()
1790 << getSpecifierRange(startSpecifier, specifierLen)
1791 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
1792 LM.getLength()));
1793 }
1794
Ted Kremenek826a3452010-07-16 02:11:22 +00001795 // The remaining checks depend on the data arguments.
1796 if (HasVAListArg)
1797 return true;
1798
Ted Kremenek666a1972010-07-26 19:45:42 +00001799 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00001800 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00001801
1802 // FIXME: Check that the argument type matches the format specifier.
1803
1804 return true;
1805}
1806
1807void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001808 const Expr *OrigFormatExpr,
1809 const CallExpr *TheCall, bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001810 unsigned format_idx, unsigned firstDataArg,
1811 bool isPrintf) {
1812
Ted Kremeneke0e53132010-01-28 23:39:18 +00001813 // CHECK: is the format string a wide literal?
Douglas Gregor5cee1192011-07-27 05:40:30 +00001814 if (!FExpr->isAscii()) {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001815 Diag(FExpr->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001816 diag::warn_format_string_is_wide_literal)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001817 << OrigFormatExpr->getSourceRange();
1818 return;
1819 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001820
Ted Kremeneke0e53132010-01-28 23:39:18 +00001821 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00001822 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001823 const char *Str = StrRef.data();
1824 unsigned StrLen = StrRef.size();
Ted Kremenek826a3452010-07-16 02:11:22 +00001825
Ted Kremeneke0e53132010-01-28 23:39:18 +00001826 // CHECK: empty format string?
Ted Kremeneke0e53132010-01-28 23:39:18 +00001827 if (StrLen == 0) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001828 Diag(FExpr->getLocStart(), diag::warn_empty_format_string)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001829 << OrigFormatExpr->getSourceRange();
1830 return;
1831 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001832
1833 if (isPrintf) {
1834 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1835 TheCall->getNumArgs() - firstDataArg,
1836 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1837 HasVAListArg, TheCall, format_idx);
1838
1839 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen))
1840 H.DoneProcessing();
1841 }
1842 else {
1843 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1844 TheCall->getNumArgs() - firstDataArg,
1845 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1846 HasVAListArg, TheCall, format_idx);
1847
1848 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen))
1849 H.DoneProcessing();
1850 }
Ted Kremenekce7024e2010-01-28 01:18:22 +00001851}
1852
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001853//===--- CHECK: Standard memory functions ---------------------------------===//
1854
Douglas Gregor2a053a32011-05-03 20:05:22 +00001855/// \brief Determine whether the given type is a dynamic class type (e.g.,
1856/// whether it has a vtable).
1857static bool isDynamicClassType(QualType T) {
1858 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
1859 if (CXXRecordDecl *Definition = Record->getDefinition())
1860 if (Definition->isDynamicClass())
1861 return true;
1862
1863 return false;
1864}
1865
Chandler Carrutha72a12f2011-06-21 23:04:20 +00001866/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00001867/// otherwise returns NULL.
1868static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00001869 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00001870 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
1871 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
1872 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00001873
Chandler Carruth000d4282011-06-16 09:09:40 +00001874 return 0;
1875}
1876
Chandler Carrutha72a12f2011-06-21 23:04:20 +00001877/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00001878static QualType getSizeOfArgType(const Expr* E) {
1879 if (const UnaryExprOrTypeTraitExpr *SizeOf =
1880 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
1881 if (SizeOf->getKind() == clang::UETT_SizeOf)
1882 return SizeOf->getTypeOfArgument();
1883
1884 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00001885}
1886
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001887/// \brief Check for dangerous or invalid arguments to memset().
1888///
Chandler Carruth929f0132011-06-03 06:23:57 +00001889/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00001890/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
1891/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001892///
1893/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00001894void Sema::CheckMemaccessArguments(const CallExpr *Call,
1895 CheckedMemoryFunction CMF,
1896 IdentifierInfo *FnName) {
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00001897 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00001898 // we have enough arguments, and if not, abort further checking.
1899 if (Call->getNumArgs() < 3)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00001900 return;
1901
Douglas Gregor707a23e2011-06-16 17:56:04 +00001902 unsigned LastArg = (CMF == CMF_Memset? 1 : 2);
Nico Webere4a1c642011-06-14 16:14:58 +00001903 const Expr *LenExpr = Call->getArg(2)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00001904
1905 // We have special checking when the length is a sizeof expression.
1906 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
1907 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
1908 llvm::FoldingSetNodeID SizeOfArgID;
1909
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00001910 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
1911 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00001912 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001913
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00001914 QualType DestTy = Dest->getType();
1915 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
1916 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00001917
Chandler Carruth000d4282011-06-16 09:09:40 +00001918 // Never warn about void type pointers. This can be used to suppress
1919 // false positives.
1920 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00001921 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001922
Chandler Carruth000d4282011-06-16 09:09:40 +00001923 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
1924 // actually comparing the expressions for equality. Because computing the
1925 // expression IDs can be expensive, we only do this if the diagnostic is
1926 // enabled.
1927 if (SizeOfArg &&
1928 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
1929 SizeOfArg->getExprLoc())) {
1930 // We only compute IDs for expressions if the warning is enabled, and
1931 // cache the sizeof arg's ID.
1932 if (SizeOfArgID == llvm::FoldingSetNodeID())
1933 SizeOfArg->Profile(SizeOfArgID, Context, true);
1934 llvm::FoldingSetNodeID DestID;
1935 Dest->Profile(DestID, Context, true);
1936 if (DestID == SizeOfArgID) {
1937 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
1938 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
1939 if (UnaryOp->getOpcode() == UO_AddrOf)
1940 ActionIdx = 1; // If its an address-of operator, just remove it.
1941 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
1942 ActionIdx = 2; // If the pointee's size is sizeof(char),
1943 // suggest an explicit length.
1944 DiagRuntimeBehavior(SizeOfArg->getExprLoc(), Dest,
1945 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
1946 << FnName << ArgIdx << ActionIdx
1947 << Dest->getSourceRange()
1948 << SizeOfArg->getSourceRange());
1949 break;
1950 }
1951 }
1952
1953 // Also check for cases where the sizeof argument is the exact same
1954 // type as the memory argument, and where it points to a user-defined
1955 // record type.
1956 if (SizeOfArgTy != QualType()) {
1957 if (PointeeTy->isRecordType() &&
1958 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
1959 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
1960 PDiag(diag::warn_sizeof_pointer_type_memaccess)
1961 << FnName << SizeOfArgTy << ArgIdx
1962 << PointeeTy << Dest->getSourceRange()
1963 << LenExpr->getSourceRange());
1964 break;
1965 }
Nico Webere4a1c642011-06-14 16:14:58 +00001966 }
1967
John McCallf85e1932011-06-15 23:02:42 +00001968 unsigned DiagID;
1969
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00001970 // Always complain about dynamic classes.
John McCallf85e1932011-06-15 23:02:42 +00001971 if (isDynamicClassType(PointeeTy))
1972 DiagID = diag::warn_dyn_class_memaccess;
Douglas Gregor707a23e2011-06-16 17:56:04 +00001973 else if (PointeeTy.hasNonTrivialObjCLifetime() && CMF != CMF_Memset)
John McCallf85e1932011-06-15 23:02:42 +00001974 DiagID = diag::warn_arc_object_memaccess;
1975 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00001976 continue;
John McCallf85e1932011-06-15 23:02:42 +00001977
1978 DiagRuntimeBehavior(
1979 Dest->getExprLoc(), Dest,
1980 PDiag(DiagID)
1981 << ArgIdx << FnName << PointeeTy
1982 << Call->getCallee()->getSourceRange());
Chandler Carruth43fa33b2011-04-29 09:46:08 +00001983
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00001984 DiagRuntimeBehavior(
1985 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00001986 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00001987 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
1988 break;
1989 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001990 }
1991}
1992
Ted Kremenek06de2762007-08-17 16:46:58 +00001993//===--- CHECK: Return Address of Stack Variable --------------------------===//
1994
Chris Lattner5f9e2722011-07-23 10:55:15 +00001995static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars);
1996static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00001997
1998/// CheckReturnStackAddr - Check if a return statement returns the address
1999/// of a stack variable.
2000void
2001Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
2002 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00002003
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002004 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002005 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002006
2007 // Perform checking for returned stack addresses, local blocks,
2008 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00002009 if (lhsType->isPointerType() ||
2010 (!getLangOptions().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002011 stackE = EvalAddr(RetValExp, refVars);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002012 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002013 stackE = EvalVal(RetValExp, refVars);
2014 }
2015
2016 if (stackE == 0)
2017 return; // Nothing suspicious was found.
2018
2019 SourceLocation diagLoc;
2020 SourceRange diagRange;
2021 if (refVars.empty()) {
2022 diagLoc = stackE->getLocStart();
2023 diagRange = stackE->getSourceRange();
2024 } else {
2025 // We followed through a reference variable. 'stackE' contains the
2026 // problematic expression but we will warn at the return statement pointing
2027 // at the reference variable. We will later display the "trail" of
2028 // reference variables using notes.
2029 diagLoc = refVars[0]->getLocStart();
2030 diagRange = refVars[0]->getSourceRange();
2031 }
2032
2033 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
2034 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
2035 : diag::warn_ret_stack_addr)
2036 << DR->getDecl()->getDeclName() << diagRange;
2037 } else if (isa<BlockExpr>(stackE)) { // local block.
2038 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
2039 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
2040 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
2041 } else { // local temporary.
2042 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
2043 : diag::warn_ret_local_temp_addr)
2044 << diagRange;
2045 }
2046
2047 // Display the "trail" of reference variables that we followed until we
2048 // found the problematic expression using notes.
2049 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
2050 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
2051 // If this var binds to another reference var, show the range of the next
2052 // var, otherwise the var binds to the problematic expression, in which case
2053 // show the range of the expression.
2054 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
2055 : stackE->getSourceRange();
2056 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
2057 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00002058 }
2059}
2060
2061/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
2062/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002063/// to a location on the stack, a local block, an address of a label, or a
2064/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00002065/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002066/// encounter a subexpression that (1) clearly does not lead to one of the
2067/// above problematic expressions (2) is something we cannot determine leads to
2068/// a problematic expression based on such local checking.
2069///
2070/// Both EvalAddr and EvalVal follow through reference variables to evaluate
2071/// the expression that they point to. Such variables are added to the
2072/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00002073///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002074/// EvalAddr processes expressions that are pointers that are used as
2075/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002076/// At the base case of the recursion is a check for the above problematic
2077/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00002078///
2079/// This implementation handles:
2080///
2081/// * pointer-to-pointer casts
2082/// * implicit conversions from array references to pointers
2083/// * taking the address of fields
2084/// * arbitrary interplay between "&" and "*" operators
2085/// * pointer arithmetic from an address of a stack variable
2086/// * taking the address of an array element where the array is on the stack
Chris Lattner5f9e2722011-07-23 10:55:15 +00002087static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002088 if (E->isTypeDependent())
2089 return NULL;
2090
Ted Kremenek06de2762007-08-17 16:46:58 +00002091 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00002092 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00002093 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002094 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002095 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00002096
Peter Collingbournef111d932011-04-15 00:35:48 +00002097 E = E->IgnoreParens();
2098
Ted Kremenek06de2762007-08-17 16:46:58 +00002099 // Our "symbolic interpreter" is just a dispatch off the currently
2100 // viewed AST node. We then recursively traverse the AST by calling
2101 // EvalAddr and EvalVal appropriately.
2102 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002103 case Stmt::DeclRefExprClass: {
2104 DeclRefExpr *DR = cast<DeclRefExpr>(E);
2105
2106 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
2107 // If this is a reference variable, follow through to the expression that
2108 // it points to.
2109 if (V->hasLocalStorage() &&
2110 V->getType()->isReferenceType() && V->hasInit()) {
2111 // Add the reference variable to the "trail".
2112 refVars.push_back(DR);
2113 return EvalAddr(V->getInit(), refVars);
2114 }
2115
2116 return NULL;
2117 }
Ted Kremenek06de2762007-08-17 16:46:58 +00002118
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002119 case Stmt::UnaryOperatorClass: {
2120 // The only unary operator that make sense to handle here
2121 // is AddrOf. All others don't make sense as pointers.
2122 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002123
John McCall2de56d12010-08-25 11:45:40 +00002124 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002125 return EvalVal(U->getSubExpr(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002126 else
Ted Kremenek06de2762007-08-17 16:46:58 +00002127 return NULL;
2128 }
Mike Stump1eb44332009-09-09 15:08:12 +00002129
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002130 case Stmt::BinaryOperatorClass: {
2131 // Handle pointer arithmetic. All other binary operators are not valid
2132 // in this context.
2133 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00002134 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00002135
John McCall2de56d12010-08-25 11:45:40 +00002136 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002137 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00002138
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002139 Expr *Base = B->getLHS();
2140
2141 // Determine which argument is the real pointer base. It could be
2142 // the RHS argument instead of the LHS.
2143 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00002144
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002145 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002146 return EvalAddr(Base, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002147 }
Steve Naroff61f40a22008-09-10 19:17:48 +00002148
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002149 // For conditional operators we need to see if either the LHS or RHS are
2150 // valid DeclRefExpr*s. If one of them is valid, we return it.
2151 case Stmt::ConditionalOperatorClass: {
2152 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002153
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002154 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002155 if (Expr *lhsExpr = C->getLHS()) {
2156 // In C++, we can have a throw-expression, which has 'void' type.
2157 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002158 if (Expr* LHS = EvalAddr(lhsExpr, refVars))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002159 return LHS;
2160 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002161
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002162 // In C++, we can have a throw-expression, which has 'void' type.
2163 if (C->getRHS()->getType()->isVoidType())
2164 return NULL;
2165
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002166 return EvalAddr(C->getRHS(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002167 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002168
2169 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00002170 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002171 return E; // local block.
2172 return NULL;
2173
2174 case Stmt::AddrLabelExprClass:
2175 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00002176
Ted Kremenek54b52742008-08-07 00:49:01 +00002177 // For casts, we need to handle conversions from arrays to
2178 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00002179 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002180 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00002181 case Stmt::CXXFunctionalCastExprClass:
2182 case Stmt::ObjCBridgedCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002183 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00002184 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002185
Steve Naroffdd972f22008-09-05 22:11:13 +00002186 if (SubExpr->getType()->isPointerType() ||
2187 SubExpr->getType()->isBlockPointerType() ||
2188 SubExpr->getType()->isObjCQualifiedIdType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002189 return EvalAddr(SubExpr, refVars);
Ted Kremenek54b52742008-08-07 00:49:01 +00002190 else if (T->isArrayType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002191 return EvalVal(SubExpr, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002192 else
Ted Kremenek54b52742008-08-07 00:49:01 +00002193 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002194 }
Mike Stump1eb44332009-09-09 15:08:12 +00002195
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002196 // C++ casts. For dynamic casts, static casts, and const casts, we
2197 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00002198 // through the cast. In the case the dynamic cast doesn't fail (and
2199 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002200 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00002201 // FIXME: The comment about is wrong; we're not always converting
2202 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00002203 // handle references to objects.
2204 case Stmt::CXXStaticCastExprClass:
2205 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00002206 case Stmt::CXXConstCastExprClass:
2207 case Stmt::CXXReinterpretCastExprClass: {
2208 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00002209 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002210 return EvalAddr(S, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002211 else
2212 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002213 }
Mike Stump1eb44332009-09-09 15:08:12 +00002214
Douglas Gregor03e80032011-06-21 17:03:29 +00002215 case Stmt::MaterializeTemporaryExprClass:
2216 if (Expr *Result = EvalAddr(
2217 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
2218 refVars))
2219 return Result;
2220
2221 return E;
2222
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002223 // Everything else: we simply don't reason about them.
2224 default:
2225 return NULL;
2226 }
Ted Kremenek06de2762007-08-17 16:46:58 +00002227}
Mike Stump1eb44332009-09-09 15:08:12 +00002228
Ted Kremenek06de2762007-08-17 16:46:58 +00002229
2230/// EvalVal - This function is complements EvalAddr in the mutual recursion.
2231/// See the comments for EvalAddr for more details.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002232static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002233do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002234 // We should only be called for evaluating non-pointer expressions, or
2235 // expressions with a pointer type that are not used as references but instead
2236 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00002237
Ted Kremenek06de2762007-08-17 16:46:58 +00002238 // Our "symbolic interpreter" is just a dispatch off the currently
2239 // viewed AST node. We then recursively traverse the AST by calling
2240 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00002241
2242 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00002243 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002244 case Stmt::ImplicitCastExprClass: {
2245 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00002246 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002247 E = IE->getSubExpr();
2248 continue;
2249 }
2250 return NULL;
2251 }
2252
Douglas Gregora2813ce2009-10-23 18:54:35 +00002253 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002254 // When we hit a DeclRefExpr we are looking at code that refers to a
2255 // variable's name. If it's not a reference variable we check if it has
2256 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00002257 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002258
Ted Kremenek06de2762007-08-17 16:46:58 +00002259 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002260 if (V->hasLocalStorage()) {
2261 if (!V->getType()->isReferenceType())
2262 return DR;
2263
2264 // Reference variable, follow through to the expression that
2265 // it points to.
2266 if (V->hasInit()) {
2267 // Add the reference variable to the "trail".
2268 refVars.push_back(DR);
2269 return EvalVal(V->getInit(), refVars);
2270 }
2271 }
Mike Stump1eb44332009-09-09 15:08:12 +00002272
Ted Kremenek06de2762007-08-17 16:46:58 +00002273 return NULL;
2274 }
Mike Stump1eb44332009-09-09 15:08:12 +00002275
Ted Kremenek06de2762007-08-17 16:46:58 +00002276 case Stmt::UnaryOperatorClass: {
2277 // The only unary operator that make sense to handle here
2278 // is Deref. All others don't resolve to a "name." This includes
2279 // handling all sorts of rvalues passed to a unary operator.
2280 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002281
John McCall2de56d12010-08-25 11:45:40 +00002282 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002283 return EvalAddr(U->getSubExpr(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002284
2285 return NULL;
2286 }
Mike Stump1eb44332009-09-09 15:08:12 +00002287
Ted Kremenek06de2762007-08-17 16:46:58 +00002288 case Stmt::ArraySubscriptExprClass: {
2289 // Array subscripts are potential references to data on the stack. We
2290 // retrieve the DeclRefExpr* for the array variable if it indeed
2291 // has local storage.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002292 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002293 }
Mike Stump1eb44332009-09-09 15:08:12 +00002294
Ted Kremenek06de2762007-08-17 16:46:58 +00002295 case Stmt::ConditionalOperatorClass: {
2296 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002297 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00002298 ConditionalOperator *C = cast<ConditionalOperator>(E);
2299
Anders Carlsson39073232007-11-30 19:04:31 +00002300 // Handle the GNU extension for missing LHS.
2301 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002302 if (Expr *LHS = EvalVal(lhsExpr, refVars))
Anders Carlsson39073232007-11-30 19:04:31 +00002303 return LHS;
2304
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002305 return EvalVal(C->getRHS(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002306 }
Mike Stump1eb44332009-09-09 15:08:12 +00002307
Ted Kremenek06de2762007-08-17 16:46:58 +00002308 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00002309 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00002310 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002311
Ted Kremenek06de2762007-08-17 16:46:58 +00002312 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00002313 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00002314 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00002315
2316 // Check whether the member type is itself a reference, in which case
2317 // we're not going to refer to the member, but to what the member refers to.
2318 if (M->getMemberDecl()->getType()->isReferenceType())
2319 return NULL;
2320
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002321 return EvalVal(M->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002322 }
Mike Stump1eb44332009-09-09 15:08:12 +00002323
Douglas Gregor03e80032011-06-21 17:03:29 +00002324 case Stmt::MaterializeTemporaryExprClass:
2325 if (Expr *Result = EvalVal(
2326 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
2327 refVars))
2328 return Result;
2329
2330 return E;
2331
Ted Kremenek06de2762007-08-17 16:46:58 +00002332 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002333 // Check that we don't return or take the address of a reference to a
2334 // temporary. This is only useful in C++.
2335 if (!E->isTypeDependent() && E->isRValue())
2336 return E;
2337
2338 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00002339 return NULL;
2340 }
Ted Kremenek68957a92010-08-04 20:01:07 +00002341} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00002342}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002343
2344//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
2345
2346/// Check for comparisons of floating point operands using != and ==.
2347/// Issue a warning if these are no self-comparisons, as they are not likely
2348/// to do what the programmer intended.
2349void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
2350 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002351
John McCallf6a16482010-12-04 03:47:34 +00002352 Expr* LeftExprSansParen = lex->IgnoreParenImpCasts();
2353 Expr* RightExprSansParen = rex->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002354
2355 // Special case: check for x == x (which is OK).
2356 // Do not emit warnings for such cases.
2357 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
2358 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
2359 if (DRL->getDecl() == DRR->getDecl())
2360 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002361
2362
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002363 // Special case: check for comparisons against literals that can be exactly
2364 // represented by APFloat. In such cases, do not emit a warning. This
2365 // is a heuristic: often comparison against such literals are used to
2366 // detect if a value in a variable has not changed. This clearly can
2367 // lead to false negatives.
2368 if (EmitWarning) {
2369 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
2370 if (FLL->isExact())
2371 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002372 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002373 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
2374 if (FLR->isExact())
2375 EmitWarning = false;
2376 }
2377 }
Mike Stump1eb44332009-09-09 15:08:12 +00002378
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002379 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002380 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002381 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002382 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002383 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002384
Sebastian Redl0eb23302009-01-19 00:08:26 +00002385 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002386 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002387 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002388 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002389
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002390 // Emit the diagnostic.
2391 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002392 Diag(loc, diag::warn_floatingpoint_eq)
2393 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002394}
John McCallba26e582010-01-04 23:21:16 +00002395
John McCallf2370c92010-01-06 05:24:50 +00002396//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
2397//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00002398
John McCallf2370c92010-01-06 05:24:50 +00002399namespace {
John McCallba26e582010-01-04 23:21:16 +00002400
John McCallf2370c92010-01-06 05:24:50 +00002401/// Structure recording the 'active' range of an integer-valued
2402/// expression.
2403struct IntRange {
2404 /// The number of bits active in the int.
2405 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00002406
John McCallf2370c92010-01-06 05:24:50 +00002407 /// True if the int is known not to have negative values.
2408 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00002409
John McCallf2370c92010-01-06 05:24:50 +00002410 IntRange(unsigned Width, bool NonNegative)
2411 : Width(Width), NonNegative(NonNegative)
2412 {}
John McCallba26e582010-01-04 23:21:16 +00002413
John McCall1844a6e2010-11-10 23:38:19 +00002414 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00002415 static IntRange forBoolType() {
2416 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00002417 }
2418
John McCall1844a6e2010-11-10 23:38:19 +00002419 /// Returns the range of an opaque value of the given integral type.
2420 static IntRange forValueOfType(ASTContext &C, QualType T) {
2421 return forValueOfCanonicalType(C,
2422 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00002423 }
2424
John McCall1844a6e2010-11-10 23:38:19 +00002425 /// Returns the range of an opaque value of a canonical integral type.
2426 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00002427 assert(T->isCanonicalUnqualified());
2428
2429 if (const VectorType *VT = dyn_cast<VectorType>(T))
2430 T = VT->getElementType().getTypePtr();
2431 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2432 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00002433
John McCall091f23f2010-11-09 22:22:12 +00002434 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00002435 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
2436 EnumDecl *Enum = ET->getDecl();
John McCall091f23f2010-11-09 22:22:12 +00002437 if (!Enum->isDefinition())
2438 return IntRange(C.getIntWidth(QualType(T, 0)), false);
2439
John McCall323ed742010-05-06 08:58:33 +00002440 unsigned NumPositive = Enum->getNumPositiveBits();
2441 unsigned NumNegative = Enum->getNumNegativeBits();
2442
2443 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
2444 }
John McCallf2370c92010-01-06 05:24:50 +00002445
2446 const BuiltinType *BT = cast<BuiltinType>(T);
2447 assert(BT->isInteger());
2448
2449 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2450 }
2451
John McCall1844a6e2010-11-10 23:38:19 +00002452 /// Returns the "target" range of a canonical integral type, i.e.
2453 /// the range of values expressible in the type.
2454 ///
2455 /// This matches forValueOfCanonicalType except that enums have the
2456 /// full range of their type, not the range of their enumerators.
2457 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
2458 assert(T->isCanonicalUnqualified());
2459
2460 if (const VectorType *VT = dyn_cast<VectorType>(T))
2461 T = VT->getElementType().getTypePtr();
2462 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2463 T = CT->getElementType().getTypePtr();
2464 if (const EnumType *ET = dyn_cast<EnumType>(T))
2465 T = ET->getDecl()->getIntegerType().getTypePtr();
2466
2467 const BuiltinType *BT = cast<BuiltinType>(T);
2468 assert(BT->isInteger());
2469
2470 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2471 }
2472
2473 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002474 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00002475 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00002476 L.NonNegative && R.NonNegative);
2477 }
2478
John McCall1844a6e2010-11-10 23:38:19 +00002479 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002480 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00002481 return IntRange(std::min(L.Width, R.Width),
2482 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00002483 }
2484};
2485
2486IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
2487 if (value.isSigned() && value.isNegative())
2488 return IntRange(value.getMinSignedBits(), false);
2489
2490 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002491 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00002492
2493 // isNonNegative() just checks the sign bit without considering
2494 // signedness.
2495 return IntRange(value.getActiveBits(), true);
2496}
2497
John McCall0acc3112010-01-06 22:57:21 +00002498IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCallf2370c92010-01-06 05:24:50 +00002499 unsigned MaxWidth) {
2500 if (result.isInt())
2501 return GetValueRange(C, result.getInt(), MaxWidth);
2502
2503 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00002504 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
2505 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
2506 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
2507 R = IntRange::join(R, El);
2508 }
John McCallf2370c92010-01-06 05:24:50 +00002509 return R;
2510 }
2511
2512 if (result.isComplexInt()) {
2513 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
2514 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
2515 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00002516 }
2517
2518 // This can happen with lossless casts to intptr_t of "based" lvalues.
2519 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00002520 // FIXME: The only reason we need to pass the type in here is to get
2521 // the sign right on this one case. It would be nice if APValue
2522 // preserved this.
John McCallf2370c92010-01-06 05:24:50 +00002523 assert(result.isLValue());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00002524 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00002525}
John McCallf2370c92010-01-06 05:24:50 +00002526
2527/// Pseudo-evaluate the given integer expression, estimating the
2528/// range of values it might take.
2529///
2530/// \param MaxWidth - the width to which the value will be truncated
2531IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
2532 E = E->IgnoreParens();
2533
2534 // Try a full evaluation first.
2535 Expr::EvalResult result;
2536 if (E->Evaluate(result, C))
John McCall0acc3112010-01-06 22:57:21 +00002537 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00002538
2539 // I think we only want to look through implicit casts here; if the
2540 // user has an explicit widening cast, we should treat the value as
2541 // being of the new, wider type.
2542 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00002543 if (CE->getCastKind() == CK_NoOp)
John McCallf2370c92010-01-06 05:24:50 +00002544 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
2545
John McCall1844a6e2010-11-10 23:38:19 +00002546 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00002547
John McCall2de56d12010-08-25 11:45:40 +00002548 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00002549
John McCallf2370c92010-01-06 05:24:50 +00002550 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00002551 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00002552 return OutputTypeRange;
2553
2554 IntRange SubRange
2555 = GetExprRange(C, CE->getSubExpr(),
2556 std::min(MaxWidth, OutputTypeRange.Width));
2557
2558 // Bail out if the subexpr's range is as wide as the cast type.
2559 if (SubRange.Width >= OutputTypeRange.Width)
2560 return OutputTypeRange;
2561
2562 // Otherwise, we take the smaller width, and we're non-negative if
2563 // either the output type or the subexpr is.
2564 return IntRange(SubRange.Width,
2565 SubRange.NonNegative || OutputTypeRange.NonNegative);
2566 }
2567
2568 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2569 // If we can fold the condition, just take that operand.
2570 bool CondResult;
2571 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
2572 return GetExprRange(C, CondResult ? CO->getTrueExpr()
2573 : CO->getFalseExpr(),
2574 MaxWidth);
2575
2576 // Otherwise, conservatively merge.
2577 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
2578 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
2579 return IntRange::join(L, R);
2580 }
2581
2582 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2583 switch (BO->getOpcode()) {
2584
2585 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00002586 case BO_LAnd:
2587 case BO_LOr:
2588 case BO_LT:
2589 case BO_GT:
2590 case BO_LE:
2591 case BO_GE:
2592 case BO_EQ:
2593 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00002594 return IntRange::forBoolType();
2595
John McCall862ff872011-07-13 06:35:24 +00002596 // The type of the assignments is the type of the LHS, so the RHS
2597 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00002598 case BO_MulAssign:
2599 case BO_DivAssign:
2600 case BO_RemAssign:
2601 case BO_AddAssign:
2602 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00002603 case BO_XorAssign:
2604 case BO_OrAssign:
2605 // TODO: bitfields?
John McCall1844a6e2010-11-10 23:38:19 +00002606 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00002607
John McCall862ff872011-07-13 06:35:24 +00002608 // Simple assignments just pass through the RHS, which will have
2609 // been coerced to the LHS type.
2610 case BO_Assign:
2611 // TODO: bitfields?
2612 return GetExprRange(C, BO->getRHS(), MaxWidth);
2613
John McCallf2370c92010-01-06 05:24:50 +00002614 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00002615 case BO_PtrMemD:
2616 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00002617 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002618
John McCall60fad452010-01-06 22:07:33 +00002619 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00002620 case BO_And:
2621 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00002622 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
2623 GetExprRange(C, BO->getRHS(), MaxWidth));
2624
John McCallf2370c92010-01-06 05:24:50 +00002625 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00002626 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00002627 // ...except that we want to treat '1 << (blah)' as logically
2628 // positive. It's an important idiom.
2629 if (IntegerLiteral *I
2630 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
2631 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00002632 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00002633 return IntRange(R.Width, /*NonNegative*/ true);
2634 }
2635 }
2636 // fallthrough
2637
John McCall2de56d12010-08-25 11:45:40 +00002638 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00002639 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002640
John McCall60fad452010-01-06 22:07:33 +00002641 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00002642 case BO_Shr:
2643 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00002644 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2645
2646 // If the shift amount is a positive constant, drop the width by
2647 // that much.
2648 llvm::APSInt shift;
2649 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
2650 shift.isNonNegative()) {
2651 unsigned zext = shift.getZExtValue();
2652 if (zext >= L.Width)
2653 L.Width = (L.NonNegative ? 0 : 1);
2654 else
2655 L.Width -= zext;
2656 }
2657
2658 return L;
2659 }
2660
2661 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00002662 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00002663 return GetExprRange(C, BO->getRHS(), MaxWidth);
2664
John McCall60fad452010-01-06 22:07:33 +00002665 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00002666 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00002667 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00002668 return IntRange::forValueOfType(C, E->getType());
John McCall00fe7612011-07-14 22:39:48 +00002669 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002670
John McCall00fe7612011-07-14 22:39:48 +00002671 // The width of a division result is mostly determined by the size
2672 // of the LHS.
2673 case BO_Div: {
2674 // Don't 'pre-truncate' the operands.
2675 unsigned opWidth = C.getIntWidth(E->getType());
2676 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
2677
2678 // If the divisor is constant, use that.
2679 llvm::APSInt divisor;
2680 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
2681 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
2682 if (log2 >= L.Width)
2683 L.Width = (L.NonNegative ? 0 : 1);
2684 else
2685 L.Width = std::min(L.Width - log2, MaxWidth);
2686 return L;
2687 }
2688
2689 // Otherwise, just use the LHS's width.
2690 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
2691 return IntRange(L.Width, L.NonNegative && R.NonNegative);
2692 }
2693
2694 // The result of a remainder can't be larger than the result of
2695 // either side.
2696 case BO_Rem: {
2697 // Don't 'pre-truncate' the operands.
2698 unsigned opWidth = C.getIntWidth(E->getType());
2699 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
2700 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
2701
2702 IntRange meet = IntRange::meet(L, R);
2703 meet.Width = std::min(meet.Width, MaxWidth);
2704 return meet;
2705 }
2706
2707 // The default behavior is okay for these.
2708 case BO_Mul:
2709 case BO_Add:
2710 case BO_Xor:
2711 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00002712 break;
2713 }
2714
John McCall00fe7612011-07-14 22:39:48 +00002715 // The default case is to treat the operation as if it were closed
2716 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00002717 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2718 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
2719 return IntRange::join(L, R);
2720 }
2721
2722 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2723 switch (UO->getOpcode()) {
2724 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00002725 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00002726 return IntRange::forBoolType();
2727
2728 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00002729 case UO_Deref:
2730 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00002731 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002732
2733 default:
2734 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
2735 }
2736 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002737
2738 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00002739 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002740 }
John McCallf2370c92010-01-06 05:24:50 +00002741
2742 FieldDecl *BitField = E->getBitField();
2743 if (BitField) {
2744 llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C);
2745 unsigned BitWidth = BitWidthAP.getZExtValue();
2746
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00002747 return IntRange(BitWidth,
2748 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00002749 }
2750
John McCall1844a6e2010-11-10 23:38:19 +00002751 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002752}
John McCall51313c32010-01-04 23:31:57 +00002753
John McCall323ed742010-05-06 08:58:33 +00002754IntRange GetExprRange(ASTContext &C, Expr *E) {
2755 return GetExprRange(C, E, C.getIntWidth(E->getType()));
2756}
2757
John McCall51313c32010-01-04 23:31:57 +00002758/// Checks whether the given value, which currently has the given
2759/// source semantics, has the same value when coerced through the
2760/// target semantics.
John McCallf2370c92010-01-06 05:24:50 +00002761bool IsSameFloatAfterCast(const llvm::APFloat &value,
2762 const llvm::fltSemantics &Src,
2763 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002764 llvm::APFloat truncated = value;
2765
2766 bool ignored;
2767 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
2768 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
2769
2770 return truncated.bitwiseIsEqual(value);
2771}
2772
2773/// Checks whether the given value, which currently has the given
2774/// source semantics, has the same value when coerced through the
2775/// target semantics.
2776///
2777/// The value might be a vector of floats (or a complex number).
John McCallf2370c92010-01-06 05:24:50 +00002778bool IsSameFloatAfterCast(const APValue &value,
2779 const llvm::fltSemantics &Src,
2780 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002781 if (value.isFloat())
2782 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
2783
2784 if (value.isVector()) {
2785 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
2786 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
2787 return false;
2788 return true;
2789 }
2790
2791 assert(value.isComplexFloat());
2792 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
2793 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
2794}
2795
John McCallb4eb64d2010-10-08 02:01:28 +00002796void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00002797
Ted Kremeneke3b159c2010-09-23 21:43:44 +00002798static bool IsZero(Sema &S, Expr *E) {
2799 // Suppress cases where we are comparing against an enum constant.
2800 if (const DeclRefExpr *DR =
2801 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
2802 if (isa<EnumConstantDecl>(DR->getDecl()))
2803 return false;
2804
2805 // Suppress cases where the '0' value is expanded from a macro.
2806 if (E->getLocStart().isMacroID())
2807 return false;
2808
John McCall323ed742010-05-06 08:58:33 +00002809 llvm::APSInt Value;
2810 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
2811}
2812
John McCall372e1032010-10-06 00:25:24 +00002813static bool HasEnumType(Expr *E) {
2814 // Strip off implicit integral promotions.
2815 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00002816 if (ICE->getCastKind() != CK_IntegralCast &&
2817 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00002818 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00002819 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00002820 }
2821
2822 return E->getType()->isEnumeralType();
2823}
2824
John McCall323ed742010-05-06 08:58:33 +00002825void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002826 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00002827 if (E->isValueDependent())
2828 return;
2829
John McCall2de56d12010-08-25 11:45:40 +00002830 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00002831 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002832 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00002833 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002834 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00002835 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002836 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00002837 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002838 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00002839 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002840 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00002841 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002842 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00002843 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002844 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00002845 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2846 }
2847}
2848
2849/// Analyze the operands of the given comparison. Implements the
2850/// fallback case from AnalyzeComparison.
2851void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00002852 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
2853 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00002854}
John McCall51313c32010-01-04 23:31:57 +00002855
John McCallba26e582010-01-04 23:21:16 +00002856/// \brief Implements -Wsign-compare.
2857///
2858/// \param lex the left-hand expression
2859/// \param rex the right-hand expression
2860/// \param OpLoc the location of the joining operator
John McCalld1b47bf2010-03-11 19:43:18 +00002861/// \param BinOpc binary opcode or 0
John McCall323ed742010-05-06 08:58:33 +00002862void AnalyzeComparison(Sema &S, BinaryOperator *E) {
2863 // The type the comparison is being performed in.
2864 QualType T = E->getLHS()->getType();
2865 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
2866 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00002867
John McCall323ed742010-05-06 08:58:33 +00002868 // We don't do anything special if this isn't an unsigned integral
2869 // comparison: we're only interested in integral comparisons, and
2870 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00002871 //
2872 // We also don't care about value-dependent expressions or expressions
2873 // whose result is a constant.
2874 if (!T->hasUnsignedIntegerRepresentation()
2875 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCall323ed742010-05-06 08:58:33 +00002876 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00002877
John McCall323ed742010-05-06 08:58:33 +00002878 Expr *lex = E->getLHS()->IgnoreParenImpCasts();
2879 Expr *rex = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00002880
John McCall323ed742010-05-06 08:58:33 +00002881 // Check to see if one of the (unmodified) operands is of different
2882 // signedness.
2883 Expr *signedOperand, *unsignedOperand;
Douglas Gregorf6094622010-07-23 15:58:24 +00002884 if (lex->getType()->hasSignedIntegerRepresentation()) {
2885 assert(!rex->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00002886 "unsigned comparison between two signed integer expressions?");
2887 signedOperand = lex;
2888 unsignedOperand = rex;
Douglas Gregorf6094622010-07-23 15:58:24 +00002889 } else if (rex->getType()->hasSignedIntegerRepresentation()) {
John McCall323ed742010-05-06 08:58:33 +00002890 signedOperand = rex;
2891 unsignedOperand = lex;
John McCallba26e582010-01-04 23:21:16 +00002892 } else {
John McCall323ed742010-05-06 08:58:33 +00002893 CheckTrivialUnsignedComparison(S, E);
2894 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00002895 }
2896
John McCall323ed742010-05-06 08:58:33 +00002897 // Otherwise, calculate the effective range of the signed operand.
2898 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00002899
John McCall323ed742010-05-06 08:58:33 +00002900 // Go ahead and analyze implicit conversions in the operands. Note
2901 // that we skip the implicit conversions on both sides.
John McCallb4eb64d2010-10-08 02:01:28 +00002902 AnalyzeImplicitConversions(S, lex, E->getOperatorLoc());
2903 AnalyzeImplicitConversions(S, rex, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00002904
John McCall323ed742010-05-06 08:58:33 +00002905 // If the signed range is non-negative, -Wsign-compare won't fire,
2906 // but we should still check for comparisons which are always true
2907 // or false.
2908 if (signedRange.NonNegative)
2909 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00002910
2911 // For (in)equality comparisons, if the unsigned operand is a
2912 // constant which cannot collide with a overflowed signed operand,
2913 // then reinterpreting the signed operand as unsigned will not
2914 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00002915 if (E->isEqualityOp()) {
2916 unsigned comparisonWidth = S.Context.getIntWidth(T);
2917 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00002918
John McCall323ed742010-05-06 08:58:33 +00002919 // We should never be unable to prove that the unsigned operand is
2920 // non-negative.
2921 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
2922
2923 if (unsignedRange.Width < comparisonWidth)
2924 return;
2925 }
2926
2927 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
2928 << lex->getType() << rex->getType()
2929 << lex->getSourceRange() << rex->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00002930}
2931
John McCall15d7d122010-11-11 03:21:53 +00002932/// Analyzes an attempt to assign the given value to a bitfield.
2933///
2934/// Returns true if there was something fishy about the attempt.
2935bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
2936 SourceLocation InitLoc) {
2937 assert(Bitfield->isBitField());
2938 if (Bitfield->isInvalidDecl())
2939 return false;
2940
John McCall91b60142010-11-11 05:33:51 +00002941 // White-list bool bitfields.
2942 if (Bitfield->getType()->isBooleanType())
2943 return false;
2944
Douglas Gregor46ff3032011-02-04 13:09:01 +00002945 // Ignore value- or type-dependent expressions.
2946 if (Bitfield->getBitWidth()->isValueDependent() ||
2947 Bitfield->getBitWidth()->isTypeDependent() ||
2948 Init->isValueDependent() ||
2949 Init->isTypeDependent())
2950 return false;
2951
John McCall15d7d122010-11-11 03:21:53 +00002952 Expr *OriginalInit = Init->IgnoreParenImpCasts();
2953
2954 llvm::APSInt Width(32);
2955 Expr::EvalResult InitValue;
2956 if (!Bitfield->getBitWidth()->isIntegerConstantExpr(Width, S.Context) ||
John McCall91b60142010-11-11 05:33:51 +00002957 !OriginalInit->Evaluate(InitValue, S.Context) ||
John McCall15d7d122010-11-11 03:21:53 +00002958 !InitValue.Val.isInt())
2959 return false;
2960
2961 const llvm::APSInt &Value = InitValue.Val.getInt();
2962 unsigned OriginalWidth = Value.getBitWidth();
2963 unsigned FieldWidth = Width.getZExtValue();
2964
2965 if (OriginalWidth <= FieldWidth)
2966 return false;
2967
Jay Foad9f71a8f2010-12-07 08:25:34 +00002968 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
John McCall15d7d122010-11-11 03:21:53 +00002969
2970 // It's fairly common to write values into signed bitfields
2971 // that, if sign-extended, would end up becoming a different
2972 // value. We don't want to warn about that.
2973 if (Value.isSigned() && Value.isNegative())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002974 TruncatedValue = TruncatedValue.sext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00002975 else
Jay Foad9f71a8f2010-12-07 08:25:34 +00002976 TruncatedValue = TruncatedValue.zext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00002977
2978 if (Value == TruncatedValue)
2979 return false;
2980
2981 std::string PrettyValue = Value.toString(10);
2982 std::string PrettyTrunc = TruncatedValue.toString(10);
2983
2984 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
2985 << PrettyValue << PrettyTrunc << OriginalInit->getType()
2986 << Init->getSourceRange();
2987
2988 return true;
2989}
2990
John McCallbeb22aa2010-11-09 23:24:47 +00002991/// Analyze the given simple or compound assignment for warning-worthy
2992/// operations.
2993void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
2994 // Just recurse on the LHS.
2995 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
2996
2997 // We want to recurse on the RHS as normal unless we're assigning to
2998 // a bitfield.
2999 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00003000 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
3001 E->getOperatorLoc())) {
3002 // Recurse, ignoring any implicit conversions on the RHS.
3003 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
3004 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00003005 }
3006 }
3007
3008 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
3009}
3010
John McCall51313c32010-01-04 23:31:57 +00003011/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003012void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
3013 SourceLocation CContext, unsigned diag) {
3014 S.Diag(E->getExprLoc(), diag)
3015 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
3016}
3017
Chandler Carruthe1b02e02011-04-05 06:47:57 +00003018/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
3019void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
3020 unsigned diag) {
3021 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag);
3022}
3023
Chandler Carruthf65076e2011-04-10 08:36:24 +00003024/// Diagnose an implicit cast from a literal expression. Also attemps to supply
3025/// fixit hints when the cast wouldn't lose information to simply write the
3026/// expression with the expected type.
3027void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
3028 SourceLocation CContext) {
3029 // Emit the primary warning first, then try to emit a fixit hint note if
3030 // reasonable.
3031 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
3032 << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext);
3033
3034 const llvm::APFloat &Value = FL->getValue();
3035
3036 // Don't attempt to fix PPC double double literals.
3037 if (&Value.getSemantics() == &llvm::APFloat::PPCDoubleDouble)
3038 return;
3039
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00003040 // Try to convert this exactly to an integer.
Chandler Carruthf65076e2011-04-10 08:36:24 +00003041 bool isExact = false;
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00003042 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
3043 T->hasUnsignedIntegerRepresentation());
3044 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00003045 llvm::APFloat::rmTowardZero, &isExact)
3046 != llvm::APFloat::opOK || !isExact)
3047 return;
3048
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00003049 std::string LiteralValue = IntegerValue.toString(10);
Chandler Carruthf65076e2011-04-10 08:36:24 +00003050 S.Diag(FL->getExprLoc(), diag::note_fix_integral_float_as_integer)
3051 << FixItHint::CreateReplacement(FL->getSourceRange(), LiteralValue);
3052}
3053
John McCall091f23f2010-11-09 22:22:12 +00003054std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
3055 if (!Range.Width) return "0";
3056
3057 llvm::APSInt ValueInRange = Value;
3058 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00003059 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00003060 return ValueInRange.toString(10);
3061}
3062
Ted Kremenekef9ff882011-03-10 20:03:42 +00003063static bool isFromSystemMacro(Sema &S, SourceLocation loc) {
3064 SourceManager &smgr = S.Context.getSourceManager();
3065 return loc.isMacroID() && smgr.isInSystemHeader(smgr.getSpellingLoc(loc));
3066}
Chandler Carruthf65076e2011-04-10 08:36:24 +00003067
John McCall323ed742010-05-06 08:58:33 +00003068void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00003069 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00003070 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00003071
John McCall323ed742010-05-06 08:58:33 +00003072 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
3073 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
3074 if (Source == Target) return;
3075 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00003076
Chandler Carruth108f7562011-07-26 05:40:03 +00003077 // If the conversion context location is invalid don't complain. We also
3078 // don't want to emit a warning if the issue occurs from the expansion of
3079 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
3080 // delay this check as long as possible. Once we detect we are in that
3081 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00003082 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00003083 return;
3084
John McCall51313c32010-01-04 23:31:57 +00003085 // Never diagnose implicit casts to bool.
3086 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
3087 return;
3088
3089 // Strip vector types.
3090 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003091 if (!isa<VectorType>(Target)) {
3092 if (isFromSystemMacro(S, CC))
3093 return;
John McCallb4eb64d2010-10-08 02:01:28 +00003094 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003095 }
Chris Lattnerb792b302011-06-14 04:51:15 +00003096
3097 // If the vector cast is cast between two vectors of the same size, it is
3098 // a bitcast, not a conversion.
3099 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
3100 return;
John McCall51313c32010-01-04 23:31:57 +00003101
3102 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
3103 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
3104 }
3105
3106 // Strip complex types.
3107 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003108 if (!isa<ComplexType>(Target)) {
3109 if (isFromSystemMacro(S, CC))
3110 return;
3111
John McCallb4eb64d2010-10-08 02:01:28 +00003112 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003113 }
John McCall51313c32010-01-04 23:31:57 +00003114
3115 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
3116 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
3117 }
3118
3119 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
3120 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
3121
3122 // If the source is floating point...
3123 if (SourceBT && SourceBT->isFloatingPoint()) {
3124 // ...and the target is floating point...
3125 if (TargetBT && TargetBT->isFloatingPoint()) {
3126 // ...then warn if we're dropping FP rank.
3127
3128 // Builtin FP kinds are ordered by increasing FP rank.
3129 if (SourceBT->getKind() > TargetBT->getKind()) {
3130 // Don't warn about float constants that are precisely
3131 // representable in the target type.
3132 Expr::EvalResult result;
John McCall323ed742010-05-06 08:58:33 +00003133 if (E->Evaluate(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00003134 // Value might be a float, a float vector, or a float complex.
3135 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00003136 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
3137 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00003138 return;
3139 }
3140
Ted Kremenekef9ff882011-03-10 20:03:42 +00003141 if (isFromSystemMacro(S, CC))
3142 return;
3143
John McCallb4eb64d2010-10-08 02:01:28 +00003144 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00003145 }
3146 return;
3147 }
3148
Ted Kremenekef9ff882011-03-10 20:03:42 +00003149 // If the target is integral, always warn.
Chandler Carrutha5b93322011-02-17 11:05:49 +00003150 if ((TargetBT && TargetBT->isInteger())) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003151 if (isFromSystemMacro(S, CC))
3152 return;
3153
Chandler Carrutha5b93322011-02-17 11:05:49 +00003154 Expr *InnerE = E->IgnoreParenImpCasts();
Chandler Carruthf65076e2011-04-10 08:36:24 +00003155 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
3156 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00003157 } else {
3158 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
3159 }
3160 }
John McCall51313c32010-01-04 23:31:57 +00003161
3162 return;
3163 }
3164
John McCallf2370c92010-01-06 05:24:50 +00003165 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00003166 return;
3167
Richard Trieu1838ca52011-05-29 19:59:02 +00003168 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
3169 == Expr::NPCK_GNUNull) && Target->isIntegerType()) {
3170 S.Diag(E->getExprLoc(), diag::warn_impcast_null_pointer_to_integer)
3171 << E->getSourceRange() << clang::SourceRange(CC);
3172 return;
3173 }
3174
John McCall323ed742010-05-06 08:58:33 +00003175 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00003176 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00003177
3178 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00003179 // If the source is a constant, use a default-on diagnostic.
3180 // TODO: this should happen for bitfield stores, too.
3181 llvm::APSInt Value(32);
3182 if (E->isIntegerConstantExpr(Value, S.Context)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003183 if (isFromSystemMacro(S, CC))
3184 return;
3185
John McCall091f23f2010-11-09 22:22:12 +00003186 std::string PrettySourceValue = Value.toString(10);
3187 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
3188
3189 S.Diag(E->getExprLoc(), diag::warn_impcast_integer_precision_constant)
3190 << PrettySourceValue << PrettyTargetValue
3191 << E->getType() << T << E->getSourceRange() << clang::SourceRange(CC);
3192 return;
3193 }
3194
Chris Lattnerb792b302011-06-14 04:51:15 +00003195 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
Ted Kremenekef9ff882011-03-10 20:03:42 +00003196 if (isFromSystemMacro(S, CC))
3197 return;
3198
John McCallf2370c92010-01-06 05:24:50 +00003199 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCallb4eb64d2010-10-08 02:01:28 +00003200 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32);
3201 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00003202 }
3203
3204 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
3205 (!TargetRange.NonNegative && SourceRange.NonNegative &&
3206 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003207
3208 if (isFromSystemMacro(S, CC))
3209 return;
3210
John McCall323ed742010-05-06 08:58:33 +00003211 unsigned DiagID = diag::warn_impcast_integer_sign;
3212
3213 // Traditionally, gcc has warned about this under -Wsign-compare.
3214 // We also want to warn about it in -Wconversion.
3215 // So if -Wconversion is off, use a completely identical diagnostic
3216 // in the sign-compare group.
3217 // The conditional-checking code will
3218 if (ICContext) {
3219 DiagID = diag::warn_impcast_integer_sign_conditional;
3220 *ICContext = true;
3221 }
3222
John McCallb4eb64d2010-10-08 02:01:28 +00003223 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00003224 }
3225
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003226 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003227 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
3228 // type, to give us better diagnostics.
3229 QualType SourceType = E->getType();
3230 if (!S.getLangOptions().CPlusPlus) {
3231 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3232 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3233 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
3234 SourceType = S.Context.getTypeDeclType(Enum);
3235 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
3236 }
3237 }
3238
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003239 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
3240 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
3241 if ((SourceEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00003242 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003243 (TargetEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00003244 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00003245 SourceEnum != TargetEnum) {
3246 if (isFromSystemMacro(S, CC))
3247 return;
3248
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003249 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003250 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003251 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003252
John McCall51313c32010-01-04 23:31:57 +00003253 return;
3254}
3255
John McCall323ed742010-05-06 08:58:33 +00003256void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
3257
3258void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00003259 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00003260 E = E->IgnoreParenImpCasts();
3261
3262 if (isa<ConditionalOperator>(E))
3263 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
3264
John McCallb4eb64d2010-10-08 02:01:28 +00003265 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003266 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00003267 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00003268 return;
3269}
3270
3271void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00003272 SourceLocation CC = E->getQuestionLoc();
3273
3274 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00003275
3276 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00003277 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
3278 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003279
3280 // If -Wconversion would have warned about either of the candidates
3281 // for a signedness conversion to the context type...
3282 if (!Suspicious) return;
3283
3284 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003285 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
3286 CC))
John McCall323ed742010-05-06 08:58:33 +00003287 return;
3288
John McCall323ed742010-05-06 08:58:33 +00003289 // ...then check whether it would have warned about either of the
3290 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00003291 if (E->getType() == T) return;
3292
3293 Suspicious = false;
3294 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
3295 E->getType(), CC, &Suspicious);
3296 if (!Suspicious)
3297 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00003298 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003299}
3300
3301/// AnalyzeImplicitConversions - Find and report any interesting
3302/// implicit conversions in the given expression. There are a couple
3303/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00003304void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00003305 QualType T = OrigE->getType();
3306 Expr *E = OrigE->IgnoreParenImpCasts();
3307
3308 // For conditional operators, we analyze the arguments as if they
3309 // were being fed directly into the output.
3310 if (isa<ConditionalOperator>(E)) {
3311 ConditionalOperator *CO = cast<ConditionalOperator>(E);
3312 CheckConditionalOperator(S, CO, T);
3313 return;
3314 }
3315
3316 // Go ahead and check any implicit conversions we might have skipped.
3317 // The non-canonical typecheck is just an optimization;
3318 // CheckImplicitConversion will filter out dead implicit conversions.
3319 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00003320 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00003321
3322 // Now continue drilling into this expression.
3323
3324 // Skip past explicit casts.
3325 if (isa<ExplicitCastExpr>(E)) {
3326 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00003327 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003328 }
3329
John McCallbeb22aa2010-11-09 23:24:47 +00003330 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3331 // Do a somewhat different check with comparison operators.
3332 if (BO->isComparisonOp())
3333 return AnalyzeComparison(S, BO);
3334
3335 // And with assignments and compound assignments.
3336 if (BO->isAssignmentOp())
3337 return AnalyzeAssignment(S, BO);
3338 }
John McCall323ed742010-05-06 08:58:33 +00003339
3340 // These break the otherwise-useful invariant below. Fortunately,
3341 // we don't really need to recurse into them, because any internal
3342 // expressions should have been analyzed already when they were
3343 // built into statements.
3344 if (isa<StmtExpr>(E)) return;
3345
3346 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003347 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00003348
3349 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00003350 CC = E->getExprLoc();
John McCall7502c1d2011-02-13 04:07:26 +00003351 for (Stmt::child_range I = E->children(); I; ++I)
John McCallb4eb64d2010-10-08 02:01:28 +00003352 AnalyzeImplicitConversions(S, cast<Expr>(*I), CC);
John McCall323ed742010-05-06 08:58:33 +00003353}
3354
3355} // end anonymous namespace
3356
3357/// Diagnoses "dangerous" implicit conversions within the given
3358/// expression (which is a full expression). Implements -Wconversion
3359/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00003360///
3361/// \param CC the "context" location of the implicit conversion, i.e.
3362/// the most location of the syntactic entity requiring the implicit
3363/// conversion
3364void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00003365 // Don't diagnose in unevaluated contexts.
3366 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
3367 return;
3368
3369 // Don't diagnose for value- or type-dependent expressions.
3370 if (E->isTypeDependent() || E->isValueDependent())
3371 return;
3372
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003373 // Check for array bounds violations in cases where the check isn't triggered
3374 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
3375 // ArraySubscriptExpr is on the RHS of a variable initialization.
3376 CheckArrayAccess(E);
3377
John McCallb4eb64d2010-10-08 02:01:28 +00003378 // This is not the right CC for (e.g.) a variable initialization.
3379 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003380}
3381
John McCall15d7d122010-11-11 03:21:53 +00003382void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
3383 FieldDecl *BitField,
3384 Expr *Init) {
3385 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
3386}
3387
Mike Stumpf8c49212010-01-21 03:59:47 +00003388/// CheckParmsForFunctionDef - Check that the parameters of the given
3389/// function are appropriate for the definition of a function. This
3390/// takes care of any checks that cannot be performed on the
3391/// declaration itself, e.g., that the types of each of the function
3392/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00003393bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
3394 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00003395 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00003396 for (; P != PEnd; ++P) {
3397 ParmVarDecl *Param = *P;
3398
Mike Stumpf8c49212010-01-21 03:59:47 +00003399 // C99 6.7.5.3p4: the parameters in a parameter type list in a
3400 // function declarator that is part of a function definition of
3401 // that function shall not have incomplete type.
3402 //
3403 // This is also C++ [dcl.fct]p6.
3404 if (!Param->isInvalidDecl() &&
3405 RequireCompleteType(Param->getLocation(), Param->getType(),
3406 diag::err_typecheck_decl_incomplete_type)) {
3407 Param->setInvalidDecl();
3408 HasInvalidParm = true;
3409 }
3410
3411 // C99 6.9.1p5: If the declarator includes a parameter type list, the
3412 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00003413 if (CheckParameterNames &&
3414 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00003415 !Param->isImplicit() &&
3416 !getLangOptions().CPlusPlus)
3417 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00003418
3419 // C99 6.7.5.3p12:
3420 // If the function declarator is not part of a definition of that
3421 // function, parameters may have incomplete type and may use the [*]
3422 // notation in their sequences of declarator specifiers to specify
3423 // variable length array types.
3424 QualType PType = Param->getOriginalType();
3425 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
3426 if (AT->getSizeModifier() == ArrayType::Star) {
3427 // FIXME: This diagnosic should point the the '[*]' if source-location
3428 // information is added for it.
3429 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
3430 }
3431 }
Mike Stumpf8c49212010-01-21 03:59:47 +00003432 }
3433
3434 return HasInvalidParm;
3435}
John McCallb7f4ffe2010-08-12 21:44:57 +00003436
3437/// CheckCastAlign - Implements -Wcast-align, which warns when a
3438/// pointer cast increases the alignment requirements.
3439void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
3440 // This is actually a lot of work to potentially be doing on every
3441 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003442 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
3443 TRange.getBegin())
John McCallb7f4ffe2010-08-12 21:44:57 +00003444 == Diagnostic::Ignored)
3445 return;
3446
3447 // Ignore dependent types.
3448 if (T->isDependentType() || Op->getType()->isDependentType())
3449 return;
3450
3451 // Require that the destination be a pointer type.
3452 const PointerType *DestPtr = T->getAs<PointerType>();
3453 if (!DestPtr) return;
3454
3455 // If the destination has alignment 1, we're done.
3456 QualType DestPointee = DestPtr->getPointeeType();
3457 if (DestPointee->isIncompleteType()) return;
3458 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
3459 if (DestAlign.isOne()) return;
3460
3461 // Require that the source be a pointer type.
3462 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
3463 if (!SrcPtr) return;
3464 QualType SrcPointee = SrcPtr->getPointeeType();
3465
3466 // Whitelist casts from cv void*. We already implicitly
3467 // whitelisted casts to cv void*, since they have alignment 1.
3468 // Also whitelist casts involving incomplete types, which implicitly
3469 // includes 'void'.
3470 if (SrcPointee->isIncompleteType()) return;
3471
3472 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
3473 if (SrcAlign >= DestAlign) return;
3474
3475 Diag(TRange.getBegin(), diag::warn_cast_align)
3476 << Op->getType() << T
3477 << static_cast<unsigned>(SrcAlign.getQuantity())
3478 << static_cast<unsigned>(DestAlign.getQuantity())
3479 << TRange << Op->getSourceRange();
3480}
3481
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003482static const Type* getElementType(const Expr *BaseExpr) {
3483 const Type* EltType = BaseExpr->getType().getTypePtr();
3484 if (EltType->isAnyPointerType())
3485 return EltType->getPointeeType().getTypePtr();
3486 else if (EltType->isArrayType())
3487 return EltType->getBaseElementTypeUnsafe();
3488 return EltType;
3489}
3490
Chandler Carruthc2684342011-08-05 09:10:50 +00003491/// \brief Check whether this array fits the idiom of a size-one tail padded
3492/// array member of a struct.
3493///
3494/// We avoid emitting out-of-bounds access warnings for such arrays as they are
3495/// commonly used to emulate flexible arrays in C89 code.
3496static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
3497 const NamedDecl *ND) {
3498 if (Size != 1 || !ND) return false;
3499
3500 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
3501 if (!FD) return false;
3502
3503 // Don't consider sizes resulting from macro expansions or template argument
3504 // substitution to form C89 tail-padded arrays.
3505 ConstantArrayTypeLoc TL =
3506 cast<ConstantArrayTypeLoc>(FD->getTypeSourceInfo()->getTypeLoc());
3507 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(TL.getSizeExpr());
3508 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
3509 return false;
3510
3511 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
3512 if (!RD || !RD->isStruct())
3513 return false;
3514
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00003515 // See if this is the last field decl in the record.
3516 const Decl *D = FD;
3517 while ((D = D->getNextDeclInContext()))
3518 if (isa<FieldDecl>(D))
3519 return false;
3520 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00003521}
3522
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003523void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
3524 bool isSubscript, bool AllowOnePastEnd) {
3525 const Type* EffectiveType = getElementType(BaseExpr);
3526 BaseExpr = BaseExpr->IgnoreParenCasts();
3527 IndexExpr = IndexExpr->IgnoreParenCasts();
3528
Chandler Carruth34064582011-02-17 20:55:08 +00003529 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003530 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00003531 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00003532 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00003533
Chandler Carruth34064582011-02-17 20:55:08 +00003534 if (IndexExpr->isValueDependent())
Ted Kremeneka0125d82011-02-16 01:57:07 +00003535 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003536 llvm::APSInt index;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003537 if (!IndexExpr->isIntegerConstantExpr(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00003538 return;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00003539
Chandler Carruthba447122011-08-05 08:07:29 +00003540 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00003541 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
3542 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00003543 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00003544 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00003545
Ted Kremenek9e060ca2011-02-23 23:06:04 +00003546 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00003547 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00003548 if (!size.isStrictlyPositive())
3549 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003550
3551 const Type* BaseType = getElementType(BaseExpr);
3552 if (!isSubscript && BaseType != EffectiveType) {
3553 // Make sure we're comparing apples to apples when comparing index to size
3554 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
3555 uint64_t array_typesize = Context.getTypeSize(BaseType);
3556 if (ptrarith_typesize != array_typesize) {
3557 // There's a cast to a different size type involved
3558 uint64_t ratio = array_typesize / ptrarith_typesize;
3559 // TODO: Be smarter about handling cases where array_typesize is not a
3560 // multiple of ptrarith_typesize
3561 if (ptrarith_typesize * ratio == array_typesize)
3562 size *= llvm::APInt(size.getBitWidth(), ratio);
3563 }
3564 }
3565
Chandler Carruth34064582011-02-17 20:55:08 +00003566 if (size.getBitWidth() > index.getBitWidth())
3567 index = index.sext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00003568 else if (size.getBitWidth() < index.getBitWidth())
3569 size = size.sext(index.getBitWidth());
3570
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003571 // For array subscripting the index must be less than size, but for pointer
3572 // arithmetic also allow the index (offset) to be equal to size since
3573 // computing the next address after the end of the array is legal and
3574 // commonly done e.g. in C++ iterators and range-based for loops.
3575 if (AllowOnePastEnd ? index.sle(size) : index.slt(size))
Chandler Carruthba447122011-08-05 08:07:29 +00003576 return;
3577
3578 // Also don't warn for arrays of size 1 which are members of some
3579 // structure. These are often used to approximate flexible arrays in C89
3580 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003581 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00003582 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003583
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003584 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
3585 if (isSubscript)
3586 DiagID = diag::warn_array_index_exceeds_bounds;
3587
3588 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
3589 PDiag(DiagID) << index.toString(10, true)
3590 << size.toString(10, true)
3591 << (unsigned)size.getLimitedValue(~0U)
3592 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00003593 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003594 unsigned DiagID = diag::warn_array_index_precedes_bounds;
3595 if (!isSubscript) {
3596 DiagID = diag::warn_ptr_arith_precedes_bounds;
3597 if (index.isNegative()) index = -index;
3598 }
3599
3600 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
3601 PDiag(DiagID) << index.toString(10, true)
3602 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00003603 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00003604
Chandler Carruth35001ca2011-02-17 21:10:52 +00003605 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003606 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
3607 PDiag(diag::note_array_index_out_of_bounds)
3608 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00003609}
3610
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003611void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003612 int AllowOnePastEnd = 0;
3613 while (expr) {
3614 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003615 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003616 case Stmt::ArraySubscriptExprClass: {
3617 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
3618 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), true,
3619 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003620 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003621 }
3622 case Stmt::UnaryOperatorClass: {
3623 // Only unwrap the * and & unary operators
3624 const UnaryOperator *UO = cast<UnaryOperator>(expr);
3625 expr = UO->getSubExpr();
3626 switch (UO->getOpcode()) {
3627 case UO_AddrOf:
3628 AllowOnePastEnd++;
3629 break;
3630 case UO_Deref:
3631 AllowOnePastEnd--;
3632 break;
3633 default:
3634 return;
3635 }
3636 break;
3637 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003638 case Stmt::ConditionalOperatorClass: {
3639 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
3640 if (const Expr *lhs = cond->getLHS())
3641 CheckArrayAccess(lhs);
3642 if (const Expr *rhs = cond->getRHS())
3643 CheckArrayAccess(rhs);
3644 return;
3645 }
3646 default:
3647 return;
3648 }
Peter Collingbournef111d932011-04-15 00:35:48 +00003649 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003650}
John McCallf85e1932011-06-15 23:02:42 +00003651
3652//===--- CHECK: Objective-C retain cycles ----------------------------------//
3653
3654namespace {
3655 struct RetainCycleOwner {
3656 RetainCycleOwner() : Variable(0), Indirect(false) {}
3657 VarDecl *Variable;
3658 SourceRange Range;
3659 SourceLocation Loc;
3660 bool Indirect;
3661
3662 void setLocsFrom(Expr *e) {
3663 Loc = e->getExprLoc();
3664 Range = e->getSourceRange();
3665 }
3666 };
3667}
3668
3669/// Consider whether capturing the given variable can possibly lead to
3670/// a retain cycle.
3671static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
3672 // In ARC, it's captured strongly iff the variable has __strong
3673 // lifetime. In MRR, it's captured strongly if the variable is
3674 // __block and has an appropriate type.
3675 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
3676 return false;
3677
3678 owner.Variable = var;
3679 owner.setLocsFrom(ref);
3680 return true;
3681}
3682
3683static bool findRetainCycleOwner(Expr *e, RetainCycleOwner &owner) {
3684 while (true) {
3685 e = e->IgnoreParens();
3686 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
3687 switch (cast->getCastKind()) {
3688 case CK_BitCast:
3689 case CK_LValueBitCast:
3690 case CK_LValueToRValue:
John McCall7e5e5f42011-07-07 06:58:02 +00003691 case CK_ObjCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00003692 e = cast->getSubExpr();
3693 continue;
3694
3695 case CK_GetObjCProperty: {
3696 // Bail out if this isn't a strong explicit property.
3697 const ObjCPropertyRefExpr *pre = cast->getSubExpr()->getObjCProperty();
3698 if (pre->isImplicitProperty()) return false;
3699 ObjCPropertyDecl *property = pre->getExplicitProperty();
3700 if (!(property->getPropertyAttributes() &
3701 (ObjCPropertyDecl::OBJC_PR_retain |
3702 ObjCPropertyDecl::OBJC_PR_copy |
3703 ObjCPropertyDecl::OBJC_PR_strong)) &&
3704 !(property->getPropertyIvarDecl() &&
3705 property->getPropertyIvarDecl()->getType()
3706 .getObjCLifetime() == Qualifiers::OCL_Strong))
3707 return false;
3708
3709 owner.Indirect = true;
3710 e = const_cast<Expr*>(pre->getBase());
3711 continue;
3712 }
3713
3714 default:
3715 return false;
3716 }
3717 }
3718
3719 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
3720 ObjCIvarDecl *ivar = ref->getDecl();
3721 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
3722 return false;
3723
3724 // Try to find a retain cycle in the base.
3725 if (!findRetainCycleOwner(ref->getBase(), owner))
3726 return false;
3727
3728 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
3729 owner.Indirect = true;
3730 return true;
3731 }
3732
3733 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
3734 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
3735 if (!var) return false;
3736 return considerVariable(var, ref, owner);
3737 }
3738
3739 if (BlockDeclRefExpr *ref = dyn_cast<BlockDeclRefExpr>(e)) {
3740 owner.Variable = ref->getDecl();
3741 owner.setLocsFrom(ref);
3742 return true;
3743 }
3744
3745 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
3746 if (member->isArrow()) return false;
3747
3748 // Don't count this as an indirect ownership.
3749 e = member->getBase();
3750 continue;
3751 }
3752
3753 // Array ivars?
3754
3755 return false;
3756 }
3757}
3758
3759namespace {
3760 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
3761 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
3762 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
3763 Variable(variable), Capturer(0) {}
3764
3765 VarDecl *Variable;
3766 Expr *Capturer;
3767
3768 void VisitDeclRefExpr(DeclRefExpr *ref) {
3769 if (ref->getDecl() == Variable && !Capturer)
3770 Capturer = ref;
3771 }
3772
3773 void VisitBlockDeclRefExpr(BlockDeclRefExpr *ref) {
3774 if (ref->getDecl() == Variable && !Capturer)
3775 Capturer = ref;
3776 }
3777
3778 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
3779 if (Capturer) return;
3780 Visit(ref->getBase());
3781 if (Capturer && ref->isFreeIvar())
3782 Capturer = ref;
3783 }
3784
3785 void VisitBlockExpr(BlockExpr *block) {
3786 // Look inside nested blocks
3787 if (block->getBlockDecl()->capturesVariable(Variable))
3788 Visit(block->getBlockDecl()->getBody());
3789 }
3790 };
3791}
3792
3793/// Check whether the given argument is a block which captures a
3794/// variable.
3795static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
3796 assert(owner.Variable && owner.Loc.isValid());
3797
3798 e = e->IgnoreParenCasts();
3799 BlockExpr *block = dyn_cast<BlockExpr>(e);
3800 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
3801 return 0;
3802
3803 FindCaptureVisitor visitor(S.Context, owner.Variable);
3804 visitor.Visit(block->getBlockDecl()->getBody());
3805 return visitor.Capturer;
3806}
3807
3808static void diagnoseRetainCycle(Sema &S, Expr *capturer,
3809 RetainCycleOwner &owner) {
3810 assert(capturer);
3811 assert(owner.Variable && owner.Loc.isValid());
3812
3813 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
3814 << owner.Variable << capturer->getSourceRange();
3815 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
3816 << owner.Indirect << owner.Range;
3817}
3818
3819/// Check for a keyword selector that starts with the word 'add' or
3820/// 'set'.
3821static bool isSetterLikeSelector(Selector sel) {
3822 if (sel.isUnarySelector()) return false;
3823
Chris Lattner5f9e2722011-07-23 10:55:15 +00003824 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00003825 while (!str.empty() && str.front() == '_') str = str.substr(1);
3826 if (str.startswith("set") || str.startswith("add"))
3827 str = str.substr(3);
3828 else
3829 return false;
3830
3831 if (str.empty()) return true;
3832 return !islower(str.front());
3833}
3834
3835/// Check a message send to see if it's likely to cause a retain cycle.
3836void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
3837 // Only check instance methods whose selector looks like a setter.
3838 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
3839 return;
3840
3841 // Try to find a variable that the receiver is strongly owned by.
3842 RetainCycleOwner owner;
3843 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
3844 if (!findRetainCycleOwner(msg->getInstanceReceiver(), owner))
3845 return;
3846 } else {
3847 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
3848 owner.Variable = getCurMethodDecl()->getSelfDecl();
3849 owner.Loc = msg->getSuperLoc();
3850 owner.Range = msg->getSuperLoc();
3851 }
3852
3853 // Check whether the receiver is captured by any of the arguments.
3854 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
3855 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
3856 return diagnoseRetainCycle(*this, capturer, owner);
3857}
3858
3859/// Check a property assign to see if it's likely to cause a retain cycle.
3860void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
3861 RetainCycleOwner owner;
3862 if (!findRetainCycleOwner(receiver, owner))
3863 return;
3864
3865 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
3866 diagnoseRetainCycle(*this, capturer, owner);
3867}
3868
Fariborz Jahanian921c1432011-06-24 18:25:34 +00003869bool Sema::checkUnsafeAssigns(SourceLocation Loc,
John McCallf85e1932011-06-15 23:02:42 +00003870 QualType LHS, Expr *RHS) {
3871 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
3872 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
Fariborz Jahanian921c1432011-06-24 18:25:34 +00003873 return false;
3874 // strip off any implicit cast added to get to the one arc-specific
3875 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
3876 if (cast->getCastKind() == CK_ObjCConsumeObject) {
John McCallf85e1932011-06-15 23:02:42 +00003877 Diag(Loc, diag::warn_arc_retained_assign)
3878 << (LT == Qualifiers::OCL_ExplicitNone)
3879 << RHS->getSourceRange();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00003880 return true;
3881 }
3882 RHS = cast->getSubExpr();
3883 }
3884 return false;
John McCallf85e1932011-06-15 23:02:42 +00003885}
3886
Fariborz Jahanian921c1432011-06-24 18:25:34 +00003887void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
3888 Expr *LHS, Expr *RHS) {
3889 QualType LHSType = LHS->getType();
3890 if (checkUnsafeAssigns(Loc, LHSType, RHS))
3891 return;
3892 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
3893 // FIXME. Check for other life times.
3894 if (LT != Qualifiers::OCL_None)
3895 return;
3896
3897 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(LHS)) {
3898 if (PRE->isImplicitProperty())
3899 return;
3900 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
3901 if (!PD)
3902 return;
3903
3904 unsigned Attributes = PD->getPropertyAttributes();
3905 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign)
3906 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
3907 if (cast->getCastKind() == CK_ObjCConsumeObject) {
3908 Diag(Loc, diag::warn_arc_retained_property_assign)
3909 << RHS->getSourceRange();
3910 return;
3911 }
3912 RHS = cast->getSubExpr();
3913 }
3914 }
3915}