blob: 54900e0cf15c095a1979b725317be498765ac2e9 [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
Douglas Gregor06bc9eb2011-05-03 20:37:33 +0000322 // Memset/memcpy/memmove 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
343 default:
344 if (FDecl->getLinkage() == ExternalLinkage &&
345 (!getLangOptions().CPlusPlus || FDecl->isExternC())) {
346 if (FnInfo->isStr("memset"))
347 CMF = CMF_Memset;
348 else if (FnInfo->isStr("memcpy"))
349 CMF = CMF_Memcpy;
350 else if (FnInfo->isStr("memmove"))
351 CMF = CMF_Memmove;
352 }
353 break;
Douglas Gregor06bc9eb2011-05-03 20:37:33 +0000354 }
Douglas Gregor707a23e2011-06-16 17:56:04 +0000355
356 if (CMF != -1)
357 CheckMemsetcpymoveArguments(TheCall, CheckedMemoryFunction(CMF), FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000358
Anders Carlssond406bf02009-08-16 01:56:34 +0000359 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000360}
361
Anders Carlssond406bf02009-08-16 01:56:34 +0000362bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000363 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000364 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000365 if (!Format)
Anders Carlssond406bf02009-08-16 01:56:34 +0000366 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000367
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000368 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
369 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000370 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000371
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000372 QualType Ty = V->getType();
373 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000374 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000375
Ted Kremenek826a3452010-07-16 02:11:22 +0000376 const bool b = Format->getType() == "scanf";
377 if (!b && !CheckablePrintfAttr(Format, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +0000378 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000379
Anders Carlssond406bf02009-08-16 01:56:34 +0000380 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek826a3452010-07-16 02:11:22 +0000381 CheckPrintfScanfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
382 HasVAListArg ? 0 : Format->getFirstArg() - 1, !b);
Anders Carlssond406bf02009-08-16 01:56:34 +0000383
384 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000385}
386
Chris Lattner5caa3702009-05-08 06:58:22 +0000387/// SemaBuiltinAtomicOverloaded - We have a call to a function like
388/// __sync_fetch_and_add, which is an overloaded function based on the pointer
389/// type of its first argument. The main ActOnCallExpr routines have already
390/// promoted the types of arguments because all of these calls are prototyped as
391/// void(...).
392///
393/// This function goes through and does final semantic checking for these
394/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000395ExprResult
396Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000397 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000398 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
399 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
400
401 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000402 if (TheCall->getNumArgs() < 1) {
403 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
404 << 0 << 1 << TheCall->getNumArgs()
405 << TheCall->getCallee()->getSourceRange();
406 return ExprError();
407 }
Mike Stump1eb44332009-09-09 15:08:12 +0000408
Chris Lattner5caa3702009-05-08 06:58:22 +0000409 // Inspect the first argument of the atomic builtin. This should always be
410 // a pointer type, whose element is an integral scalar or pointer type.
411 // Because it is a pointer type, we don't have to worry about any implicit
412 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000413 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000414 Expr *FirstArg = TheCall->getArg(0);
John McCallf85e1932011-06-15 23:02:42 +0000415 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
416 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000417 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
418 << FirstArg->getType() << FirstArg->getSourceRange();
419 return ExprError();
420 }
Mike Stump1eb44332009-09-09 15:08:12 +0000421
John McCallf85e1932011-06-15 23:02:42 +0000422 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000423 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000424 !ValType->isBlockPointerType()) {
425 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
426 << FirstArg->getType() << FirstArg->getSourceRange();
427 return ExprError();
428 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000429
John McCallf85e1932011-06-15 23:02:42 +0000430 switch (ValType.getObjCLifetime()) {
431 case Qualifiers::OCL_None:
432 case Qualifiers::OCL_ExplicitNone:
433 // okay
434 break;
435
436 case Qualifiers::OCL_Weak:
437 case Qualifiers::OCL_Strong:
438 case Qualifiers::OCL_Autoreleasing:
439 Diag(DRE->getLocStart(), diag::err_arc_atomic_lifetime)
440 << ValType << FirstArg->getSourceRange();
441 return ExprError();
442 }
443
Chandler Carruth8d13d222010-07-18 20:54:12 +0000444 // The majority of builtins return a value, but a few have special return
445 // types, so allow them to override appropriately below.
446 QualType ResultType = ValType;
447
Chris Lattner5caa3702009-05-08 06:58:22 +0000448 // We need to figure out which concrete builtin this maps onto. For example,
449 // __sync_fetch_and_add with a 2 byte object turns into
450 // __sync_fetch_and_add_2.
451#define BUILTIN_ROW(x) \
452 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
453 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000454
Chris Lattner5caa3702009-05-08 06:58:22 +0000455 static const unsigned BuiltinIndices[][5] = {
456 BUILTIN_ROW(__sync_fetch_and_add),
457 BUILTIN_ROW(__sync_fetch_and_sub),
458 BUILTIN_ROW(__sync_fetch_and_or),
459 BUILTIN_ROW(__sync_fetch_and_and),
460 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +0000461
Chris Lattner5caa3702009-05-08 06:58:22 +0000462 BUILTIN_ROW(__sync_add_and_fetch),
463 BUILTIN_ROW(__sync_sub_and_fetch),
464 BUILTIN_ROW(__sync_and_and_fetch),
465 BUILTIN_ROW(__sync_or_and_fetch),
466 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000467
Chris Lattner5caa3702009-05-08 06:58:22 +0000468 BUILTIN_ROW(__sync_val_compare_and_swap),
469 BUILTIN_ROW(__sync_bool_compare_and_swap),
470 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +0000471 BUILTIN_ROW(__sync_lock_release),
472 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +0000473 };
Mike Stump1eb44332009-09-09 15:08:12 +0000474#undef BUILTIN_ROW
475
Chris Lattner5caa3702009-05-08 06:58:22 +0000476 // Determine the index of the size.
477 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000478 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000479 case 1: SizeIndex = 0; break;
480 case 2: SizeIndex = 1; break;
481 case 4: SizeIndex = 2; break;
482 case 8: SizeIndex = 3; break;
483 case 16: SizeIndex = 4; break;
484 default:
Chandler Carruthd2014572010-07-09 18:59:35 +0000485 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
486 << FirstArg->getType() << FirstArg->getSourceRange();
487 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +0000488 }
Mike Stump1eb44332009-09-09 15:08:12 +0000489
Chris Lattner5caa3702009-05-08 06:58:22 +0000490 // Each of these builtins has one pointer argument, followed by some number of
491 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
492 // that we ignore. Find out which row of BuiltinIndices to read from as well
493 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000494 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000495 unsigned BuiltinIndex, NumFixed = 1;
496 switch (BuiltinID) {
497 default: assert(0 && "Unknown overloaded atomic builtin!");
498 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
499 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
500 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
501 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
502 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000503
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000504 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
505 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
506 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
507 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 8; break;
508 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000509
Chris Lattner5caa3702009-05-08 06:58:22 +0000510 case Builtin::BI__sync_val_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000511 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +0000512 NumFixed = 2;
513 break;
514 case Builtin::BI__sync_bool_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000515 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +0000516 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000517 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000518 break;
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000519 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000520 case Builtin::BI__sync_lock_release:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000521 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000522 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000523 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000524 break;
Chris Lattner23aa9c82011-04-09 03:57:26 +0000525 case Builtin::BI__sync_swap: BuiltinIndex = 14; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000526 }
Mike Stump1eb44332009-09-09 15:08:12 +0000527
Chris Lattner5caa3702009-05-08 06:58:22 +0000528 // Now that we know how many fixed arguments we expect, first check that we
529 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +0000530 if (TheCall->getNumArgs() < 1+NumFixed) {
531 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
532 << 0 << 1+NumFixed << TheCall->getNumArgs()
533 << TheCall->getCallee()->getSourceRange();
534 return ExprError();
535 }
Mike Stump1eb44332009-09-09 15:08:12 +0000536
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000537 // Get the decl for the concrete builtin from this, we can tell what the
538 // concrete integer type we should convert to is.
539 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
540 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
541 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +0000542 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000543 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
544 TUScope, false, DRE->getLocStart()));
Chandler Carruthd2014572010-07-09 18:59:35 +0000545
John McCallf871d0c2010-08-07 06:22:56 +0000546 // The first argument --- the pointer --- has a fixed type; we
547 // deduce the types of the rest of the arguments accordingly. Walk
548 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +0000549 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +0000550 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +0000551
Chris Lattner5caa3702009-05-08 06:58:22 +0000552 // If the argument is an implicit cast, then there was a promotion due to
553 // "...", just remove it now.
John Wiegley429bb272011-04-08 18:41:53 +0000554 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg.get())) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000555 Arg = ICE->getSubExpr();
556 ICE->setSubExpr(0);
John Wiegley429bb272011-04-08 18:41:53 +0000557 TheCall->setArg(i+1, Arg.get());
Chris Lattner5caa3702009-05-08 06:58:22 +0000558 }
Mike Stump1eb44332009-09-09 15:08:12 +0000559
Chris Lattner5caa3702009-05-08 06:58:22 +0000560 // GCC does an implicit conversion to the pointer or integer ValType. This
561 // can fail in some cases (1i -> int**), check for this error case now.
John McCalldaa8e4e2010-11-15 09:13:47 +0000562 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +0000563 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +0000564 CXXCastPath BasePath;
John McCallf85e1932011-06-15 23:02:42 +0000565 Arg = CheckCastTypes(Arg.get()->getLocStart(), Arg.get()->getSourceRange(),
566 ValType, Arg.take(), Kind, VK, BasePath);
John Wiegley429bb272011-04-08 18:41:53 +0000567 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +0000568 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000569
Chris Lattner5caa3702009-05-08 06:58:22 +0000570 // Okay, we have something that *can* be converted to the right type. Check
571 // to see if there is a potentially weird extension going on here. This can
572 // happen when you do an atomic operation on something like an char* and
573 // pass in 42. The 42 gets converted to char. This is even more strange
574 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +0000575 // FIXME: Do this check.
John Wiegley429bb272011-04-08 18:41:53 +0000576 Arg = ImpCastExprToType(Arg.take(), ValType, Kind, VK, &BasePath);
577 TheCall->setArg(i+1, Arg.get());
Chris Lattner5caa3702009-05-08 06:58:22 +0000578 }
Mike Stump1eb44332009-09-09 15:08:12 +0000579
Chris Lattner5caa3702009-05-08 06:58:22 +0000580 // Switch the DeclRefExpr to refer to the new decl.
581 DRE->setDecl(NewBuiltinDecl);
582 DRE->setType(NewBuiltinDecl->getType());
Mike Stump1eb44332009-09-09 15:08:12 +0000583
Chris Lattner5caa3702009-05-08 06:58:22 +0000584 // Set the callee in the CallExpr.
585 // FIXME: This leaks the original parens and implicit casts.
John Wiegley429bb272011-04-08 18:41:53 +0000586 ExprResult PromotedCall = UsualUnaryConversions(DRE);
587 if (PromotedCall.isInvalid())
588 return ExprError();
589 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +0000590
Chandler Carruthdb4325b2010-07-18 07:23:17 +0000591 // Change the result type of the call to match the original value type. This
592 // is arbitrary, but the codegen for these builtins ins design to handle it
593 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +0000594 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +0000595
596 return move(TheCallResult);
Chris Lattner5caa3702009-05-08 06:58:22 +0000597}
598
599
Chris Lattner69039812009-02-18 06:01:06 +0000600/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000601/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +0000602/// Note: It might also make sense to do the UTF-16 conversion here (would
603/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +0000604bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000605 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000606 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
607
608 if (!Literal || Literal->isWide()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000609 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
610 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000611 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000612 }
Mike Stump1eb44332009-09-09 15:08:12 +0000613
Fariborz Jahanian7da71022010-09-07 19:38:13 +0000614 if (Literal->containsNonAsciiOrNull()) {
615 llvm::StringRef String = Literal->getString();
616 unsigned NumBytes = String.size();
617 llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
618 const UTF8 *FromPtr = (UTF8 *)String.data();
619 UTF16 *ToPtr = &ToBuf[0];
620
621 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
622 &ToPtr, ToPtr + NumBytes,
623 strictConversion);
624 // Check for conversion failure.
625 if (Result != conversionOK)
626 Diag(Arg->getLocStart(),
627 diag::warn_cfstring_truncated) << Arg->getSourceRange();
628 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000629 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000630}
631
Chris Lattnerc27c6652007-12-20 00:05:45 +0000632/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
633/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000634bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
635 Expr *Fn = TheCall->getCallee();
636 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000637 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000638 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000639 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
640 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +0000641 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000642 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000643 return true;
644 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000645
646 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +0000647 return Diag(TheCall->getLocEnd(),
648 diag::err_typecheck_call_too_few_args_at_least)
649 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000650 }
651
Chris Lattnerc27c6652007-12-20 00:05:45 +0000652 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000653 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +0000654 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000655 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +0000656 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +0000657 else if (FunctionDecl *FD = getCurFunctionDecl())
658 isVariadic = FD->isVariadic();
659 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000660 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +0000661
Chris Lattnerc27c6652007-12-20 00:05:45 +0000662 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000663 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
664 return true;
665 }
Mike Stump1eb44332009-09-09 15:08:12 +0000666
Chris Lattner30ce3442007-12-19 23:59:04 +0000667 // Verify that the second argument to the builtin is the last argument of the
668 // current function or method.
669 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000670 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +0000671
Anders Carlsson88cf2262008-02-11 04:20:54 +0000672 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
673 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000674 // FIXME: This isn't correct for methods (results in bogus warning).
675 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000676 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000677 if (CurBlock)
678 LastArg = *(CurBlock->TheDecl->param_end()-1);
679 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +0000680 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000681 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000682 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000683 SecondArgIsLastNamedArgument = PV == LastArg;
684 }
685 }
Mike Stump1eb44332009-09-09 15:08:12 +0000686
Chris Lattner30ce3442007-12-19 23:59:04 +0000687 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +0000688 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000689 diag::warn_second_parameter_of_va_start_not_last_named_argument);
690 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000691}
Chris Lattner30ce3442007-12-19 23:59:04 +0000692
Chris Lattner1b9a0792007-12-20 00:26:33 +0000693/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
694/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000695bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
696 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000697 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000698 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000699 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +0000700 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000701 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000702 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000703 << SourceRange(TheCall->getArg(2)->getLocStart(),
704 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000705
John Wiegley429bb272011-04-08 18:41:53 +0000706 ExprResult OrigArg0 = TheCall->getArg(0);
707 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000708
Chris Lattner1b9a0792007-12-20 00:26:33 +0000709 // Do standard promotions between the two arguments, returning their common
710 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000711 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +0000712 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
713 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +0000714
715 // Make sure any conversions are pushed back into the call; this is
716 // type safe since unordered compare builtins are declared as "_Bool
717 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +0000718 TheCall->setArg(0, OrigArg0.get());
719 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +0000720
John Wiegley429bb272011-04-08 18:41:53 +0000721 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +0000722 return false;
723
Chris Lattner1b9a0792007-12-20 00:26:33 +0000724 // If the common type isn't a real floating type, then the arguments were
725 // invalid for this operation.
726 if (!Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +0000727 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000728 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +0000729 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
730 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000731
Chris Lattner1b9a0792007-12-20 00:26:33 +0000732 return false;
733}
734
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000735/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
736/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000737/// to check everything. We expect the last argument to be a floating point
738/// value.
739bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
740 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +0000741 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000742 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000743 if (TheCall->getNumArgs() > NumArgs)
744 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000745 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000746 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000747 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000748 (*(TheCall->arg_end()-1))->getLocEnd());
749
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000750 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +0000751
Eli Friedman9ac6f622009-08-31 20:06:00 +0000752 if (OrigArg->isTypeDependent())
753 return false;
754
Chris Lattner81368fb2010-05-06 05:50:07 +0000755 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +0000756 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000757 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000758 diag::err_typecheck_call_invalid_unary_fp)
759 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000760
Chris Lattner81368fb2010-05-06 05:50:07 +0000761 // If this is an implicit conversion from float -> double, remove it.
762 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
763 Expr *CastArg = Cast->getSubExpr();
764 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
765 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
766 "promotion from float to double is the only expected cast here");
767 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +0000768 TheCall->setArg(NumArgs-1, CastArg);
769 OrigArg = CastArg;
770 }
771 }
772
Eli Friedman9ac6f622009-08-31 20:06:00 +0000773 return false;
774}
775
Eli Friedmand38617c2008-05-14 19:38:39 +0000776/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
777// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +0000778ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000779 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000780 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +0000781 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +0000782 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +0000783 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000784
Nate Begeman37b6a572010-06-08 00:16:34 +0000785 // Determine which of the following types of shufflevector we're checking:
786 // 1) unary, vector mask: (lhs, mask)
787 // 2) binary, vector mask: (lhs, rhs, mask)
788 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
789 QualType resType = TheCall->getArg(0)->getType();
790 unsigned numElements = 0;
791
Douglas Gregorcde01732009-05-19 22:10:17 +0000792 if (!TheCall->getArg(0)->isTypeDependent() &&
793 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000794 QualType LHSType = TheCall->getArg(0)->getType();
795 QualType RHSType = TheCall->getArg(1)->getType();
796
797 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000798 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000799 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000800 TheCall->getArg(1)->getLocEnd());
801 return ExprError();
802 }
Nate Begeman37b6a572010-06-08 00:16:34 +0000803
804 numElements = LHSType->getAs<VectorType>()->getNumElements();
805 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +0000806
Nate Begeman37b6a572010-06-08 00:16:34 +0000807 // Check to see if we have a call with 2 vector arguments, the unary shuffle
808 // with mask. If so, verify that RHS is an integer vector type with the
809 // same number of elts as lhs.
810 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +0000811 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +0000812 RHSType->getAs<VectorType>()->getNumElements() != numElements)
813 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
814 << SourceRange(TheCall->getArg(1)->getLocStart(),
815 TheCall->getArg(1)->getLocEnd());
816 numResElements = numElements;
817 }
818 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000819 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000820 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000821 TheCall->getArg(1)->getLocEnd());
822 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +0000823 } else if (numElements != numResElements) {
824 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +0000825 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +0000826 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +0000827 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000828 }
829
830 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000831 if (TheCall->getArg(i)->isTypeDependent() ||
832 TheCall->getArg(i)->isValueDependent())
833 continue;
834
Nate Begeman37b6a572010-06-08 00:16:34 +0000835 llvm::APSInt Result(32);
836 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
837 return ExprError(Diag(TheCall->getLocStart(),
838 diag::err_shufflevector_nonconstant_argument)
839 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000840
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000841 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000842 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000843 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000844 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000845 }
846
847 llvm::SmallVector<Expr*, 32> exprs;
848
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000849 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000850 exprs.push_back(TheCall->getArg(i));
851 TheCall->setArg(i, 0);
852 }
853
Nate Begemana88dc302009-08-12 02:10:25 +0000854 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begeman37b6a572010-06-08 00:16:34 +0000855 exprs.size(), resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000856 TheCall->getCallee()->getLocStart(),
857 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000858}
Chris Lattner30ce3442007-12-19 23:59:04 +0000859
Daniel Dunbar4493f792008-07-21 22:59:13 +0000860/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
861// This is declared to take (const void*, ...) and can take two
862// optional constant int args.
863bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000864 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000865
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000866 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +0000867 return Diag(TheCall->getLocEnd(),
868 diag::err_typecheck_call_too_many_args_at_most)
869 << 0 /*function call*/ << 3 << NumArgs
870 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000871
872 // Argument 0 is checked for us and the remaining arguments must be
873 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000874 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000875 Expr *Arg = TheCall->getArg(i);
Eric Christopher691ebc32010-04-17 02:26:23 +0000876
Eli Friedman9aef7262009-12-04 00:30:06 +0000877 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +0000878 if (SemaBuiltinConstantArg(TheCall, i, Result))
879 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000880
Daniel Dunbar4493f792008-07-21 22:59:13 +0000881 // FIXME: gcc issues a warning and rewrites these to 0. These
882 // seems especially odd for the third argument since the default
883 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000884 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +0000885 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000886 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000887 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000888 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +0000889 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000890 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000891 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000892 }
893 }
894
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000895 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000896}
897
Eric Christopher691ebc32010-04-17 02:26:23 +0000898/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
899/// TheCall is a constant expression.
900bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
901 llvm::APSInt &Result) {
902 Expr *Arg = TheCall->getArg(ArgNum);
903 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
904 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
905
906 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
907
908 if (!Arg->isIntegerConstantExpr(Result, Context))
909 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +0000910 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +0000911
Chris Lattner21fb98e2009-09-23 06:06:36 +0000912 return false;
913}
914
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000915/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
916/// int type). This simply type checks that type is one of the defined
917/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000918// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000919bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +0000920 llvm::APSInt Result;
921
922 // Check constant-ness first.
923 if (SemaBuiltinConstantArg(TheCall, 1, Result))
924 return true;
925
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000926 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000927 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000928 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
929 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000930 }
931
932 return false;
933}
934
Eli Friedman586d6a82009-05-03 06:04:26 +0000935/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +0000936/// This checks that val is a constant 1.
937bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
938 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +0000939 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +0000940
Eric Christopher691ebc32010-04-17 02:26:23 +0000941 // TODO: This is less than ideal. Overload this to take a value.
942 if (SemaBuiltinConstantArg(TheCall, 1, Result))
943 return true;
944
945 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +0000946 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
947 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
948
949 return false;
950}
951
Ted Kremenekb43e8ad2011-02-24 23:03:04 +0000952// Handle i > 1 ? "x" : "y", recursively.
Ted Kremenek082d9362009-03-20 21:35:28 +0000953bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
954 bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +0000955 unsigned format_idx, unsigned firstDataArg,
956 bool isPrintf) {
Ted Kremenek4fe64412010-09-09 03:51:39 +0000957 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +0000958 if (E->isTypeDependent() || E->isValueDependent())
959 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000960
Peter Collingbournef111d932011-04-15 00:35:48 +0000961 E = E->IgnoreParens();
962
Ted Kremenekd30ef872009-01-12 23:09:09 +0000963 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +0000964 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +0000965 case Stmt::ConditionalOperatorClass: {
John McCall56ca35d2011-02-17 10:25:35 +0000966 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
Ted Kremenek826a3452010-07-16 02:11:22 +0000967 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg,
968 format_idx, firstDataArg, isPrintf)
John McCall56ca35d2011-02-17 10:25:35 +0000969 && SemaCheckStringLiteral(C->getFalseExpr(), TheCall, HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +0000970 format_idx, firstDataArg, isPrintf);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000971 }
972
Ted Kremenek95355bb2010-09-09 03:51:42 +0000973 case Stmt::IntegerLiteralClass:
974 // Technically -Wformat-nonliteral does not warn about this case.
975 // The behavior of printf and friends in this case is implementation
976 // dependent. Ideally if the format string cannot be null then
977 // it should have a 'nonnull' attribute in the function prototype.
978 return true;
979
Ted Kremenekd30ef872009-01-12 23:09:09 +0000980 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +0000981 E = cast<ImplicitCastExpr>(E)->getSubExpr();
982 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000983 }
984
John McCall56ca35d2011-02-17 10:25:35 +0000985 case Stmt::OpaqueValueExprClass:
986 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
987 E = src;
988 goto tryAgain;
989 }
990 return false;
991
Ted Kremenekb43e8ad2011-02-24 23:03:04 +0000992 case Stmt::PredefinedExprClass:
993 // While __func__, etc., are technically not string literals, they
994 // cannot contain format specifiers and thus are not a security
995 // liability.
996 return true;
997
Ted Kremenek082d9362009-03-20 21:35:28 +0000998 case Stmt::DeclRefExprClass: {
999 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001000
Ted Kremenek082d9362009-03-20 21:35:28 +00001001 // As an exception, do not flag errors for variables binding to
1002 // const string literals.
1003 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1004 bool isConstant = false;
1005 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001006
Ted Kremenek082d9362009-03-20 21:35:28 +00001007 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1008 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001009 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001010 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001011 PT->getPointeeType().isConstant(Context);
1012 }
Mike Stump1eb44332009-09-09 15:08:12 +00001013
Ted Kremenek082d9362009-03-20 21:35:28 +00001014 if (isConstant) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001015 if (const Expr *Init = VD->getAnyInitializer())
Ted Kremenek082d9362009-03-20 21:35:28 +00001016 return SemaCheckStringLiteral(Init, TheCall,
Ted Kremenek826a3452010-07-16 02:11:22 +00001017 HasVAListArg, format_idx, firstDataArg,
1018 isPrintf);
Ted Kremenek082d9362009-03-20 21:35:28 +00001019 }
Mike Stump1eb44332009-09-09 15:08:12 +00001020
Anders Carlssond966a552009-06-28 19:55:58 +00001021 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1022 // special check to see if the format string is a function parameter
1023 // of the function calling the printf function. If the function
1024 // has an attribute indicating it is a printf-like function, then we
1025 // should suppress warnings concerning non-literals being used in a call
1026 // to a vprintf function. For example:
1027 //
1028 // void
1029 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1030 // va_list ap;
1031 // va_start(ap, fmt);
1032 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1033 // ...
1034 //
1035 //
1036 // FIXME: We don't have full attribute support yet, so just check to see
1037 // if the argument is a DeclRefExpr that references a parameter. We'll
1038 // add proper support for checking the attribute later.
1039 if (HasVAListArg)
1040 if (isa<ParmVarDecl>(VD))
1041 return true;
Ted Kremenek082d9362009-03-20 21:35:28 +00001042 }
Mike Stump1eb44332009-09-09 15:08:12 +00001043
Ted Kremenek082d9362009-03-20 21:35:28 +00001044 return false;
1045 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001046
Anders Carlsson8f031b32009-06-27 04:05:33 +00001047 case Stmt::CallExprClass: {
1048 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001049 if (const ImplicitCastExpr *ICE
Anders Carlsson8f031b32009-06-27 04:05:33 +00001050 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
1051 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
1052 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001053 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001054 unsigned ArgIndex = FA->getFormatIdx();
1055 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001056
1057 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001058 format_idx, firstDataArg, isPrintf);
Anders Carlsson8f031b32009-06-27 04:05:33 +00001059 }
1060 }
1061 }
1062 }
Mike Stump1eb44332009-09-09 15:08:12 +00001063
Anders Carlsson8f031b32009-06-27 04:05:33 +00001064 return false;
1065 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001066 case Stmt::ObjCStringLiteralClass:
1067 case Stmt::StringLiteralClass: {
1068 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001069
Ted Kremenek082d9362009-03-20 21:35:28 +00001070 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001071 StrE = ObjCFExpr->getString();
1072 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001073 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001074
Ted Kremenekd30ef872009-01-12 23:09:09 +00001075 if (StrE) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001076 CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx,
1077 firstDataArg, isPrintf);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001078 return true;
1079 }
Mike Stump1eb44332009-09-09 15:08:12 +00001080
Ted Kremenekd30ef872009-01-12 23:09:09 +00001081 return false;
1082 }
Mike Stump1eb44332009-09-09 15:08:12 +00001083
Ted Kremenek082d9362009-03-20 21:35:28 +00001084 default:
1085 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001086 }
1087}
1088
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001089void
Mike Stump1eb44332009-09-09 15:08:12 +00001090Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001091 const Expr * const *ExprArgs,
1092 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001093 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1094 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001095 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001096 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001097 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001098 Expr::NPC_ValueDependentIsNotNull))
Nick Lewycky909a70d2011-03-25 01:44:32 +00001099 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001100 }
1101}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001102
Ted Kremenek826a3452010-07-16 02:11:22 +00001103/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1104/// functions) for correct use of format strings.
Chris Lattner59907c42007-08-10 20:18:51 +00001105void
Ted Kremenek826a3452010-07-16 02:11:22 +00001106Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
1107 unsigned format_idx, unsigned firstDataArg,
1108 bool isPrintf) {
1109
Ted Kremenek082d9362009-03-20 21:35:28 +00001110 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +00001111
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001112 // The way the format attribute works in GCC, the implicit this argument
1113 // of member functions is counted. However, it doesn't appear in our own
1114 // lists, so decrement format_idx in that case.
1115 if (isa<CXXMemberCallExpr>(TheCall)) {
Chandler Carruth9263a302010-11-16 08:49:43 +00001116 const CXXMethodDecl *method_decl =
1117 dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl());
1118 if (method_decl && method_decl->isInstance()) {
1119 // Catch a format attribute mistakenly referring to the object argument.
1120 if (format_idx == 0)
1121 return;
1122 --format_idx;
1123 if(firstDataArg != 0)
1124 --firstDataArg;
1125 }
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001126 }
1127
Ted Kremenek826a3452010-07-16 02:11:22 +00001128 // CHECK: printf/scanf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +00001129 if (format_idx >= TheCall->getNumArgs()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001130 Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001131 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001132 return;
1133 }
Mike Stump1eb44332009-09-09 15:08:12 +00001134
Ted Kremenek082d9362009-03-20 21:35:28 +00001135 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001136
Chris Lattner59907c42007-08-10 20:18:51 +00001137 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001138 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001139 // Dynamically generated format strings are difficult to
1140 // automatically vet at compile time. Requiring that format strings
1141 // are string literals: (1) permits the checking of format strings by
1142 // the compiler and thereby (2) can practically remove the source of
1143 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001144
Mike Stump1eb44332009-09-09 15:08:12 +00001145 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001146 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001147 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001148 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001149 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
Ted Kremenek826a3452010-07-16 02:11:22 +00001150 firstDataArg, isPrintf))
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001151 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001152
Chris Lattner655f1412009-04-29 04:59:47 +00001153 // If there are no arguments specified, warn with -Wformat-security, otherwise
1154 // warn only with -Wformat-nonliteral.
1155 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump1eb44332009-09-09 15:08:12 +00001156 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001157 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001158 << OrigFormatExpr->getSourceRange();
1159 else
Mike Stump1eb44332009-09-09 15:08:12 +00001160 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001161 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001162 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001163}
Ted Kremenek71895b92007-08-14 17:39:48 +00001164
Ted Kremeneke0e53132010-01-28 23:39:18 +00001165namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001166class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1167protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001168 Sema &S;
1169 const StringLiteral *FExpr;
1170 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001171 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001172 const unsigned NumDataArgs;
1173 const bool IsObjCLiteral;
1174 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001175 const bool HasVAListArg;
1176 const CallExpr *TheCall;
1177 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001178 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001179 bool usesPositionalArgs;
1180 bool atFirstArg;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001181public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001182 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001183 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001184 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001185 const char *beg, bool hasVAListArg,
1186 const CallExpr *theCall, unsigned formatIdx)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001187 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek6ee76532010-03-25 03:59:12 +00001188 FirstDataArg(firstDataArg),
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001189 NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001190 IsObjCLiteral(isObjCLiteral), Beg(beg),
1191 HasVAListArg(hasVAListArg),
Ted Kremenekefaff192010-02-27 01:41:03 +00001192 TheCall(theCall), FormatIdx(formatIdx),
1193 usesPositionalArgs(false), atFirstArg(true) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001194 CoveredArgs.resize(numDataArgs);
1195 CoveredArgs.reset();
1196 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001197
Ted Kremenek07d161f2010-01-29 01:50:07 +00001198 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001199
Ted Kremenek826a3452010-07-16 02:11:22 +00001200 void HandleIncompleteSpecifier(const char *startSpecifier,
1201 unsigned specifierLen);
1202
Ted Kremenekefaff192010-02-27 01:41:03 +00001203 virtual void HandleInvalidPosition(const char *startSpecifier,
1204 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001205 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001206
1207 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1208
Ted Kremeneke0e53132010-01-28 23:39:18 +00001209 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001210
Ted Kremenek826a3452010-07-16 02:11:22 +00001211protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001212 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1213 const char *startSpec,
1214 unsigned specifierLen,
1215 const char *csStart, unsigned csLen);
1216
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001217 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00001218 CharSourceRange getSpecifierRange(const char *startSpecifier,
1219 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001220 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001221
Ted Kremenek0d277352010-01-29 01:06:55 +00001222 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00001223
1224 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1225 const analyze_format_string::ConversionSpecifier &CS,
1226 const char *startSpecifier, unsigned specifierLen,
1227 unsigned argIndex);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001228};
1229}
1230
Ted Kremenek826a3452010-07-16 02:11:22 +00001231SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001232 return OrigFormatExpr->getSourceRange();
1233}
1234
Ted Kremenek826a3452010-07-16 02:11:22 +00001235CharSourceRange CheckFormatHandler::
1236getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001237 SourceLocation Start = getLocationOfByte(startSpecifier);
1238 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1239
1240 // Advance the end SourceLocation by one due to half-open ranges.
1241 End = End.getFileLocWithOffset(1);
1242
1243 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001244}
1245
Ted Kremenek826a3452010-07-16 02:11:22 +00001246SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001247 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001248}
1249
Ted Kremenek826a3452010-07-16 02:11:22 +00001250void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1251 unsigned specifierLen){
Ted Kremenek808015a2010-01-29 03:16:21 +00001252 SourceLocation Loc = getLocationOfByte(startSpecifier);
1253 S.Diag(Loc, diag::warn_printf_incomplete_specifier)
Ted Kremenek826a3452010-07-16 02:11:22 +00001254 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek808015a2010-01-29 03:16:21 +00001255}
1256
Ted Kremenekefaff192010-02-27 01:41:03 +00001257void
Ted Kremenek826a3452010-07-16 02:11:22 +00001258CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1259 analyze_format_string::PositionContext p) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001260 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek826a3452010-07-16 02:11:22 +00001261 S.Diag(Loc, diag::warn_format_invalid_positional_specifier)
1262 << (unsigned) p << getSpecifierRange(startPos, posLen);
Ted Kremenekefaff192010-02-27 01:41:03 +00001263}
1264
Ted Kremenek826a3452010-07-16 02:11:22 +00001265void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00001266 unsigned posLen) {
1267 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek826a3452010-07-16 02:11:22 +00001268 S.Diag(Loc, diag::warn_format_zero_positional_specifier)
1269 << getSpecifierRange(startPos, posLen);
Ted Kremenekefaff192010-02-27 01:41:03 +00001270}
1271
Ted Kremenek826a3452010-07-16 02:11:22 +00001272void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Ted Kremenek0c069442011-03-15 21:18:48 +00001273 if (!IsObjCLiteral) {
1274 // The presence of a null character is likely an error.
1275 S.Diag(getLocationOfByte(nullCharacter),
1276 diag::warn_printf_format_string_contains_null_char)
1277 << getFormatStringRange();
1278 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001279}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001280
Ted Kremenek826a3452010-07-16 02:11:22 +00001281const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
1282 return TheCall->getArg(FirstDataArg + i);
1283}
1284
1285void CheckFormatHandler::DoneProcessing() {
1286 // Does the number of data arguments exceed the number of
1287 // format conversions in the format string?
1288 if (!HasVAListArg) {
1289 // Find any arguments that weren't covered.
1290 CoveredArgs.flip();
1291 signed notCoveredArg = CoveredArgs.find_first();
1292 if (notCoveredArg >= 0) {
1293 assert((unsigned)notCoveredArg < NumDataArgs);
1294 S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(),
1295 diag::warn_printf_data_arg_not_used)
1296 << getFormatStringRange();
1297 }
1298 }
1299}
1300
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001301bool
1302CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1303 SourceLocation Loc,
1304 const char *startSpec,
1305 unsigned specifierLen,
1306 const char *csStart,
1307 unsigned csLen) {
1308
1309 bool keepGoing = true;
1310 if (argIndex < NumDataArgs) {
1311 // Consider the argument coverered, even though the specifier doesn't
1312 // make sense.
1313 CoveredArgs.set(argIndex);
1314 }
1315 else {
1316 // If argIndex exceeds the number of data arguments we
1317 // don't issue a warning because that is just a cascade of warnings (and
1318 // they may have intended '%%' anyway). We don't want to continue processing
1319 // the format string after this point, however, as we will like just get
1320 // gibberish when trying to match arguments.
1321 keepGoing = false;
1322 }
1323
1324 S.Diag(Loc, diag::warn_format_invalid_conversion)
1325 << llvm::StringRef(csStart, csLen)
1326 << getSpecifierRange(startSpec, specifierLen);
1327
1328 return keepGoing;
1329}
1330
Ted Kremenek666a1972010-07-26 19:45:42 +00001331bool
1332CheckFormatHandler::CheckNumArgs(
1333 const analyze_format_string::FormatSpecifier &FS,
1334 const analyze_format_string::ConversionSpecifier &CS,
1335 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1336
1337 if (argIndex >= NumDataArgs) {
1338 if (FS.usesPositionalArg()) {
1339 S.Diag(getLocationOfByte(CS.getStart()),
1340 diag::warn_printf_positional_arg_exceeds_data_args)
1341 << (argIndex+1) << NumDataArgs
1342 << getSpecifierRange(startSpecifier, specifierLen);
1343 }
1344 else {
1345 S.Diag(getLocationOfByte(CS.getStart()),
1346 diag::warn_printf_insufficient_data_args)
1347 << getSpecifierRange(startSpecifier, specifierLen);
1348 }
1349
1350 return false;
1351 }
1352 return true;
1353}
1354
Ted Kremenek826a3452010-07-16 02:11:22 +00001355//===--- CHECK: Printf format string checking ------------------------------===//
1356
1357namespace {
1358class CheckPrintfHandler : public CheckFormatHandler {
1359public:
1360 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1361 const Expr *origFormatExpr, unsigned firstDataArg,
1362 unsigned numDataArgs, bool isObjCLiteral,
1363 const char *beg, bool hasVAListArg,
1364 const CallExpr *theCall, unsigned formatIdx)
1365 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1366 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1367 theCall, formatIdx) {}
1368
1369
1370 bool HandleInvalidPrintfConversionSpecifier(
1371 const analyze_printf::PrintfSpecifier &FS,
1372 const char *startSpecifier,
1373 unsigned specifierLen);
1374
1375 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1376 const char *startSpecifier,
1377 unsigned specifierLen);
1378
1379 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1380 const char *startSpecifier, unsigned specifierLen);
1381 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1382 const analyze_printf::OptionalAmount &Amt,
1383 unsigned type,
1384 const char *startSpecifier, unsigned specifierLen);
1385 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1386 const analyze_printf::OptionalFlag &flag,
1387 const char *startSpecifier, unsigned specifierLen);
1388 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1389 const analyze_printf::OptionalFlag &ignoredFlag,
1390 const analyze_printf::OptionalFlag &flag,
1391 const char *startSpecifier, unsigned specifierLen);
1392};
1393}
1394
1395bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1396 const analyze_printf::PrintfSpecifier &FS,
1397 const char *startSpecifier,
1398 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001399 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001400 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001401
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001402 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1403 getLocationOfByte(CS.getStart()),
1404 startSpecifier, specifierLen,
1405 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001406}
1407
Ted Kremenek826a3452010-07-16 02:11:22 +00001408bool CheckPrintfHandler::HandleAmount(
1409 const analyze_format_string::OptionalAmount &Amt,
1410 unsigned k, const char *startSpecifier,
1411 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001412
1413 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001414 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001415 unsigned argIndex = Amt.getArgIndex();
1416 if (argIndex >= NumDataArgs) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001417 S.Diag(getLocationOfByte(Amt.getStart()),
1418 diag::warn_printf_asterisk_missing_arg)
Ted Kremenek826a3452010-07-16 02:11:22 +00001419 << k << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek0d277352010-01-29 01:06:55 +00001420 // Don't do any more checking. We will just emit
1421 // spurious errors.
1422 return false;
1423 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001424
Ted Kremenek0d277352010-01-29 01:06:55 +00001425 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00001426 // Although not in conformance with C99, we also allow the argument to be
1427 // an 'unsigned int' as that is a reasonably safe case. GCC also
1428 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001429 CoveredArgs.set(argIndex);
1430 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00001431 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001432
1433 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1434 assert(ATR.isValid());
1435
1436 if (!ATR.matchesType(S.Context, T)) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001437 S.Diag(getLocationOfByte(Amt.getStart()),
1438 diag::warn_printf_asterisk_wrong_type)
1439 << k
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001440 << ATR.getRepresentativeType(S.Context) << T
Ted Kremenek826a3452010-07-16 02:11:22 +00001441 << getSpecifierRange(startSpecifier, specifierLen)
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001442 << Arg->getSourceRange();
Ted Kremenek0d277352010-01-29 01:06:55 +00001443 // Don't do any more checking. We will just emit
1444 // spurious errors.
1445 return false;
1446 }
1447 }
1448 }
1449 return true;
1450}
Ted Kremenek0d277352010-01-29 01:06:55 +00001451
Tom Caree4ee9662010-06-17 19:00:27 +00001452void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00001453 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001454 const analyze_printf::OptionalAmount &Amt,
1455 unsigned type,
1456 const char *startSpecifier,
1457 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001458 const analyze_printf::PrintfConversionSpecifier &CS =
1459 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001460 switch (Amt.getHowSpecified()) {
1461 case analyze_printf::OptionalAmount::Constant:
1462 S.Diag(getLocationOfByte(Amt.getStart()),
1463 diag::warn_printf_nonsensical_optional_amount)
1464 << type
1465 << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001466 << getSpecifierRange(startSpecifier, specifierLen)
1467 << FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
Tom Caree4ee9662010-06-17 19:00:27 +00001468 Amt.getConstantLength()));
1469 break;
1470
1471 default:
1472 S.Diag(getLocationOfByte(Amt.getStart()),
1473 diag::warn_printf_nonsensical_optional_amount)
1474 << type
1475 << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001476 << getSpecifierRange(startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001477 break;
1478 }
1479}
1480
Ted Kremenek826a3452010-07-16 02:11:22 +00001481void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001482 const analyze_printf::OptionalFlag &flag,
1483 const char *startSpecifier,
1484 unsigned specifierLen) {
1485 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001486 const analyze_printf::PrintfConversionSpecifier &CS =
1487 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001488 S.Diag(getLocationOfByte(flag.getPosition()),
1489 diag::warn_printf_nonsensical_flag)
1490 << flag.toString() << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001491 << getSpecifierRange(startSpecifier, specifierLen)
1492 << FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1));
Tom Caree4ee9662010-06-17 19:00:27 +00001493}
1494
1495void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00001496 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001497 const analyze_printf::OptionalFlag &ignoredFlag,
1498 const analyze_printf::OptionalFlag &flag,
1499 const char *startSpecifier,
1500 unsigned specifierLen) {
1501 // Warn about ignored flag with a fixit removal.
1502 S.Diag(getLocationOfByte(ignoredFlag.getPosition()),
1503 diag::warn_printf_ignored_flag)
1504 << ignoredFlag.toString() << flag.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001505 << getSpecifierRange(startSpecifier, specifierLen)
1506 << FixItHint::CreateRemoval(getSpecifierRange(
Tom Caree4ee9662010-06-17 19:00:27 +00001507 ignoredFlag.getPosition(), 1));
1508}
1509
Ted Kremeneke0e53132010-01-28 23:39:18 +00001510bool
Ted Kremenek826a3452010-07-16 02:11:22 +00001511CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001512 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001513 const char *startSpecifier,
1514 unsigned specifierLen) {
1515
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001516 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00001517 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001518 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00001519
Ted Kremenekbaa40062010-07-19 22:01:06 +00001520 if (FS.consumesDataArgument()) {
1521 if (atFirstArg) {
1522 atFirstArg = false;
1523 usesPositionalArgs = FS.usesPositionalArg();
1524 }
1525 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1526 // Cannot mix-and-match positional and non-positional arguments.
1527 S.Diag(getLocationOfByte(CS.getStart()),
1528 diag::warn_format_mix_positional_nonpositional_args)
1529 << getSpecifierRange(startSpecifier, specifierLen);
1530 return false;
1531 }
Ted Kremenek0d277352010-01-29 01:06:55 +00001532 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001533
Ted Kremenekefaff192010-02-27 01:41:03 +00001534 // First check if the field width, precision, and conversion specifier
1535 // have matching data arguments.
1536 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1537 startSpecifier, specifierLen)) {
1538 return false;
1539 }
1540
1541 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1542 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001543 return false;
1544 }
1545
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001546 if (!CS.consumesDataArgument()) {
1547 // FIXME: Technically specifying a precision or field width here
1548 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001549 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001550 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001551
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001552 // Consume the argument.
1553 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00001554 if (argIndex < NumDataArgs) {
1555 // The check to see if the argIndex is valid will come later.
1556 // We set the bit here because we may exit early from this
1557 // function if we encounter some other error.
1558 CoveredArgs.set(argIndex);
1559 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001560
1561 // Check for using an Objective-C specific conversion specifier
1562 // in a non-ObjC literal.
1563 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001564 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
1565 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001566 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001567
Tom Caree4ee9662010-06-17 19:00:27 +00001568 // Check for invalid use of field width
1569 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001570 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00001571 startSpecifier, specifierLen);
1572 }
1573
1574 // Check for invalid use of precision
1575 if (!FS.hasValidPrecision()) {
1576 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
1577 startSpecifier, specifierLen);
1578 }
1579
1580 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00001581 if (!FS.hasValidThousandsGroupingPrefix())
1582 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001583 if (!FS.hasValidLeadingZeros())
1584 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
1585 if (!FS.hasValidPlusPrefix())
1586 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00001587 if (!FS.hasValidSpacePrefix())
1588 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001589 if (!FS.hasValidAlternativeForm())
1590 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
1591 if (!FS.hasValidLeftJustified())
1592 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
1593
1594 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00001595 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
1596 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
1597 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001598 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
1599 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
1600 startSpecifier, specifierLen);
1601
1602 // Check the length modifier is valid with the given conversion specifier.
1603 const LengthModifier &LM = FS.getLengthModifier();
1604 if (!FS.hasValidLengthModifier())
1605 S.Diag(getLocationOfByte(LM.getStart()),
Ted Kremenek649aecf2010-07-20 20:03:43 +00001606 diag::warn_format_nonsensical_length)
Tom Caree4ee9662010-06-17 19:00:27 +00001607 << LM.toString() << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001608 << getSpecifierRange(startSpecifier, specifierLen)
1609 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
Tom Caree4ee9662010-06-17 19:00:27 +00001610 LM.getLength()));
1611
1612 // Are we using '%n'?
Ted Kremenek35d353b2010-07-20 20:04:10 +00001613 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Caree4ee9662010-06-17 19:00:27 +00001614 // Issue a warning about this being a possible security issue.
Ted Kremeneke82d8042010-01-29 01:35:25 +00001615 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
Ted Kremenek826a3452010-07-16 02:11:22 +00001616 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremeneke82d8042010-01-29 01:35:25 +00001617 // Continue checking the other format specifiers.
1618 return true;
1619 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001620
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001621 // The remaining checks depend on the data arguments.
1622 if (HasVAListArg)
1623 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001624
Ted Kremenek666a1972010-07-26 19:45:42 +00001625 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001626 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001627
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001628 // Now type check the data expression that matches the
1629 // format specifier.
1630 const Expr *Ex = getDataArg(argIndex);
1631 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
1632 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
1633 // Check if we didn't match because of an implicit cast from a 'char'
1634 // or 'short' to an 'int'. This is done because printf is a varargs
1635 // function.
1636 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00001637 if (ICE->getType() == S.Context.IntTy) {
1638 // All further checking is done on the subexpression.
1639 Ex = ICE->getSubExpr();
1640 if (ATR.matchesType(S.Context, Ex->getType()))
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001641 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00001642 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001643
1644 // We may be able to offer a FixItHint if it is a supported type.
1645 PrintfSpecifier fixedFS = FS;
1646 bool success = fixedFS.fixType(Ex->getType());
1647
1648 if (success) {
1649 // Get the fix string from the fixed format specifier
1650 llvm::SmallString<128> buf;
1651 llvm::raw_svector_ostream os(buf);
1652 fixedFS.toString(os);
1653
Ted Kremenek9325eaf2010-08-24 22:24:51 +00001654 // FIXME: getRepresentativeType() perhaps should return a string
1655 // instead of a QualType to better handle when the representative
1656 // type is 'wint_t' (which is defined in the system headers).
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001657 S.Diag(getLocationOfByte(CS.getStart()),
1658 diag::warn_printf_conversion_argument_type_mismatch)
1659 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1660 << getSpecifierRange(startSpecifier, specifierLen)
1661 << Ex->getSourceRange()
1662 << FixItHint::CreateReplacement(
1663 getSpecifierRange(startSpecifier, specifierLen),
1664 os.str());
1665 }
1666 else {
1667 S.Diag(getLocationOfByte(CS.getStart()),
1668 diag::warn_printf_conversion_argument_type_mismatch)
1669 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1670 << getSpecifierRange(startSpecifier, specifierLen)
1671 << Ex->getSourceRange();
1672 }
1673 }
1674
Ted Kremeneke0e53132010-01-28 23:39:18 +00001675 return true;
1676}
1677
Ted Kremenek826a3452010-07-16 02:11:22 +00001678//===--- CHECK: Scanf format string checking ------------------------------===//
1679
1680namespace {
1681class CheckScanfHandler : public CheckFormatHandler {
1682public:
1683 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
1684 const Expr *origFormatExpr, unsigned firstDataArg,
1685 unsigned numDataArgs, bool isObjCLiteral,
1686 const char *beg, bool hasVAListArg,
1687 const CallExpr *theCall, unsigned formatIdx)
1688 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1689 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1690 theCall, formatIdx) {}
1691
1692 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
1693 const char *startSpecifier,
1694 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001695
1696 bool HandleInvalidScanfConversionSpecifier(
1697 const analyze_scanf::ScanfSpecifier &FS,
1698 const char *startSpecifier,
1699 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00001700
1701 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00001702};
Ted Kremenek07d161f2010-01-29 01:50:07 +00001703}
Ted Kremeneke0e53132010-01-28 23:39:18 +00001704
Ted Kremenekb7c21012010-07-16 18:28:03 +00001705void CheckScanfHandler::HandleIncompleteScanList(const char *start,
1706 const char *end) {
1707 S.Diag(getLocationOfByte(end), diag::warn_scanf_scanlist_incomplete)
1708 << getSpecifierRange(start, end - start);
1709}
1710
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001711bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
1712 const analyze_scanf::ScanfSpecifier &FS,
1713 const char *startSpecifier,
1714 unsigned specifierLen) {
1715
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001716 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001717 FS.getConversionSpecifier();
1718
1719 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1720 getLocationOfByte(CS.getStart()),
1721 startSpecifier, specifierLen,
1722 CS.getStart(), CS.getLength());
1723}
1724
Ted Kremenek826a3452010-07-16 02:11:22 +00001725bool CheckScanfHandler::HandleScanfSpecifier(
1726 const analyze_scanf::ScanfSpecifier &FS,
1727 const char *startSpecifier,
1728 unsigned specifierLen) {
1729
1730 using namespace analyze_scanf;
1731 using namespace analyze_format_string;
1732
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001733 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001734
Ted Kremenekbaa40062010-07-19 22:01:06 +00001735 // Handle case where '%' and '*' don't consume an argument. These shouldn't
1736 // be used to decide if we are using positional arguments consistently.
1737 if (FS.consumesDataArgument()) {
1738 if (atFirstArg) {
1739 atFirstArg = false;
1740 usesPositionalArgs = FS.usesPositionalArg();
1741 }
1742 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1743 // Cannot mix-and-match positional and non-positional arguments.
1744 S.Diag(getLocationOfByte(CS.getStart()),
1745 diag::warn_format_mix_positional_nonpositional_args)
1746 << getSpecifierRange(startSpecifier, specifierLen);
1747 return false;
1748 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001749 }
1750
1751 // Check if the field with is non-zero.
1752 const OptionalAmount &Amt = FS.getFieldWidth();
1753 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
1754 if (Amt.getConstantAmount() == 0) {
1755 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
1756 Amt.getConstantLength());
1757 S.Diag(getLocationOfByte(Amt.getStart()),
1758 diag::warn_scanf_nonzero_width)
1759 << R << FixItHint::CreateRemoval(R);
1760 }
1761 }
1762
1763 if (!FS.consumesDataArgument()) {
1764 // FIXME: Technically specifying a precision or field width here
1765 // makes no sense. Worth issuing a warning at some point.
1766 return true;
1767 }
1768
1769 // Consume the argument.
1770 unsigned argIndex = FS.getArgIndex();
1771 if (argIndex < NumDataArgs) {
1772 // The check to see if the argIndex is valid will come later.
1773 // We set the bit here because we may exit early from this
1774 // function if we encounter some other error.
1775 CoveredArgs.set(argIndex);
1776 }
1777
Ted Kremenek1e51c202010-07-20 20:04:47 +00001778 // Check the length modifier is valid with the given conversion specifier.
1779 const LengthModifier &LM = FS.getLengthModifier();
1780 if (!FS.hasValidLengthModifier()) {
1781 S.Diag(getLocationOfByte(LM.getStart()),
1782 diag::warn_format_nonsensical_length)
1783 << LM.toString() << CS.toString()
1784 << getSpecifierRange(startSpecifier, specifierLen)
1785 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
1786 LM.getLength()));
1787 }
1788
Ted Kremenek826a3452010-07-16 02:11:22 +00001789 // The remaining checks depend on the data arguments.
1790 if (HasVAListArg)
1791 return true;
1792
Ted Kremenek666a1972010-07-26 19:45:42 +00001793 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00001794 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00001795
1796 // FIXME: Check that the argument type matches the format specifier.
1797
1798 return true;
1799}
1800
1801void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001802 const Expr *OrigFormatExpr,
1803 const CallExpr *TheCall, bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001804 unsigned format_idx, unsigned firstDataArg,
1805 bool isPrintf) {
1806
Ted Kremeneke0e53132010-01-28 23:39:18 +00001807 // CHECK: is the format string a wide literal?
1808 if (FExpr->isWide()) {
1809 Diag(FExpr->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001810 diag::warn_format_string_is_wide_literal)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001811 << OrigFormatExpr->getSourceRange();
1812 return;
1813 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001814
Ted Kremeneke0e53132010-01-28 23:39:18 +00001815 // Str - The format string. NOTE: this is NOT null-terminated!
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001816 llvm::StringRef StrRef = FExpr->getString();
1817 const char *Str = StrRef.data();
1818 unsigned StrLen = StrRef.size();
Ted Kremenek826a3452010-07-16 02:11:22 +00001819
Ted Kremeneke0e53132010-01-28 23:39:18 +00001820 // CHECK: empty format string?
Ted Kremeneke0e53132010-01-28 23:39:18 +00001821 if (StrLen == 0) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001822 Diag(FExpr->getLocStart(), diag::warn_empty_format_string)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001823 << OrigFormatExpr->getSourceRange();
1824 return;
1825 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001826
1827 if (isPrintf) {
1828 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1829 TheCall->getNumArgs() - firstDataArg,
1830 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1831 HasVAListArg, TheCall, format_idx);
1832
1833 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen))
1834 H.DoneProcessing();
1835 }
1836 else {
1837 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1838 TheCall->getNumArgs() - firstDataArg,
1839 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1840 HasVAListArg, TheCall, format_idx);
1841
1842 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen))
1843 H.DoneProcessing();
1844 }
Ted Kremenekce7024e2010-01-28 01:18:22 +00001845}
1846
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001847//===--- CHECK: Standard memory functions ---------------------------------===//
1848
Douglas Gregor2a053a32011-05-03 20:05:22 +00001849/// \brief Determine whether the given type is a dynamic class type (e.g.,
1850/// whether it has a vtable).
1851static bool isDynamicClassType(QualType T) {
1852 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
1853 if (CXXRecordDecl *Definition = Record->getDefinition())
1854 if (Definition->isDynamicClass())
1855 return true;
1856
1857 return false;
1858}
1859
Chandler Carruth000d4282011-06-16 09:09:40 +00001860/// \brief If E is a sizeof expression returns the argument expression,
1861/// otherwise returns NULL.
1862static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00001863 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00001864 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
1865 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
1866 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00001867
Chandler Carruth000d4282011-06-16 09:09:40 +00001868 return 0;
1869}
1870
1871/// \brief If E is a sizeof expression returns the argument type.
1872static QualType getSizeOfArgType(const Expr* E) {
1873 if (const UnaryExprOrTypeTraitExpr *SizeOf =
1874 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
1875 if (SizeOf->getKind() == clang::UETT_SizeOf)
1876 return SizeOf->getTypeOfArgument();
1877
1878 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00001879}
1880
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001881/// \brief Check for dangerous or invalid arguments to memset().
1882///
Chandler Carruth929f0132011-06-03 06:23:57 +00001883/// This issues warnings on known problematic, dangerous or unspecified
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00001884/// arguments to the standard 'memset', 'memcpy', and 'memmove' function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001885///
1886/// \param Call The call expression to diagnose.
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00001887void Sema::CheckMemsetcpymoveArguments(const CallExpr *Call,
Douglas Gregor707a23e2011-06-16 17:56:04 +00001888 CheckedMemoryFunction CMF,
1889 IdentifierInfo *FnName) {
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00001890 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00001891 // we have enough arguments, and if not, abort further checking.
1892 if (Call->getNumArgs() < 3)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00001893 return;
1894
Douglas Gregor707a23e2011-06-16 17:56:04 +00001895 unsigned LastArg = (CMF == CMF_Memset? 1 : 2);
Nico Webere4a1c642011-06-14 16:14:58 +00001896 const Expr *LenExpr = Call->getArg(2)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00001897
1898 // We have special checking when the length is a sizeof expression.
1899 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
1900 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
1901 llvm::FoldingSetNodeID SizeOfArgID;
1902
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00001903 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
1904 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00001905 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001906
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00001907 QualType DestTy = Dest->getType();
1908 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
1909 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00001910
Chandler Carruth000d4282011-06-16 09:09:40 +00001911 // Never warn about void type pointers. This can be used to suppress
1912 // false positives.
1913 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00001914 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001915
Chandler Carruth000d4282011-06-16 09:09:40 +00001916 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
1917 // actually comparing the expressions for equality. Because computing the
1918 // expression IDs can be expensive, we only do this if the diagnostic is
1919 // enabled.
1920 if (SizeOfArg &&
1921 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
1922 SizeOfArg->getExprLoc())) {
1923 // We only compute IDs for expressions if the warning is enabled, and
1924 // cache the sizeof arg's ID.
1925 if (SizeOfArgID == llvm::FoldingSetNodeID())
1926 SizeOfArg->Profile(SizeOfArgID, Context, true);
1927 llvm::FoldingSetNodeID DestID;
1928 Dest->Profile(DestID, Context, true);
1929 if (DestID == SizeOfArgID) {
1930 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
1931 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
1932 if (UnaryOp->getOpcode() == UO_AddrOf)
1933 ActionIdx = 1; // If its an address-of operator, just remove it.
1934 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
1935 ActionIdx = 2; // If the pointee's size is sizeof(char),
1936 // suggest an explicit length.
1937 DiagRuntimeBehavior(SizeOfArg->getExprLoc(), Dest,
1938 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
1939 << FnName << ArgIdx << ActionIdx
1940 << Dest->getSourceRange()
1941 << SizeOfArg->getSourceRange());
1942 break;
1943 }
1944 }
1945
1946 // Also check for cases where the sizeof argument is the exact same
1947 // type as the memory argument, and where it points to a user-defined
1948 // record type.
1949 if (SizeOfArgTy != QualType()) {
1950 if (PointeeTy->isRecordType() &&
1951 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
1952 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
1953 PDiag(diag::warn_sizeof_pointer_type_memaccess)
1954 << FnName << SizeOfArgTy << ArgIdx
1955 << PointeeTy << Dest->getSourceRange()
1956 << LenExpr->getSourceRange());
1957 break;
1958 }
Nico Webere4a1c642011-06-14 16:14:58 +00001959 }
1960
John McCallf85e1932011-06-15 23:02:42 +00001961 unsigned DiagID;
1962
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00001963 // Always complain about dynamic classes.
John McCallf85e1932011-06-15 23:02:42 +00001964 if (isDynamicClassType(PointeeTy))
1965 DiagID = diag::warn_dyn_class_memaccess;
Douglas Gregor707a23e2011-06-16 17:56:04 +00001966 else if (PointeeTy.hasNonTrivialObjCLifetime() && CMF != CMF_Memset)
John McCallf85e1932011-06-15 23:02:42 +00001967 DiagID = diag::warn_arc_object_memaccess;
1968 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00001969 continue;
John McCallf85e1932011-06-15 23:02:42 +00001970
1971 DiagRuntimeBehavior(
1972 Dest->getExprLoc(), Dest,
1973 PDiag(DiagID)
1974 << ArgIdx << FnName << PointeeTy
1975 << Call->getCallee()->getSourceRange());
Chandler Carruth43fa33b2011-04-29 09:46:08 +00001976
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00001977 DiagRuntimeBehavior(
1978 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00001979 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00001980 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
1981 break;
1982 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001983 }
1984}
1985
Ted Kremenek06de2762007-08-17 16:46:58 +00001986//===--- CHECK: Return Address of Stack Variable --------------------------===//
1987
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001988static Expr *EvalVal(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars);
1989static Expr *EvalAddr(Expr* E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00001990
1991/// CheckReturnStackAddr - Check if a return statement returns the address
1992/// of a stack variable.
1993void
1994Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1995 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00001996
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001997 Expr *stackE = 0;
1998 llvm::SmallVector<DeclRefExpr *, 8> refVars;
1999
2000 // Perform checking for returned stack addresses, local blocks,
2001 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00002002 if (lhsType->isPointerType() ||
2003 (!getLangOptions().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002004 stackE = EvalAddr(RetValExp, refVars);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002005 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002006 stackE = EvalVal(RetValExp, refVars);
2007 }
2008
2009 if (stackE == 0)
2010 return; // Nothing suspicious was found.
2011
2012 SourceLocation diagLoc;
2013 SourceRange diagRange;
2014 if (refVars.empty()) {
2015 diagLoc = stackE->getLocStart();
2016 diagRange = stackE->getSourceRange();
2017 } else {
2018 // We followed through a reference variable. 'stackE' contains the
2019 // problematic expression but we will warn at the return statement pointing
2020 // at the reference variable. We will later display the "trail" of
2021 // reference variables using notes.
2022 diagLoc = refVars[0]->getLocStart();
2023 diagRange = refVars[0]->getSourceRange();
2024 }
2025
2026 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
2027 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
2028 : diag::warn_ret_stack_addr)
2029 << DR->getDecl()->getDeclName() << diagRange;
2030 } else if (isa<BlockExpr>(stackE)) { // local block.
2031 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
2032 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
2033 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
2034 } else { // local temporary.
2035 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
2036 : diag::warn_ret_local_temp_addr)
2037 << diagRange;
2038 }
2039
2040 // Display the "trail" of reference variables that we followed until we
2041 // found the problematic expression using notes.
2042 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
2043 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
2044 // If this var binds to another reference var, show the range of the next
2045 // var, otherwise the var binds to the problematic expression, in which case
2046 // show the range of the expression.
2047 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
2048 : stackE->getSourceRange();
2049 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
2050 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00002051 }
2052}
2053
2054/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
2055/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002056/// to a location on the stack, a local block, an address of a label, or a
2057/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00002058/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002059/// encounter a subexpression that (1) clearly does not lead to one of the
2060/// above problematic expressions (2) is something we cannot determine leads to
2061/// a problematic expression based on such local checking.
2062///
2063/// Both EvalAddr and EvalVal follow through reference variables to evaluate
2064/// the expression that they point to. Such variables are added to the
2065/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00002066///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002067/// EvalAddr processes expressions that are pointers that are used as
2068/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002069/// At the base case of the recursion is a check for the above problematic
2070/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00002071///
2072/// This implementation handles:
2073///
2074/// * pointer-to-pointer casts
2075/// * implicit conversions from array references to pointers
2076/// * taking the address of fields
2077/// * arbitrary interplay between "&" and "*" operators
2078/// * pointer arithmetic from an address of a stack variable
2079/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002080static Expr *EvalAddr(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars) {
2081 if (E->isTypeDependent())
2082 return NULL;
2083
Ted Kremenek06de2762007-08-17 16:46:58 +00002084 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00002085 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00002086 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002087 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002088 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00002089
Peter Collingbournef111d932011-04-15 00:35:48 +00002090 E = E->IgnoreParens();
2091
Ted Kremenek06de2762007-08-17 16:46:58 +00002092 // Our "symbolic interpreter" is just a dispatch off the currently
2093 // viewed AST node. We then recursively traverse the AST by calling
2094 // EvalAddr and EvalVal appropriately.
2095 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002096 case Stmt::DeclRefExprClass: {
2097 DeclRefExpr *DR = cast<DeclRefExpr>(E);
2098
2099 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
2100 // If this is a reference variable, follow through to the expression that
2101 // it points to.
2102 if (V->hasLocalStorage() &&
2103 V->getType()->isReferenceType() && V->hasInit()) {
2104 // Add the reference variable to the "trail".
2105 refVars.push_back(DR);
2106 return EvalAddr(V->getInit(), refVars);
2107 }
2108
2109 return NULL;
2110 }
Ted Kremenek06de2762007-08-17 16:46:58 +00002111
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002112 case Stmt::UnaryOperatorClass: {
2113 // The only unary operator that make sense to handle here
2114 // is AddrOf. All others don't make sense as pointers.
2115 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002116
John McCall2de56d12010-08-25 11:45:40 +00002117 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002118 return EvalVal(U->getSubExpr(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002119 else
Ted Kremenek06de2762007-08-17 16:46:58 +00002120 return NULL;
2121 }
Mike Stump1eb44332009-09-09 15:08:12 +00002122
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002123 case Stmt::BinaryOperatorClass: {
2124 // Handle pointer arithmetic. All other binary operators are not valid
2125 // in this context.
2126 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00002127 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00002128
John McCall2de56d12010-08-25 11:45:40 +00002129 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002130 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00002131
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002132 Expr *Base = B->getLHS();
2133
2134 // Determine which argument is the real pointer base. It could be
2135 // the RHS argument instead of the LHS.
2136 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00002137
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002138 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002139 return EvalAddr(Base, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002140 }
Steve Naroff61f40a22008-09-10 19:17:48 +00002141
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002142 // For conditional operators we need to see if either the LHS or RHS are
2143 // valid DeclRefExpr*s. If one of them is valid, we return it.
2144 case Stmt::ConditionalOperatorClass: {
2145 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002146
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002147 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002148 if (Expr *lhsExpr = C->getLHS()) {
2149 // In C++, we can have a throw-expression, which has 'void' type.
2150 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002151 if (Expr* LHS = EvalAddr(lhsExpr, refVars))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002152 return LHS;
2153 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002154
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002155 // In C++, we can have a throw-expression, which has 'void' type.
2156 if (C->getRHS()->getType()->isVoidType())
2157 return NULL;
2158
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002159 return EvalAddr(C->getRHS(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002160 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002161
2162 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00002163 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002164 return E; // local block.
2165 return NULL;
2166
2167 case Stmt::AddrLabelExprClass:
2168 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00002169
Ted Kremenek54b52742008-08-07 00:49:01 +00002170 // For casts, we need to handle conversions from arrays to
2171 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00002172 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002173 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00002174 case Stmt::CXXFunctionalCastExprClass:
2175 case Stmt::ObjCBridgedCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002176 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00002177 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002178
Steve Naroffdd972f22008-09-05 22:11:13 +00002179 if (SubExpr->getType()->isPointerType() ||
2180 SubExpr->getType()->isBlockPointerType() ||
2181 SubExpr->getType()->isObjCQualifiedIdType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002182 return EvalAddr(SubExpr, refVars);
Ted Kremenek54b52742008-08-07 00:49:01 +00002183 else if (T->isArrayType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002184 return EvalVal(SubExpr, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002185 else
Ted Kremenek54b52742008-08-07 00:49:01 +00002186 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002187 }
Mike Stump1eb44332009-09-09 15:08:12 +00002188
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002189 // C++ casts. For dynamic casts, static casts, and const casts, we
2190 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00002191 // through the cast. In the case the dynamic cast doesn't fail (and
2192 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002193 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00002194 // FIXME: The comment about is wrong; we're not always converting
2195 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00002196 // handle references to objects.
2197 case Stmt::CXXStaticCastExprClass:
2198 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00002199 case Stmt::CXXConstCastExprClass:
2200 case Stmt::CXXReinterpretCastExprClass: {
2201 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00002202 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002203 return EvalAddr(S, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002204 else
2205 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002206 }
Mike Stump1eb44332009-09-09 15:08:12 +00002207
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002208 // Everything else: we simply don't reason about them.
2209 default:
2210 return NULL;
2211 }
Ted Kremenek06de2762007-08-17 16:46:58 +00002212}
Mike Stump1eb44332009-09-09 15:08:12 +00002213
Ted Kremenek06de2762007-08-17 16:46:58 +00002214
2215/// EvalVal - This function is complements EvalAddr in the mutual recursion.
2216/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002217static Expr *EvalVal(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002218do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002219 // We should only be called for evaluating non-pointer expressions, or
2220 // expressions with a pointer type that are not used as references but instead
2221 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00002222
Ted Kremenek06de2762007-08-17 16:46:58 +00002223 // Our "symbolic interpreter" is just a dispatch off the currently
2224 // viewed AST node. We then recursively traverse the AST by calling
2225 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00002226
2227 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00002228 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002229 case Stmt::ImplicitCastExprClass: {
2230 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00002231 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002232 E = IE->getSubExpr();
2233 continue;
2234 }
2235 return NULL;
2236 }
2237
Douglas Gregora2813ce2009-10-23 18:54:35 +00002238 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002239 // When we hit a DeclRefExpr we are looking at code that refers to a
2240 // variable's name. If it's not a reference variable we check if it has
2241 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00002242 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002243
Ted Kremenek06de2762007-08-17 16:46:58 +00002244 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002245 if (V->hasLocalStorage()) {
2246 if (!V->getType()->isReferenceType())
2247 return DR;
2248
2249 // Reference variable, follow through to the expression that
2250 // it points to.
2251 if (V->hasInit()) {
2252 // Add the reference variable to the "trail".
2253 refVars.push_back(DR);
2254 return EvalVal(V->getInit(), refVars);
2255 }
2256 }
Mike Stump1eb44332009-09-09 15:08:12 +00002257
Ted Kremenek06de2762007-08-17 16:46:58 +00002258 return NULL;
2259 }
Mike Stump1eb44332009-09-09 15:08:12 +00002260
Ted Kremenek06de2762007-08-17 16:46:58 +00002261 case Stmt::UnaryOperatorClass: {
2262 // The only unary operator that make sense to handle here
2263 // is Deref. All others don't resolve to a "name." This includes
2264 // handling all sorts of rvalues passed to a unary operator.
2265 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002266
John McCall2de56d12010-08-25 11:45:40 +00002267 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002268 return EvalAddr(U->getSubExpr(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002269
2270 return NULL;
2271 }
Mike Stump1eb44332009-09-09 15:08:12 +00002272
Ted Kremenek06de2762007-08-17 16:46:58 +00002273 case Stmt::ArraySubscriptExprClass: {
2274 // Array subscripts are potential references to data on the stack. We
2275 // retrieve the DeclRefExpr* for the array variable if it indeed
2276 // has local storage.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002277 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002278 }
Mike Stump1eb44332009-09-09 15:08:12 +00002279
Ted Kremenek06de2762007-08-17 16:46:58 +00002280 case Stmt::ConditionalOperatorClass: {
2281 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002282 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00002283 ConditionalOperator *C = cast<ConditionalOperator>(E);
2284
Anders Carlsson39073232007-11-30 19:04:31 +00002285 // Handle the GNU extension for missing LHS.
2286 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002287 if (Expr *LHS = EvalVal(lhsExpr, refVars))
Anders Carlsson39073232007-11-30 19:04:31 +00002288 return LHS;
2289
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002290 return EvalVal(C->getRHS(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002291 }
Mike Stump1eb44332009-09-09 15:08:12 +00002292
Ted Kremenek06de2762007-08-17 16:46:58 +00002293 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00002294 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00002295 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002296
Ted Kremenek06de2762007-08-17 16:46:58 +00002297 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00002298 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00002299 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00002300
2301 // Check whether the member type is itself a reference, in which case
2302 // we're not going to refer to the member, but to what the member refers to.
2303 if (M->getMemberDecl()->getType()->isReferenceType())
2304 return NULL;
2305
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002306 return EvalVal(M->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002307 }
Mike Stump1eb44332009-09-09 15:08:12 +00002308
Ted Kremenek06de2762007-08-17 16:46:58 +00002309 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002310 // Check that we don't return or take the address of a reference to a
2311 // temporary. This is only useful in C++.
2312 if (!E->isTypeDependent() && E->isRValue())
2313 return E;
2314
2315 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00002316 return NULL;
2317 }
Ted Kremenek68957a92010-08-04 20:01:07 +00002318} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00002319}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002320
2321//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
2322
2323/// Check for comparisons of floating point operands using != and ==.
2324/// Issue a warning if these are no self-comparisons, as they are not likely
2325/// to do what the programmer intended.
2326void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
2327 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002328
John McCallf6a16482010-12-04 03:47:34 +00002329 Expr* LeftExprSansParen = lex->IgnoreParenImpCasts();
2330 Expr* RightExprSansParen = rex->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002331
2332 // Special case: check for x == x (which is OK).
2333 // Do not emit warnings for such cases.
2334 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
2335 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
2336 if (DRL->getDecl() == DRR->getDecl())
2337 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002338
2339
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002340 // Special case: check for comparisons against literals that can be exactly
2341 // represented by APFloat. In such cases, do not emit a warning. This
2342 // is a heuristic: often comparison against such literals are used to
2343 // detect if a value in a variable has not changed. This clearly can
2344 // lead to false negatives.
2345 if (EmitWarning) {
2346 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
2347 if (FLL->isExact())
2348 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002349 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002350 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
2351 if (FLR->isExact())
2352 EmitWarning = false;
2353 }
2354 }
Mike Stump1eb44332009-09-09 15:08:12 +00002355
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002356 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002357 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002358 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002359 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002360 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002361
Sebastian Redl0eb23302009-01-19 00:08:26 +00002362 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002363 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002364 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002365 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002366
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002367 // Emit the diagnostic.
2368 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002369 Diag(loc, diag::warn_floatingpoint_eq)
2370 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002371}
John McCallba26e582010-01-04 23:21:16 +00002372
John McCallf2370c92010-01-06 05:24:50 +00002373//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
2374//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00002375
John McCallf2370c92010-01-06 05:24:50 +00002376namespace {
John McCallba26e582010-01-04 23:21:16 +00002377
John McCallf2370c92010-01-06 05:24:50 +00002378/// Structure recording the 'active' range of an integer-valued
2379/// expression.
2380struct IntRange {
2381 /// The number of bits active in the int.
2382 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00002383
John McCallf2370c92010-01-06 05:24:50 +00002384 /// True if the int is known not to have negative values.
2385 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00002386
John McCallf2370c92010-01-06 05:24:50 +00002387 IntRange(unsigned Width, bool NonNegative)
2388 : Width(Width), NonNegative(NonNegative)
2389 {}
John McCallba26e582010-01-04 23:21:16 +00002390
John McCall1844a6e2010-11-10 23:38:19 +00002391 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00002392 static IntRange forBoolType() {
2393 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00002394 }
2395
John McCall1844a6e2010-11-10 23:38:19 +00002396 /// Returns the range of an opaque value of the given integral type.
2397 static IntRange forValueOfType(ASTContext &C, QualType T) {
2398 return forValueOfCanonicalType(C,
2399 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00002400 }
2401
John McCall1844a6e2010-11-10 23:38:19 +00002402 /// Returns the range of an opaque value of a canonical integral type.
2403 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00002404 assert(T->isCanonicalUnqualified());
2405
2406 if (const VectorType *VT = dyn_cast<VectorType>(T))
2407 T = VT->getElementType().getTypePtr();
2408 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2409 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00002410
John McCall091f23f2010-11-09 22:22:12 +00002411 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00002412 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
2413 EnumDecl *Enum = ET->getDecl();
John McCall091f23f2010-11-09 22:22:12 +00002414 if (!Enum->isDefinition())
2415 return IntRange(C.getIntWidth(QualType(T, 0)), false);
2416
John McCall323ed742010-05-06 08:58:33 +00002417 unsigned NumPositive = Enum->getNumPositiveBits();
2418 unsigned NumNegative = Enum->getNumNegativeBits();
2419
2420 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
2421 }
John McCallf2370c92010-01-06 05:24:50 +00002422
2423 const BuiltinType *BT = cast<BuiltinType>(T);
2424 assert(BT->isInteger());
2425
2426 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2427 }
2428
John McCall1844a6e2010-11-10 23:38:19 +00002429 /// Returns the "target" range of a canonical integral type, i.e.
2430 /// the range of values expressible in the type.
2431 ///
2432 /// This matches forValueOfCanonicalType except that enums have the
2433 /// full range of their type, not the range of their enumerators.
2434 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
2435 assert(T->isCanonicalUnqualified());
2436
2437 if (const VectorType *VT = dyn_cast<VectorType>(T))
2438 T = VT->getElementType().getTypePtr();
2439 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2440 T = CT->getElementType().getTypePtr();
2441 if (const EnumType *ET = dyn_cast<EnumType>(T))
2442 T = ET->getDecl()->getIntegerType().getTypePtr();
2443
2444 const BuiltinType *BT = cast<BuiltinType>(T);
2445 assert(BT->isInteger());
2446
2447 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2448 }
2449
2450 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002451 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00002452 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00002453 L.NonNegative && R.NonNegative);
2454 }
2455
John McCall1844a6e2010-11-10 23:38:19 +00002456 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002457 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00002458 return IntRange(std::min(L.Width, R.Width),
2459 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00002460 }
2461};
2462
2463IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
2464 if (value.isSigned() && value.isNegative())
2465 return IntRange(value.getMinSignedBits(), false);
2466
2467 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002468 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00002469
2470 // isNonNegative() just checks the sign bit without considering
2471 // signedness.
2472 return IntRange(value.getActiveBits(), true);
2473}
2474
John McCall0acc3112010-01-06 22:57:21 +00002475IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCallf2370c92010-01-06 05:24:50 +00002476 unsigned MaxWidth) {
2477 if (result.isInt())
2478 return GetValueRange(C, result.getInt(), MaxWidth);
2479
2480 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00002481 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
2482 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
2483 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
2484 R = IntRange::join(R, El);
2485 }
John McCallf2370c92010-01-06 05:24:50 +00002486 return R;
2487 }
2488
2489 if (result.isComplexInt()) {
2490 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
2491 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
2492 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00002493 }
2494
2495 // This can happen with lossless casts to intptr_t of "based" lvalues.
2496 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00002497 // FIXME: The only reason we need to pass the type in here is to get
2498 // the sign right on this one case. It would be nice if APValue
2499 // preserved this.
John McCallf2370c92010-01-06 05:24:50 +00002500 assert(result.isLValue());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00002501 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00002502}
John McCallf2370c92010-01-06 05:24:50 +00002503
2504/// Pseudo-evaluate the given integer expression, estimating the
2505/// range of values it might take.
2506///
2507/// \param MaxWidth - the width to which the value will be truncated
2508IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
2509 E = E->IgnoreParens();
2510
2511 // Try a full evaluation first.
2512 Expr::EvalResult result;
2513 if (E->Evaluate(result, C))
John McCall0acc3112010-01-06 22:57:21 +00002514 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00002515
2516 // I think we only want to look through implicit casts here; if the
2517 // user has an explicit widening cast, we should treat the value as
2518 // being of the new, wider type.
2519 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00002520 if (CE->getCastKind() == CK_NoOp)
John McCallf2370c92010-01-06 05:24:50 +00002521 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
2522
John McCall1844a6e2010-11-10 23:38:19 +00002523 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00002524
John McCall2de56d12010-08-25 11:45:40 +00002525 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00002526
John McCallf2370c92010-01-06 05:24:50 +00002527 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00002528 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00002529 return OutputTypeRange;
2530
2531 IntRange SubRange
2532 = GetExprRange(C, CE->getSubExpr(),
2533 std::min(MaxWidth, OutputTypeRange.Width));
2534
2535 // Bail out if the subexpr's range is as wide as the cast type.
2536 if (SubRange.Width >= OutputTypeRange.Width)
2537 return OutputTypeRange;
2538
2539 // Otherwise, we take the smaller width, and we're non-negative if
2540 // either the output type or the subexpr is.
2541 return IntRange(SubRange.Width,
2542 SubRange.NonNegative || OutputTypeRange.NonNegative);
2543 }
2544
2545 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2546 // If we can fold the condition, just take that operand.
2547 bool CondResult;
2548 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
2549 return GetExprRange(C, CondResult ? CO->getTrueExpr()
2550 : CO->getFalseExpr(),
2551 MaxWidth);
2552
2553 // Otherwise, conservatively merge.
2554 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
2555 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
2556 return IntRange::join(L, R);
2557 }
2558
2559 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2560 switch (BO->getOpcode()) {
2561
2562 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00002563 case BO_LAnd:
2564 case BO_LOr:
2565 case BO_LT:
2566 case BO_GT:
2567 case BO_LE:
2568 case BO_GE:
2569 case BO_EQ:
2570 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00002571 return IntRange::forBoolType();
2572
John McCallc0cd21d2010-02-23 19:22:29 +00002573 // The type of these compound assignments is the type of the LHS,
2574 // so the RHS is not necessarily an integer.
John McCall2de56d12010-08-25 11:45:40 +00002575 case BO_MulAssign:
2576 case BO_DivAssign:
2577 case BO_RemAssign:
2578 case BO_AddAssign:
2579 case BO_SubAssign:
John McCall1844a6e2010-11-10 23:38:19 +00002580 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00002581
John McCallf2370c92010-01-06 05:24:50 +00002582 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00002583 case BO_PtrMemD:
2584 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00002585 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002586
John McCall60fad452010-01-06 22:07:33 +00002587 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00002588 case BO_And:
2589 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00002590 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
2591 GetExprRange(C, BO->getRHS(), MaxWidth));
2592
John McCallf2370c92010-01-06 05:24:50 +00002593 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00002594 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00002595 // ...except that we want to treat '1 << (blah)' as logically
2596 // positive. It's an important idiom.
2597 if (IntegerLiteral *I
2598 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
2599 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00002600 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00002601 return IntRange(R.Width, /*NonNegative*/ true);
2602 }
2603 }
2604 // fallthrough
2605
John McCall2de56d12010-08-25 11:45:40 +00002606 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00002607 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002608
John McCall60fad452010-01-06 22:07:33 +00002609 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00002610 case BO_Shr:
2611 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00002612 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2613
2614 // If the shift amount is a positive constant, drop the width by
2615 // that much.
2616 llvm::APSInt shift;
2617 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
2618 shift.isNonNegative()) {
2619 unsigned zext = shift.getZExtValue();
2620 if (zext >= L.Width)
2621 L.Width = (L.NonNegative ? 0 : 1);
2622 else
2623 L.Width -= zext;
2624 }
2625
2626 return L;
2627 }
2628
2629 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00002630 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00002631 return GetExprRange(C, BO->getRHS(), MaxWidth);
2632
John McCall60fad452010-01-06 22:07:33 +00002633 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00002634 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00002635 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00002636 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002637 // fallthrough
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002638
John McCallf2370c92010-01-06 05:24:50 +00002639 default:
2640 break;
2641 }
2642
2643 // Treat every other operator as if it were closed on the
2644 // narrowest type that encompasses both operands.
2645 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2646 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
2647 return IntRange::join(L, R);
2648 }
2649
2650 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2651 switch (UO->getOpcode()) {
2652 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00002653 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00002654 return IntRange::forBoolType();
2655
2656 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00002657 case UO_Deref:
2658 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00002659 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002660
2661 default:
2662 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
2663 }
2664 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002665
2666 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00002667 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002668 }
John McCallf2370c92010-01-06 05:24:50 +00002669
2670 FieldDecl *BitField = E->getBitField();
2671 if (BitField) {
2672 llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C);
2673 unsigned BitWidth = BitWidthAP.getZExtValue();
2674
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00002675 return IntRange(BitWidth,
2676 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00002677 }
2678
John McCall1844a6e2010-11-10 23:38:19 +00002679 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002680}
John McCall51313c32010-01-04 23:31:57 +00002681
John McCall323ed742010-05-06 08:58:33 +00002682IntRange GetExprRange(ASTContext &C, Expr *E) {
2683 return GetExprRange(C, E, C.getIntWidth(E->getType()));
2684}
2685
John McCall51313c32010-01-04 23:31:57 +00002686/// Checks whether the given value, which currently has the given
2687/// source semantics, has the same value when coerced through the
2688/// target semantics.
John McCallf2370c92010-01-06 05:24:50 +00002689bool IsSameFloatAfterCast(const llvm::APFloat &value,
2690 const llvm::fltSemantics &Src,
2691 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002692 llvm::APFloat truncated = value;
2693
2694 bool ignored;
2695 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
2696 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
2697
2698 return truncated.bitwiseIsEqual(value);
2699}
2700
2701/// Checks whether the given value, which currently has the given
2702/// source semantics, has the same value when coerced through the
2703/// target semantics.
2704///
2705/// The value might be a vector of floats (or a complex number).
John McCallf2370c92010-01-06 05:24:50 +00002706bool IsSameFloatAfterCast(const APValue &value,
2707 const llvm::fltSemantics &Src,
2708 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002709 if (value.isFloat())
2710 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
2711
2712 if (value.isVector()) {
2713 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
2714 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
2715 return false;
2716 return true;
2717 }
2718
2719 assert(value.isComplexFloat());
2720 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
2721 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
2722}
2723
John McCallb4eb64d2010-10-08 02:01:28 +00002724void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00002725
Ted Kremeneke3b159c2010-09-23 21:43:44 +00002726static bool IsZero(Sema &S, Expr *E) {
2727 // Suppress cases where we are comparing against an enum constant.
2728 if (const DeclRefExpr *DR =
2729 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
2730 if (isa<EnumConstantDecl>(DR->getDecl()))
2731 return false;
2732
2733 // Suppress cases where the '0' value is expanded from a macro.
2734 if (E->getLocStart().isMacroID())
2735 return false;
2736
John McCall323ed742010-05-06 08:58:33 +00002737 llvm::APSInt Value;
2738 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
2739}
2740
John McCall372e1032010-10-06 00:25:24 +00002741static bool HasEnumType(Expr *E) {
2742 // Strip off implicit integral promotions.
2743 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00002744 if (ICE->getCastKind() != CK_IntegralCast &&
2745 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00002746 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00002747 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00002748 }
2749
2750 return E->getType()->isEnumeralType();
2751}
2752
John McCall323ed742010-05-06 08:58:33 +00002753void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002754 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00002755 if (E->isValueDependent())
2756 return;
2757
John McCall2de56d12010-08-25 11:45:40 +00002758 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00002759 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002760 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00002761 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002762 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00002763 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002764 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00002765 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002766 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00002767 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002768 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00002769 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002770 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00002771 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002772 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00002773 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2774 }
2775}
2776
2777/// Analyze the operands of the given comparison. Implements the
2778/// fallback case from AnalyzeComparison.
2779void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00002780 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
2781 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00002782}
John McCall51313c32010-01-04 23:31:57 +00002783
John McCallba26e582010-01-04 23:21:16 +00002784/// \brief Implements -Wsign-compare.
2785///
2786/// \param lex the left-hand expression
2787/// \param rex the right-hand expression
2788/// \param OpLoc the location of the joining operator
John McCalld1b47bf2010-03-11 19:43:18 +00002789/// \param BinOpc binary opcode or 0
John McCall323ed742010-05-06 08:58:33 +00002790void AnalyzeComparison(Sema &S, BinaryOperator *E) {
2791 // The type the comparison is being performed in.
2792 QualType T = E->getLHS()->getType();
2793 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
2794 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00002795
John McCall323ed742010-05-06 08:58:33 +00002796 // We don't do anything special if this isn't an unsigned integral
2797 // comparison: we're only interested in integral comparisons, and
2798 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00002799 //
2800 // We also don't care about value-dependent expressions or expressions
2801 // whose result is a constant.
2802 if (!T->hasUnsignedIntegerRepresentation()
2803 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCall323ed742010-05-06 08:58:33 +00002804 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00002805
John McCall323ed742010-05-06 08:58:33 +00002806 Expr *lex = E->getLHS()->IgnoreParenImpCasts();
2807 Expr *rex = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00002808
John McCall323ed742010-05-06 08:58:33 +00002809 // Check to see if one of the (unmodified) operands is of different
2810 // signedness.
2811 Expr *signedOperand, *unsignedOperand;
Douglas Gregorf6094622010-07-23 15:58:24 +00002812 if (lex->getType()->hasSignedIntegerRepresentation()) {
2813 assert(!rex->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00002814 "unsigned comparison between two signed integer expressions?");
2815 signedOperand = lex;
2816 unsignedOperand = rex;
Douglas Gregorf6094622010-07-23 15:58:24 +00002817 } else if (rex->getType()->hasSignedIntegerRepresentation()) {
John McCall323ed742010-05-06 08:58:33 +00002818 signedOperand = rex;
2819 unsignedOperand = lex;
John McCallba26e582010-01-04 23:21:16 +00002820 } else {
John McCall323ed742010-05-06 08:58:33 +00002821 CheckTrivialUnsignedComparison(S, E);
2822 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00002823 }
2824
John McCall323ed742010-05-06 08:58:33 +00002825 // Otherwise, calculate the effective range of the signed operand.
2826 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00002827
John McCall323ed742010-05-06 08:58:33 +00002828 // Go ahead and analyze implicit conversions in the operands. Note
2829 // that we skip the implicit conversions on both sides.
John McCallb4eb64d2010-10-08 02:01:28 +00002830 AnalyzeImplicitConversions(S, lex, E->getOperatorLoc());
2831 AnalyzeImplicitConversions(S, rex, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00002832
John McCall323ed742010-05-06 08:58:33 +00002833 // If the signed range is non-negative, -Wsign-compare won't fire,
2834 // but we should still check for comparisons which are always true
2835 // or false.
2836 if (signedRange.NonNegative)
2837 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00002838
2839 // For (in)equality comparisons, if the unsigned operand is a
2840 // constant which cannot collide with a overflowed signed operand,
2841 // then reinterpreting the signed operand as unsigned will not
2842 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00002843 if (E->isEqualityOp()) {
2844 unsigned comparisonWidth = S.Context.getIntWidth(T);
2845 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00002846
John McCall323ed742010-05-06 08:58:33 +00002847 // We should never be unable to prove that the unsigned operand is
2848 // non-negative.
2849 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
2850
2851 if (unsignedRange.Width < comparisonWidth)
2852 return;
2853 }
2854
2855 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
2856 << lex->getType() << rex->getType()
2857 << lex->getSourceRange() << rex->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00002858}
2859
John McCall15d7d122010-11-11 03:21:53 +00002860/// Analyzes an attempt to assign the given value to a bitfield.
2861///
2862/// Returns true if there was something fishy about the attempt.
2863bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
2864 SourceLocation InitLoc) {
2865 assert(Bitfield->isBitField());
2866 if (Bitfield->isInvalidDecl())
2867 return false;
2868
John McCall91b60142010-11-11 05:33:51 +00002869 // White-list bool bitfields.
2870 if (Bitfield->getType()->isBooleanType())
2871 return false;
2872
Douglas Gregor46ff3032011-02-04 13:09:01 +00002873 // Ignore value- or type-dependent expressions.
2874 if (Bitfield->getBitWidth()->isValueDependent() ||
2875 Bitfield->getBitWidth()->isTypeDependent() ||
2876 Init->isValueDependent() ||
2877 Init->isTypeDependent())
2878 return false;
2879
John McCall15d7d122010-11-11 03:21:53 +00002880 Expr *OriginalInit = Init->IgnoreParenImpCasts();
2881
2882 llvm::APSInt Width(32);
2883 Expr::EvalResult InitValue;
2884 if (!Bitfield->getBitWidth()->isIntegerConstantExpr(Width, S.Context) ||
John McCall91b60142010-11-11 05:33:51 +00002885 !OriginalInit->Evaluate(InitValue, S.Context) ||
John McCall15d7d122010-11-11 03:21:53 +00002886 !InitValue.Val.isInt())
2887 return false;
2888
2889 const llvm::APSInt &Value = InitValue.Val.getInt();
2890 unsigned OriginalWidth = Value.getBitWidth();
2891 unsigned FieldWidth = Width.getZExtValue();
2892
2893 if (OriginalWidth <= FieldWidth)
2894 return false;
2895
Jay Foad9f71a8f2010-12-07 08:25:34 +00002896 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
John McCall15d7d122010-11-11 03:21:53 +00002897
2898 // It's fairly common to write values into signed bitfields
2899 // that, if sign-extended, would end up becoming a different
2900 // value. We don't want to warn about that.
2901 if (Value.isSigned() && Value.isNegative())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002902 TruncatedValue = TruncatedValue.sext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00002903 else
Jay Foad9f71a8f2010-12-07 08:25:34 +00002904 TruncatedValue = TruncatedValue.zext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00002905
2906 if (Value == TruncatedValue)
2907 return false;
2908
2909 std::string PrettyValue = Value.toString(10);
2910 std::string PrettyTrunc = TruncatedValue.toString(10);
2911
2912 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
2913 << PrettyValue << PrettyTrunc << OriginalInit->getType()
2914 << Init->getSourceRange();
2915
2916 return true;
2917}
2918
John McCallbeb22aa2010-11-09 23:24:47 +00002919/// Analyze the given simple or compound assignment for warning-worthy
2920/// operations.
2921void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
2922 // Just recurse on the LHS.
2923 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
2924
2925 // We want to recurse on the RHS as normal unless we're assigning to
2926 // a bitfield.
2927 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00002928 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
2929 E->getOperatorLoc())) {
2930 // Recurse, ignoring any implicit conversions on the RHS.
2931 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
2932 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00002933 }
2934 }
2935
2936 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
2937}
2938
John McCall51313c32010-01-04 23:31:57 +00002939/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00002940void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
2941 SourceLocation CContext, unsigned diag) {
2942 S.Diag(E->getExprLoc(), diag)
2943 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
2944}
2945
Chandler Carruthe1b02e02011-04-05 06:47:57 +00002946/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
2947void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
2948 unsigned diag) {
2949 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag);
2950}
2951
Chandler Carruthf65076e2011-04-10 08:36:24 +00002952/// Diagnose an implicit cast from a literal expression. Also attemps to supply
2953/// fixit hints when the cast wouldn't lose information to simply write the
2954/// expression with the expected type.
2955void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
2956 SourceLocation CContext) {
2957 // Emit the primary warning first, then try to emit a fixit hint note if
2958 // reasonable.
2959 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
2960 << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext);
2961
2962 const llvm::APFloat &Value = FL->getValue();
2963
2964 // Don't attempt to fix PPC double double literals.
2965 if (&Value.getSemantics() == &llvm::APFloat::PPCDoubleDouble)
2966 return;
2967
2968 // Try to convert this exactly to an 64-bit integer. FIXME: It would be
2969 // nice to support arbitrarily large integers here.
2970 bool isExact = false;
2971 uint64_t IntegerPart;
2972 if (Value.convertToInteger(&IntegerPart, 64, /*isSigned=*/true,
2973 llvm::APFloat::rmTowardZero, &isExact)
2974 != llvm::APFloat::opOK || !isExact)
2975 return;
2976
2977 llvm::APInt IntegerValue(64, IntegerPart, /*isSigned=*/true);
2978
2979 std::string LiteralValue = IntegerValue.toString(10, /*isSigned=*/true);
2980 S.Diag(FL->getExprLoc(), diag::note_fix_integral_float_as_integer)
2981 << FixItHint::CreateReplacement(FL->getSourceRange(), LiteralValue);
2982}
2983
John McCall091f23f2010-11-09 22:22:12 +00002984std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
2985 if (!Range.Width) return "0";
2986
2987 llvm::APSInt ValueInRange = Value;
2988 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002989 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00002990 return ValueInRange.toString(10);
2991}
2992
Ted Kremenekef9ff882011-03-10 20:03:42 +00002993static bool isFromSystemMacro(Sema &S, SourceLocation loc) {
2994 SourceManager &smgr = S.Context.getSourceManager();
2995 return loc.isMacroID() && smgr.isInSystemHeader(smgr.getSpellingLoc(loc));
2996}
Chandler Carruthf65076e2011-04-10 08:36:24 +00002997
John McCall323ed742010-05-06 08:58:33 +00002998void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00002999 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00003000 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00003001
John McCall323ed742010-05-06 08:58:33 +00003002 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
3003 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
3004 if (Source == Target) return;
3005 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00003006
Ted Kremenekef9ff882011-03-10 20:03:42 +00003007 // If the conversion context location is invalid don't complain.
3008 // We also don't want to emit a warning if the issue occurs from the
3009 // instantiation of a system macro. The problem is that 'getSpellingLoc()'
3010 // is slow, so we delay this check as long as possible. Once we detect
3011 // we are in that scenario, we just return.
3012 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00003013 return;
3014
John McCall51313c32010-01-04 23:31:57 +00003015 // Never diagnose implicit casts to bool.
3016 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
3017 return;
3018
3019 // Strip vector types.
3020 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003021 if (!isa<VectorType>(Target)) {
3022 if (isFromSystemMacro(S, CC))
3023 return;
John McCallb4eb64d2010-10-08 02:01:28 +00003024 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003025 }
Chris Lattnerb792b302011-06-14 04:51:15 +00003026
3027 // If the vector cast is cast between two vectors of the same size, it is
3028 // a bitcast, not a conversion.
3029 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
3030 return;
John McCall51313c32010-01-04 23:31:57 +00003031
3032 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
3033 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
3034 }
3035
3036 // Strip complex types.
3037 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003038 if (!isa<ComplexType>(Target)) {
3039 if (isFromSystemMacro(S, CC))
3040 return;
3041
John McCallb4eb64d2010-10-08 02:01:28 +00003042 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003043 }
John McCall51313c32010-01-04 23:31:57 +00003044
3045 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
3046 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
3047 }
3048
3049 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
3050 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
3051
3052 // If the source is floating point...
3053 if (SourceBT && SourceBT->isFloatingPoint()) {
3054 // ...and the target is floating point...
3055 if (TargetBT && TargetBT->isFloatingPoint()) {
3056 // ...then warn if we're dropping FP rank.
3057
3058 // Builtin FP kinds are ordered by increasing FP rank.
3059 if (SourceBT->getKind() > TargetBT->getKind()) {
3060 // Don't warn about float constants that are precisely
3061 // representable in the target type.
3062 Expr::EvalResult result;
John McCall323ed742010-05-06 08:58:33 +00003063 if (E->Evaluate(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00003064 // Value might be a float, a float vector, or a float complex.
3065 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00003066 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
3067 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00003068 return;
3069 }
3070
Ted Kremenekef9ff882011-03-10 20:03:42 +00003071 if (isFromSystemMacro(S, CC))
3072 return;
3073
John McCallb4eb64d2010-10-08 02:01:28 +00003074 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00003075 }
3076 return;
3077 }
3078
Ted Kremenekef9ff882011-03-10 20:03:42 +00003079 // If the target is integral, always warn.
Chandler Carrutha5b93322011-02-17 11:05:49 +00003080 if ((TargetBT && TargetBT->isInteger())) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003081 if (isFromSystemMacro(S, CC))
3082 return;
3083
Chandler Carrutha5b93322011-02-17 11:05:49 +00003084 Expr *InnerE = E->IgnoreParenImpCasts();
Chandler Carruthf65076e2011-04-10 08:36:24 +00003085 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
3086 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00003087 } else {
3088 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
3089 }
3090 }
John McCall51313c32010-01-04 23:31:57 +00003091
3092 return;
3093 }
3094
John McCallf2370c92010-01-06 05:24:50 +00003095 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00003096 return;
3097
Richard Trieu1838ca52011-05-29 19:59:02 +00003098 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
3099 == Expr::NPCK_GNUNull) && Target->isIntegerType()) {
3100 S.Diag(E->getExprLoc(), diag::warn_impcast_null_pointer_to_integer)
3101 << E->getSourceRange() << clang::SourceRange(CC);
3102 return;
3103 }
3104
John McCall323ed742010-05-06 08:58:33 +00003105 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00003106 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00003107
3108 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00003109 // If the source is a constant, use a default-on diagnostic.
3110 // TODO: this should happen for bitfield stores, too.
3111 llvm::APSInt Value(32);
3112 if (E->isIntegerConstantExpr(Value, S.Context)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003113 if (isFromSystemMacro(S, CC))
3114 return;
3115
John McCall091f23f2010-11-09 22:22:12 +00003116 std::string PrettySourceValue = Value.toString(10);
3117 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
3118
3119 S.Diag(E->getExprLoc(), diag::warn_impcast_integer_precision_constant)
3120 << PrettySourceValue << PrettyTargetValue
3121 << E->getType() << T << E->getSourceRange() << clang::SourceRange(CC);
3122 return;
3123 }
3124
Chris Lattnerb792b302011-06-14 04:51:15 +00003125 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
Ted Kremenekef9ff882011-03-10 20:03:42 +00003126 if (isFromSystemMacro(S, CC))
3127 return;
3128
John McCallf2370c92010-01-06 05:24:50 +00003129 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCallb4eb64d2010-10-08 02:01:28 +00003130 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32);
3131 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00003132 }
3133
3134 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
3135 (!TargetRange.NonNegative && SourceRange.NonNegative &&
3136 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003137
3138 if (isFromSystemMacro(S, CC))
3139 return;
3140
John McCall323ed742010-05-06 08:58:33 +00003141 unsigned DiagID = diag::warn_impcast_integer_sign;
3142
3143 // Traditionally, gcc has warned about this under -Wsign-compare.
3144 // We also want to warn about it in -Wconversion.
3145 // So if -Wconversion is off, use a completely identical diagnostic
3146 // in the sign-compare group.
3147 // The conditional-checking code will
3148 if (ICContext) {
3149 DiagID = diag::warn_impcast_integer_sign_conditional;
3150 *ICContext = true;
3151 }
3152
John McCallb4eb64d2010-10-08 02:01:28 +00003153 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00003154 }
3155
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003156 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003157 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
3158 // type, to give us better diagnostics.
3159 QualType SourceType = E->getType();
3160 if (!S.getLangOptions().CPlusPlus) {
3161 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3162 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3163 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
3164 SourceType = S.Context.getTypeDeclType(Enum);
3165 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
3166 }
3167 }
3168
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003169 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
3170 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
3171 if ((SourceEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00003172 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003173 (TargetEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00003174 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00003175 SourceEnum != TargetEnum) {
3176 if (isFromSystemMacro(S, CC))
3177 return;
3178
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003179 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003180 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003181 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003182
John McCall51313c32010-01-04 23:31:57 +00003183 return;
3184}
3185
John McCall323ed742010-05-06 08:58:33 +00003186void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
3187
3188void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00003189 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00003190 E = E->IgnoreParenImpCasts();
3191
3192 if (isa<ConditionalOperator>(E))
3193 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
3194
John McCallb4eb64d2010-10-08 02:01:28 +00003195 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003196 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00003197 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00003198 return;
3199}
3200
3201void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00003202 SourceLocation CC = E->getQuestionLoc();
3203
3204 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00003205
3206 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00003207 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
3208 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003209
3210 // If -Wconversion would have warned about either of the candidates
3211 // for a signedness conversion to the context type...
3212 if (!Suspicious) return;
3213
3214 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003215 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
3216 CC))
John McCall323ed742010-05-06 08:58:33 +00003217 return;
3218
3219 // ...and -Wsign-compare isn't...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003220 if (!S.Diags.getDiagnosticLevel(diag::warn_mixed_sign_conditional, CC))
John McCall323ed742010-05-06 08:58:33 +00003221 return;
3222
3223 // ...then check whether it would have warned about either of the
3224 // candidates for a signedness conversion to the condition type.
3225 if (E->getType() != T) {
3226 Suspicious = false;
3227 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00003228 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003229 if (!Suspicious)
3230 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00003231 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003232 if (!Suspicious)
3233 return;
3234 }
3235
3236 // If so, emit a diagnostic under -Wsign-compare.
3237 Expr *lex = E->getTrueExpr()->IgnoreParenImpCasts();
3238 Expr *rex = E->getFalseExpr()->IgnoreParenImpCasts();
3239 S.Diag(E->getQuestionLoc(), diag::warn_mixed_sign_conditional)
3240 << lex->getType() << rex->getType()
3241 << lex->getSourceRange() << rex->getSourceRange();
3242}
3243
3244/// AnalyzeImplicitConversions - Find and report any interesting
3245/// implicit conversions in the given expression. There are a couple
3246/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00003247void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00003248 QualType T = OrigE->getType();
3249 Expr *E = OrigE->IgnoreParenImpCasts();
3250
3251 // For conditional operators, we analyze the arguments as if they
3252 // were being fed directly into the output.
3253 if (isa<ConditionalOperator>(E)) {
3254 ConditionalOperator *CO = cast<ConditionalOperator>(E);
3255 CheckConditionalOperator(S, CO, T);
3256 return;
3257 }
3258
3259 // Go ahead and check any implicit conversions we might have skipped.
3260 // The non-canonical typecheck is just an optimization;
3261 // CheckImplicitConversion will filter out dead implicit conversions.
3262 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00003263 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00003264
3265 // Now continue drilling into this expression.
3266
3267 // Skip past explicit casts.
3268 if (isa<ExplicitCastExpr>(E)) {
3269 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00003270 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003271 }
3272
John McCallbeb22aa2010-11-09 23:24:47 +00003273 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3274 // Do a somewhat different check with comparison operators.
3275 if (BO->isComparisonOp())
3276 return AnalyzeComparison(S, BO);
3277
3278 // And with assignments and compound assignments.
3279 if (BO->isAssignmentOp())
3280 return AnalyzeAssignment(S, BO);
3281 }
John McCall323ed742010-05-06 08:58:33 +00003282
3283 // These break the otherwise-useful invariant below. Fortunately,
3284 // we don't really need to recurse into them, because any internal
3285 // expressions should have been analyzed already when they were
3286 // built into statements.
3287 if (isa<StmtExpr>(E)) return;
3288
3289 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003290 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00003291
3292 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00003293 CC = E->getExprLoc();
John McCall7502c1d2011-02-13 04:07:26 +00003294 for (Stmt::child_range I = E->children(); I; ++I)
John McCallb4eb64d2010-10-08 02:01:28 +00003295 AnalyzeImplicitConversions(S, cast<Expr>(*I), CC);
John McCall323ed742010-05-06 08:58:33 +00003296}
3297
3298} // end anonymous namespace
3299
3300/// Diagnoses "dangerous" implicit conversions within the given
3301/// expression (which is a full expression). Implements -Wconversion
3302/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00003303///
3304/// \param CC the "context" location of the implicit conversion, i.e.
3305/// the most location of the syntactic entity requiring the implicit
3306/// conversion
3307void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00003308 // Don't diagnose in unevaluated contexts.
3309 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
3310 return;
3311
3312 // Don't diagnose for value- or type-dependent expressions.
3313 if (E->isTypeDependent() || E->isValueDependent())
3314 return;
3315
John McCallb4eb64d2010-10-08 02:01:28 +00003316 // This is not the right CC for (e.g.) a variable initialization.
3317 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003318}
3319
John McCall15d7d122010-11-11 03:21:53 +00003320void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
3321 FieldDecl *BitField,
3322 Expr *Init) {
3323 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
3324}
3325
Mike Stumpf8c49212010-01-21 03:59:47 +00003326/// CheckParmsForFunctionDef - Check that the parameters of the given
3327/// function are appropriate for the definition of a function. This
3328/// takes care of any checks that cannot be performed on the
3329/// declaration itself, e.g., that the types of each of the function
3330/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00003331bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
3332 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00003333 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00003334 for (; P != PEnd; ++P) {
3335 ParmVarDecl *Param = *P;
3336
Mike Stumpf8c49212010-01-21 03:59:47 +00003337 // C99 6.7.5.3p4: the parameters in a parameter type list in a
3338 // function declarator that is part of a function definition of
3339 // that function shall not have incomplete type.
3340 //
3341 // This is also C++ [dcl.fct]p6.
3342 if (!Param->isInvalidDecl() &&
3343 RequireCompleteType(Param->getLocation(), Param->getType(),
3344 diag::err_typecheck_decl_incomplete_type)) {
3345 Param->setInvalidDecl();
3346 HasInvalidParm = true;
3347 }
3348
3349 // C99 6.9.1p5: If the declarator includes a parameter type list, the
3350 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00003351 if (CheckParameterNames &&
3352 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00003353 !Param->isImplicit() &&
3354 !getLangOptions().CPlusPlus)
3355 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00003356
3357 // C99 6.7.5.3p12:
3358 // If the function declarator is not part of a definition of that
3359 // function, parameters may have incomplete type and may use the [*]
3360 // notation in their sequences of declarator specifiers to specify
3361 // variable length array types.
3362 QualType PType = Param->getOriginalType();
3363 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
3364 if (AT->getSizeModifier() == ArrayType::Star) {
3365 // FIXME: This diagnosic should point the the '[*]' if source-location
3366 // information is added for it.
3367 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
3368 }
3369 }
Mike Stumpf8c49212010-01-21 03:59:47 +00003370 }
3371
3372 return HasInvalidParm;
3373}
John McCallb7f4ffe2010-08-12 21:44:57 +00003374
3375/// CheckCastAlign - Implements -Wcast-align, which warns when a
3376/// pointer cast increases the alignment requirements.
3377void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
3378 // This is actually a lot of work to potentially be doing on every
3379 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003380 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
3381 TRange.getBegin())
John McCallb7f4ffe2010-08-12 21:44:57 +00003382 == Diagnostic::Ignored)
3383 return;
3384
3385 // Ignore dependent types.
3386 if (T->isDependentType() || Op->getType()->isDependentType())
3387 return;
3388
3389 // Require that the destination be a pointer type.
3390 const PointerType *DestPtr = T->getAs<PointerType>();
3391 if (!DestPtr) return;
3392
3393 // If the destination has alignment 1, we're done.
3394 QualType DestPointee = DestPtr->getPointeeType();
3395 if (DestPointee->isIncompleteType()) return;
3396 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
3397 if (DestAlign.isOne()) return;
3398
3399 // Require that the source be a pointer type.
3400 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
3401 if (!SrcPtr) return;
3402 QualType SrcPointee = SrcPtr->getPointeeType();
3403
3404 // Whitelist casts from cv void*. We already implicitly
3405 // whitelisted casts to cv void*, since they have alignment 1.
3406 // Also whitelist casts involving incomplete types, which implicitly
3407 // includes 'void'.
3408 if (SrcPointee->isIncompleteType()) return;
3409
3410 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
3411 if (SrcAlign >= DestAlign) return;
3412
3413 Diag(TRange.getBegin(), diag::warn_cast_align)
3414 << Op->getType() << T
3415 << static_cast<unsigned>(SrcAlign.getQuantity())
3416 << static_cast<unsigned>(DestAlign.getQuantity())
3417 << TRange << Op->getSourceRange();
3418}
3419
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003420static void CheckArrayAccess_Check(Sema &S,
3421 const clang::ArraySubscriptExpr *E) {
Chandler Carruth35001ca2011-02-17 21:10:52 +00003422 const Expr *BaseExpr = E->getBase()->IgnoreParenImpCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00003423 const ConstantArrayType *ArrayTy =
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003424 S.Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00003425 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00003426 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00003427
Chandler Carruth34064582011-02-17 20:55:08 +00003428 const Expr *IndexExpr = E->getIdx();
3429 if (IndexExpr->isValueDependent())
Ted Kremeneka0125d82011-02-16 01:57:07 +00003430 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003431 llvm::APSInt index;
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003432 if (!IndexExpr->isIntegerConstantExpr(index, S.Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00003433 return;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00003434
Ted Kremenek9e060ca2011-02-23 23:06:04 +00003435 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00003436 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00003437 if (!size.isStrictlyPositive())
3438 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003439 if (size.getBitWidth() > index.getBitWidth())
3440 index = index.sext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00003441 else if (size.getBitWidth() < index.getBitWidth())
3442 size = size.sext(index.getBitWidth());
3443
Chandler Carruth34064582011-02-17 20:55:08 +00003444 if (index.slt(size))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00003445 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003446
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003447 S.DiagRuntimeBehavior(E->getBase()->getLocStart(), BaseExpr,
3448 S.PDiag(diag::warn_array_index_exceeds_bounds)
3449 << index.toString(10, true)
3450 << size.toString(10, true)
3451 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00003452 } else {
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003453 S.DiagRuntimeBehavior(E->getBase()->getLocStart(), BaseExpr,
3454 S.PDiag(diag::warn_array_index_precedes_bounds)
3455 << index.toString(10, true)
3456 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00003457 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00003458
3459 const NamedDecl *ND = NULL;
3460 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
3461 ND = dyn_cast<NamedDecl>(DRE->getDecl());
3462 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
3463 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
3464 if (ND)
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003465 S.DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
3466 S.PDiag(diag::note_array_index_out_of_bounds)
3467 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00003468}
3469
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003470void Sema::CheckArrayAccess(const Expr *expr) {
Peter Collingbournef111d932011-04-15 00:35:48 +00003471 while (true) {
3472 expr = expr->IgnoreParens();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003473 switch (expr->getStmtClass()) {
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003474 case Stmt::ArraySubscriptExprClass:
3475 CheckArrayAccess_Check(*this, cast<ArraySubscriptExpr>(expr));
3476 return;
3477 case Stmt::ConditionalOperatorClass: {
3478 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
3479 if (const Expr *lhs = cond->getLHS())
3480 CheckArrayAccess(lhs);
3481 if (const Expr *rhs = cond->getRHS())
3482 CheckArrayAccess(rhs);
3483 return;
3484 }
3485 default:
3486 return;
3487 }
Peter Collingbournef111d932011-04-15 00:35:48 +00003488 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003489}
John McCallf85e1932011-06-15 23:02:42 +00003490
3491//===--- CHECK: Objective-C retain cycles ----------------------------------//
3492
3493namespace {
3494 struct RetainCycleOwner {
3495 RetainCycleOwner() : Variable(0), Indirect(false) {}
3496 VarDecl *Variable;
3497 SourceRange Range;
3498 SourceLocation Loc;
3499 bool Indirect;
3500
3501 void setLocsFrom(Expr *e) {
3502 Loc = e->getExprLoc();
3503 Range = e->getSourceRange();
3504 }
3505 };
3506}
3507
3508/// Consider whether capturing the given variable can possibly lead to
3509/// a retain cycle.
3510static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
3511 // In ARC, it's captured strongly iff the variable has __strong
3512 // lifetime. In MRR, it's captured strongly if the variable is
3513 // __block and has an appropriate type.
3514 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
3515 return false;
3516
3517 owner.Variable = var;
3518 owner.setLocsFrom(ref);
3519 return true;
3520}
3521
3522static bool findRetainCycleOwner(Expr *e, RetainCycleOwner &owner) {
3523 while (true) {
3524 e = e->IgnoreParens();
3525 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
3526 switch (cast->getCastKind()) {
3527 case CK_BitCast:
3528 case CK_LValueBitCast:
3529 case CK_LValueToRValue:
3530 e = cast->getSubExpr();
3531 continue;
3532
3533 case CK_GetObjCProperty: {
3534 // Bail out if this isn't a strong explicit property.
3535 const ObjCPropertyRefExpr *pre = cast->getSubExpr()->getObjCProperty();
3536 if (pre->isImplicitProperty()) return false;
3537 ObjCPropertyDecl *property = pre->getExplicitProperty();
3538 if (!(property->getPropertyAttributes() &
3539 (ObjCPropertyDecl::OBJC_PR_retain |
3540 ObjCPropertyDecl::OBJC_PR_copy |
3541 ObjCPropertyDecl::OBJC_PR_strong)) &&
3542 !(property->getPropertyIvarDecl() &&
3543 property->getPropertyIvarDecl()->getType()
3544 .getObjCLifetime() == Qualifiers::OCL_Strong))
3545 return false;
3546
3547 owner.Indirect = true;
3548 e = const_cast<Expr*>(pre->getBase());
3549 continue;
3550 }
3551
3552 default:
3553 return false;
3554 }
3555 }
3556
3557 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
3558 ObjCIvarDecl *ivar = ref->getDecl();
3559 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
3560 return false;
3561
3562 // Try to find a retain cycle in the base.
3563 if (!findRetainCycleOwner(ref->getBase(), owner))
3564 return false;
3565
3566 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
3567 owner.Indirect = true;
3568 return true;
3569 }
3570
3571 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
3572 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
3573 if (!var) return false;
3574 return considerVariable(var, ref, owner);
3575 }
3576
3577 if (BlockDeclRefExpr *ref = dyn_cast<BlockDeclRefExpr>(e)) {
3578 owner.Variable = ref->getDecl();
3579 owner.setLocsFrom(ref);
3580 return true;
3581 }
3582
3583 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
3584 if (member->isArrow()) return false;
3585
3586 // Don't count this as an indirect ownership.
3587 e = member->getBase();
3588 continue;
3589 }
3590
3591 // Array ivars?
3592
3593 return false;
3594 }
3595}
3596
3597namespace {
3598 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
3599 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
3600 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
3601 Variable(variable), Capturer(0) {}
3602
3603 VarDecl *Variable;
3604 Expr *Capturer;
3605
3606 void VisitDeclRefExpr(DeclRefExpr *ref) {
3607 if (ref->getDecl() == Variable && !Capturer)
3608 Capturer = ref;
3609 }
3610
3611 void VisitBlockDeclRefExpr(BlockDeclRefExpr *ref) {
3612 if (ref->getDecl() == Variable && !Capturer)
3613 Capturer = ref;
3614 }
3615
3616 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
3617 if (Capturer) return;
3618 Visit(ref->getBase());
3619 if (Capturer && ref->isFreeIvar())
3620 Capturer = ref;
3621 }
3622
3623 void VisitBlockExpr(BlockExpr *block) {
3624 // Look inside nested blocks
3625 if (block->getBlockDecl()->capturesVariable(Variable))
3626 Visit(block->getBlockDecl()->getBody());
3627 }
3628 };
3629}
3630
3631/// Check whether the given argument is a block which captures a
3632/// variable.
3633static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
3634 assert(owner.Variable && owner.Loc.isValid());
3635
3636 e = e->IgnoreParenCasts();
3637 BlockExpr *block = dyn_cast<BlockExpr>(e);
3638 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
3639 return 0;
3640
3641 FindCaptureVisitor visitor(S.Context, owner.Variable);
3642 visitor.Visit(block->getBlockDecl()->getBody());
3643 return visitor.Capturer;
3644}
3645
3646static void diagnoseRetainCycle(Sema &S, Expr *capturer,
3647 RetainCycleOwner &owner) {
3648 assert(capturer);
3649 assert(owner.Variable && owner.Loc.isValid());
3650
3651 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
3652 << owner.Variable << capturer->getSourceRange();
3653 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
3654 << owner.Indirect << owner.Range;
3655}
3656
3657/// Check for a keyword selector that starts with the word 'add' or
3658/// 'set'.
3659static bool isSetterLikeSelector(Selector sel) {
3660 if (sel.isUnarySelector()) return false;
3661
3662 llvm::StringRef str = sel.getNameForSlot(0);
3663 while (!str.empty() && str.front() == '_') str = str.substr(1);
3664 if (str.startswith("set") || str.startswith("add"))
3665 str = str.substr(3);
3666 else
3667 return false;
3668
3669 if (str.empty()) return true;
3670 return !islower(str.front());
3671}
3672
3673/// Check a message send to see if it's likely to cause a retain cycle.
3674void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
3675 // Only check instance methods whose selector looks like a setter.
3676 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
3677 return;
3678
3679 // Try to find a variable that the receiver is strongly owned by.
3680 RetainCycleOwner owner;
3681 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
3682 if (!findRetainCycleOwner(msg->getInstanceReceiver(), owner))
3683 return;
3684 } else {
3685 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
3686 owner.Variable = getCurMethodDecl()->getSelfDecl();
3687 owner.Loc = msg->getSuperLoc();
3688 owner.Range = msg->getSuperLoc();
3689 }
3690
3691 // Check whether the receiver is captured by any of the arguments.
3692 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
3693 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
3694 return diagnoseRetainCycle(*this, capturer, owner);
3695}
3696
3697/// Check a property assign to see if it's likely to cause a retain cycle.
3698void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
3699 RetainCycleOwner owner;
3700 if (!findRetainCycleOwner(receiver, owner))
3701 return;
3702
3703 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
3704 diagnoseRetainCycle(*this, capturer, owner);
3705}
3706
3707void Sema::checkUnsafeAssigns(SourceLocation Loc,
3708 QualType LHS, Expr *RHS) {
3709 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
3710 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
3711 return;
3712 if (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS))
3713 if (cast->getCastKind() == CK_ObjCConsumeObject)
3714 Diag(Loc, diag::warn_arc_retained_assign)
3715 << (LT == Qualifiers::OCL_ExplicitNone)
3716 << RHS->getSourceRange();
3717}
3718