blob: 81506bf571ab7e51fb6711c22d0b827914c85d87 [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
323 if (FDecl->getLinkage() == ExternalLinkage &&
324 (!getLangOptions().CPlusPlus || FDecl->isExternC())) {
325 if (FnInfo->isStr("memset") || FnInfo->isStr("memcpy") ||
326 FnInfo->isStr("memmove"))
327 CheckMemsetcpymoveArguments(TheCall, FnInfo);
328 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000329
Anders Carlssond406bf02009-08-16 01:56:34 +0000330 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000331}
332
Anders Carlssond406bf02009-08-16 01:56:34 +0000333bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000334 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000335 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000336 if (!Format)
Anders Carlssond406bf02009-08-16 01:56:34 +0000337 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000338
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000339 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
340 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000341 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000342
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000343 QualType Ty = V->getType();
344 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000345 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000346
Ted Kremenek826a3452010-07-16 02:11:22 +0000347 const bool b = Format->getType() == "scanf";
348 if (!b && !CheckablePrintfAttr(Format, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +0000349 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000350
Anders Carlssond406bf02009-08-16 01:56:34 +0000351 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek826a3452010-07-16 02:11:22 +0000352 CheckPrintfScanfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
353 HasVAListArg ? 0 : Format->getFirstArg() - 1, !b);
Anders Carlssond406bf02009-08-16 01:56:34 +0000354
355 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000356}
357
Chris Lattner5caa3702009-05-08 06:58:22 +0000358/// SemaBuiltinAtomicOverloaded - We have a call to a function like
359/// __sync_fetch_and_add, which is an overloaded function based on the pointer
360/// type of its first argument. The main ActOnCallExpr routines have already
361/// promoted the types of arguments because all of these calls are prototyped as
362/// void(...).
363///
364/// This function goes through and does final semantic checking for these
365/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000366ExprResult
367Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000368 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000369 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
370 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
371
372 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000373 if (TheCall->getNumArgs() < 1) {
374 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
375 << 0 << 1 << TheCall->getNumArgs()
376 << TheCall->getCallee()->getSourceRange();
377 return ExprError();
378 }
Mike Stump1eb44332009-09-09 15:08:12 +0000379
Chris Lattner5caa3702009-05-08 06:58:22 +0000380 // Inspect the first argument of the atomic builtin. This should always be
381 // a pointer type, whose element is an integral scalar or pointer type.
382 // Because it is a pointer type, we don't have to worry about any implicit
383 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000384 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000385 Expr *FirstArg = TheCall->getArg(0);
John McCallf85e1932011-06-15 23:02:42 +0000386 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
387 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000388 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
389 << FirstArg->getType() << FirstArg->getSourceRange();
390 return ExprError();
391 }
Mike Stump1eb44332009-09-09 15:08:12 +0000392
John McCallf85e1932011-06-15 23:02:42 +0000393 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000394 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000395 !ValType->isBlockPointerType()) {
396 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
397 << FirstArg->getType() << FirstArg->getSourceRange();
398 return ExprError();
399 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000400
John McCallf85e1932011-06-15 23:02:42 +0000401 switch (ValType.getObjCLifetime()) {
402 case Qualifiers::OCL_None:
403 case Qualifiers::OCL_ExplicitNone:
404 // okay
405 break;
406
407 case Qualifiers::OCL_Weak:
408 case Qualifiers::OCL_Strong:
409 case Qualifiers::OCL_Autoreleasing:
410 Diag(DRE->getLocStart(), diag::err_arc_atomic_lifetime)
411 << ValType << FirstArg->getSourceRange();
412 return ExprError();
413 }
414
Chandler Carruth8d13d222010-07-18 20:54:12 +0000415 // The majority of builtins return a value, but a few have special return
416 // types, so allow them to override appropriately below.
417 QualType ResultType = ValType;
418
Chris Lattner5caa3702009-05-08 06:58:22 +0000419 // We need to figure out which concrete builtin this maps onto. For example,
420 // __sync_fetch_and_add with a 2 byte object turns into
421 // __sync_fetch_and_add_2.
422#define BUILTIN_ROW(x) \
423 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
424 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000425
Chris Lattner5caa3702009-05-08 06:58:22 +0000426 static const unsigned BuiltinIndices[][5] = {
427 BUILTIN_ROW(__sync_fetch_and_add),
428 BUILTIN_ROW(__sync_fetch_and_sub),
429 BUILTIN_ROW(__sync_fetch_and_or),
430 BUILTIN_ROW(__sync_fetch_and_and),
431 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +0000432
Chris Lattner5caa3702009-05-08 06:58:22 +0000433 BUILTIN_ROW(__sync_add_and_fetch),
434 BUILTIN_ROW(__sync_sub_and_fetch),
435 BUILTIN_ROW(__sync_and_and_fetch),
436 BUILTIN_ROW(__sync_or_and_fetch),
437 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000438
Chris Lattner5caa3702009-05-08 06:58:22 +0000439 BUILTIN_ROW(__sync_val_compare_and_swap),
440 BUILTIN_ROW(__sync_bool_compare_and_swap),
441 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +0000442 BUILTIN_ROW(__sync_lock_release),
443 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +0000444 };
Mike Stump1eb44332009-09-09 15:08:12 +0000445#undef BUILTIN_ROW
446
Chris Lattner5caa3702009-05-08 06:58:22 +0000447 // Determine the index of the size.
448 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000449 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000450 case 1: SizeIndex = 0; break;
451 case 2: SizeIndex = 1; break;
452 case 4: SizeIndex = 2; break;
453 case 8: SizeIndex = 3; break;
454 case 16: SizeIndex = 4; break;
455 default:
Chandler Carruthd2014572010-07-09 18:59:35 +0000456 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
457 << FirstArg->getType() << FirstArg->getSourceRange();
458 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +0000459 }
Mike Stump1eb44332009-09-09 15:08:12 +0000460
Chris Lattner5caa3702009-05-08 06:58:22 +0000461 // Each of these builtins has one pointer argument, followed by some number of
462 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
463 // that we ignore. Find out which row of BuiltinIndices to read from as well
464 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000465 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000466 unsigned BuiltinIndex, NumFixed = 1;
467 switch (BuiltinID) {
468 default: assert(0 && "Unknown overloaded atomic builtin!");
469 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
470 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
471 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
472 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
473 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000474
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000475 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
476 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
477 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
478 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 8; break;
479 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000480
Chris Lattner5caa3702009-05-08 06:58:22 +0000481 case Builtin::BI__sync_val_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000482 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +0000483 NumFixed = 2;
484 break;
485 case Builtin::BI__sync_bool_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000486 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +0000487 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000488 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000489 break;
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000490 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000491 case Builtin::BI__sync_lock_release:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000492 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000493 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000494 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000495 break;
Chris Lattner23aa9c82011-04-09 03:57:26 +0000496 case Builtin::BI__sync_swap: BuiltinIndex = 14; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000497 }
Mike Stump1eb44332009-09-09 15:08:12 +0000498
Chris Lattner5caa3702009-05-08 06:58:22 +0000499 // Now that we know how many fixed arguments we expect, first check that we
500 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +0000501 if (TheCall->getNumArgs() < 1+NumFixed) {
502 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
503 << 0 << 1+NumFixed << TheCall->getNumArgs()
504 << TheCall->getCallee()->getSourceRange();
505 return ExprError();
506 }
Mike Stump1eb44332009-09-09 15:08:12 +0000507
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000508 // Get the decl for the concrete builtin from this, we can tell what the
509 // concrete integer type we should convert to is.
510 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
511 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
512 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +0000513 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000514 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
515 TUScope, false, DRE->getLocStart()));
Chandler Carruthd2014572010-07-09 18:59:35 +0000516
John McCallf871d0c2010-08-07 06:22:56 +0000517 // The first argument --- the pointer --- has a fixed type; we
518 // deduce the types of the rest of the arguments accordingly. Walk
519 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +0000520 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +0000521 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +0000522
Chris Lattner5caa3702009-05-08 06:58:22 +0000523 // If the argument is an implicit cast, then there was a promotion due to
524 // "...", just remove it now.
John Wiegley429bb272011-04-08 18:41:53 +0000525 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg.get())) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000526 Arg = ICE->getSubExpr();
527 ICE->setSubExpr(0);
John Wiegley429bb272011-04-08 18:41:53 +0000528 TheCall->setArg(i+1, Arg.get());
Chris Lattner5caa3702009-05-08 06:58:22 +0000529 }
Mike Stump1eb44332009-09-09 15:08:12 +0000530
Chris Lattner5caa3702009-05-08 06:58:22 +0000531 // GCC does an implicit conversion to the pointer or integer ValType. This
532 // can fail in some cases (1i -> int**), check for this error case now.
John McCalldaa8e4e2010-11-15 09:13:47 +0000533 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +0000534 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +0000535 CXXCastPath BasePath;
John McCallf85e1932011-06-15 23:02:42 +0000536 Arg = CheckCastTypes(Arg.get()->getLocStart(), Arg.get()->getSourceRange(),
537 ValType, Arg.take(), Kind, VK, BasePath);
John Wiegley429bb272011-04-08 18:41:53 +0000538 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +0000539 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000540
Chris Lattner5caa3702009-05-08 06:58:22 +0000541 // Okay, we have something that *can* be converted to the right type. Check
542 // to see if there is a potentially weird extension going on here. This can
543 // happen when you do an atomic operation on something like an char* and
544 // pass in 42. The 42 gets converted to char. This is even more strange
545 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +0000546 // FIXME: Do this check.
John Wiegley429bb272011-04-08 18:41:53 +0000547 Arg = ImpCastExprToType(Arg.take(), ValType, Kind, VK, &BasePath);
548 TheCall->setArg(i+1, Arg.get());
Chris Lattner5caa3702009-05-08 06:58:22 +0000549 }
Mike Stump1eb44332009-09-09 15:08:12 +0000550
Chris Lattner5caa3702009-05-08 06:58:22 +0000551 // Switch the DeclRefExpr to refer to the new decl.
552 DRE->setDecl(NewBuiltinDecl);
553 DRE->setType(NewBuiltinDecl->getType());
Mike Stump1eb44332009-09-09 15:08:12 +0000554
Chris Lattner5caa3702009-05-08 06:58:22 +0000555 // Set the callee in the CallExpr.
556 // FIXME: This leaks the original parens and implicit casts.
John Wiegley429bb272011-04-08 18:41:53 +0000557 ExprResult PromotedCall = UsualUnaryConversions(DRE);
558 if (PromotedCall.isInvalid())
559 return ExprError();
560 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +0000561
Chandler Carruthdb4325b2010-07-18 07:23:17 +0000562 // Change the result type of the call to match the original value type. This
563 // is arbitrary, but the codegen for these builtins ins design to handle it
564 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +0000565 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +0000566
567 return move(TheCallResult);
Chris Lattner5caa3702009-05-08 06:58:22 +0000568}
569
570
Chris Lattner69039812009-02-18 06:01:06 +0000571/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000572/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +0000573/// Note: It might also make sense to do the UTF-16 conversion here (would
574/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +0000575bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000576 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000577 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
578
579 if (!Literal || Literal->isWide()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000580 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
581 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000582 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000583 }
Mike Stump1eb44332009-09-09 15:08:12 +0000584
Fariborz Jahanian7da71022010-09-07 19:38:13 +0000585 if (Literal->containsNonAsciiOrNull()) {
586 llvm::StringRef String = Literal->getString();
587 unsigned NumBytes = String.size();
588 llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
589 const UTF8 *FromPtr = (UTF8 *)String.data();
590 UTF16 *ToPtr = &ToBuf[0];
591
592 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
593 &ToPtr, ToPtr + NumBytes,
594 strictConversion);
595 // Check for conversion failure.
596 if (Result != conversionOK)
597 Diag(Arg->getLocStart(),
598 diag::warn_cfstring_truncated) << Arg->getSourceRange();
599 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000600 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000601}
602
Chris Lattnerc27c6652007-12-20 00:05:45 +0000603/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
604/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000605bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
606 Expr *Fn = TheCall->getCallee();
607 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000608 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000609 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000610 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
611 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +0000612 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000613 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000614 return true;
615 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000616
617 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +0000618 return Diag(TheCall->getLocEnd(),
619 diag::err_typecheck_call_too_few_args_at_least)
620 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000621 }
622
Chris Lattnerc27c6652007-12-20 00:05:45 +0000623 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000624 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +0000625 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000626 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +0000627 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +0000628 else if (FunctionDecl *FD = getCurFunctionDecl())
629 isVariadic = FD->isVariadic();
630 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000631 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +0000632
Chris Lattnerc27c6652007-12-20 00:05:45 +0000633 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000634 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
635 return true;
636 }
Mike Stump1eb44332009-09-09 15:08:12 +0000637
Chris Lattner30ce3442007-12-19 23:59:04 +0000638 // Verify that the second argument to the builtin is the last argument of the
639 // current function or method.
640 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000641 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +0000642
Anders Carlsson88cf2262008-02-11 04:20:54 +0000643 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
644 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000645 // FIXME: This isn't correct for methods (results in bogus warning).
646 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000647 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000648 if (CurBlock)
649 LastArg = *(CurBlock->TheDecl->param_end()-1);
650 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +0000651 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000652 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000653 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000654 SecondArgIsLastNamedArgument = PV == LastArg;
655 }
656 }
Mike Stump1eb44332009-09-09 15:08:12 +0000657
Chris Lattner30ce3442007-12-19 23:59:04 +0000658 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +0000659 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000660 diag::warn_second_parameter_of_va_start_not_last_named_argument);
661 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000662}
Chris Lattner30ce3442007-12-19 23:59:04 +0000663
Chris Lattner1b9a0792007-12-20 00:26:33 +0000664/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
665/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000666bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
667 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000668 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000669 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000670 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +0000671 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000672 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000673 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000674 << SourceRange(TheCall->getArg(2)->getLocStart(),
675 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000676
John Wiegley429bb272011-04-08 18:41:53 +0000677 ExprResult OrigArg0 = TheCall->getArg(0);
678 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000679
Chris Lattner1b9a0792007-12-20 00:26:33 +0000680 // Do standard promotions between the two arguments, returning their common
681 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000682 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +0000683 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
684 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +0000685
686 // Make sure any conversions are pushed back into the call; this is
687 // type safe since unordered compare builtins are declared as "_Bool
688 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +0000689 TheCall->setArg(0, OrigArg0.get());
690 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +0000691
John Wiegley429bb272011-04-08 18:41:53 +0000692 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +0000693 return false;
694
Chris Lattner1b9a0792007-12-20 00:26:33 +0000695 // If the common type isn't a real floating type, then the arguments were
696 // invalid for this operation.
697 if (!Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +0000698 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000699 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +0000700 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
701 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000702
Chris Lattner1b9a0792007-12-20 00:26:33 +0000703 return false;
704}
705
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000706/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
707/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000708/// to check everything. We expect the last argument to be a floating point
709/// value.
710bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
711 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +0000712 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000713 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000714 if (TheCall->getNumArgs() > NumArgs)
715 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000716 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000717 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000718 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000719 (*(TheCall->arg_end()-1))->getLocEnd());
720
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000721 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +0000722
Eli Friedman9ac6f622009-08-31 20:06:00 +0000723 if (OrigArg->isTypeDependent())
724 return false;
725
Chris Lattner81368fb2010-05-06 05:50:07 +0000726 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +0000727 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000728 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000729 diag::err_typecheck_call_invalid_unary_fp)
730 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000731
Chris Lattner81368fb2010-05-06 05:50:07 +0000732 // If this is an implicit conversion from float -> double, remove it.
733 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
734 Expr *CastArg = Cast->getSubExpr();
735 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
736 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
737 "promotion from float to double is the only expected cast here");
738 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +0000739 TheCall->setArg(NumArgs-1, CastArg);
740 OrigArg = CastArg;
741 }
742 }
743
Eli Friedman9ac6f622009-08-31 20:06:00 +0000744 return false;
745}
746
Eli Friedmand38617c2008-05-14 19:38:39 +0000747/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
748// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +0000749ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000750 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000751 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +0000752 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +0000753 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +0000754 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000755
Nate Begeman37b6a572010-06-08 00:16:34 +0000756 // Determine which of the following types of shufflevector we're checking:
757 // 1) unary, vector mask: (lhs, mask)
758 // 2) binary, vector mask: (lhs, rhs, mask)
759 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
760 QualType resType = TheCall->getArg(0)->getType();
761 unsigned numElements = 0;
762
Douglas Gregorcde01732009-05-19 22:10:17 +0000763 if (!TheCall->getArg(0)->isTypeDependent() &&
764 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000765 QualType LHSType = TheCall->getArg(0)->getType();
766 QualType RHSType = TheCall->getArg(1)->getType();
767
768 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000769 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000770 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000771 TheCall->getArg(1)->getLocEnd());
772 return ExprError();
773 }
Nate Begeman37b6a572010-06-08 00:16:34 +0000774
775 numElements = LHSType->getAs<VectorType>()->getNumElements();
776 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +0000777
Nate Begeman37b6a572010-06-08 00:16:34 +0000778 // Check to see if we have a call with 2 vector arguments, the unary shuffle
779 // with mask. If so, verify that RHS is an integer vector type with the
780 // same number of elts as lhs.
781 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +0000782 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +0000783 RHSType->getAs<VectorType>()->getNumElements() != numElements)
784 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
785 << SourceRange(TheCall->getArg(1)->getLocStart(),
786 TheCall->getArg(1)->getLocEnd());
787 numResElements = numElements;
788 }
789 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000790 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000791 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000792 TheCall->getArg(1)->getLocEnd());
793 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +0000794 } else if (numElements != numResElements) {
795 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +0000796 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +0000797 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +0000798 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000799 }
800
801 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000802 if (TheCall->getArg(i)->isTypeDependent() ||
803 TheCall->getArg(i)->isValueDependent())
804 continue;
805
Nate Begeman37b6a572010-06-08 00:16:34 +0000806 llvm::APSInt Result(32);
807 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
808 return ExprError(Diag(TheCall->getLocStart(),
809 diag::err_shufflevector_nonconstant_argument)
810 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000811
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000812 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000813 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000814 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000815 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000816 }
817
818 llvm::SmallVector<Expr*, 32> exprs;
819
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000820 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000821 exprs.push_back(TheCall->getArg(i));
822 TheCall->setArg(i, 0);
823 }
824
Nate Begemana88dc302009-08-12 02:10:25 +0000825 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begeman37b6a572010-06-08 00:16:34 +0000826 exprs.size(), resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000827 TheCall->getCallee()->getLocStart(),
828 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000829}
Chris Lattner30ce3442007-12-19 23:59:04 +0000830
Daniel Dunbar4493f792008-07-21 22:59:13 +0000831/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
832// This is declared to take (const void*, ...) and can take two
833// optional constant int args.
834bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000835 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000836
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000837 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +0000838 return Diag(TheCall->getLocEnd(),
839 diag::err_typecheck_call_too_many_args_at_most)
840 << 0 /*function call*/ << 3 << NumArgs
841 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000842
843 // Argument 0 is checked for us and the remaining arguments must be
844 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000845 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000846 Expr *Arg = TheCall->getArg(i);
Eric Christopher691ebc32010-04-17 02:26:23 +0000847
Eli Friedman9aef7262009-12-04 00:30:06 +0000848 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +0000849 if (SemaBuiltinConstantArg(TheCall, i, Result))
850 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000851
Daniel Dunbar4493f792008-07-21 22:59:13 +0000852 // FIXME: gcc issues a warning and rewrites these to 0. These
853 // seems especially odd for the third argument since the default
854 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000855 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +0000856 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000857 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000858 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000859 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +0000860 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000861 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000862 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000863 }
864 }
865
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000866 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000867}
868
Eric Christopher691ebc32010-04-17 02:26:23 +0000869/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
870/// TheCall is a constant expression.
871bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
872 llvm::APSInt &Result) {
873 Expr *Arg = TheCall->getArg(ArgNum);
874 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
875 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
876
877 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
878
879 if (!Arg->isIntegerConstantExpr(Result, Context))
880 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +0000881 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +0000882
Chris Lattner21fb98e2009-09-23 06:06:36 +0000883 return false;
884}
885
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000886/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
887/// int type). This simply type checks that type is one of the defined
888/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000889// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000890bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +0000891 llvm::APSInt Result;
892
893 // Check constant-ness first.
894 if (SemaBuiltinConstantArg(TheCall, 1, Result))
895 return true;
896
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000897 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000898 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000899 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
900 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000901 }
902
903 return false;
904}
905
Eli Friedman586d6a82009-05-03 06:04:26 +0000906/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +0000907/// This checks that val is a constant 1.
908bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
909 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +0000910 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +0000911
Eric Christopher691ebc32010-04-17 02:26:23 +0000912 // TODO: This is less than ideal. Overload this to take a value.
913 if (SemaBuiltinConstantArg(TheCall, 1, Result))
914 return true;
915
916 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +0000917 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
918 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
919
920 return false;
921}
922
Ted Kremenekb43e8ad2011-02-24 23:03:04 +0000923// Handle i > 1 ? "x" : "y", recursively.
Ted Kremenek082d9362009-03-20 21:35:28 +0000924bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
925 bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +0000926 unsigned format_idx, unsigned firstDataArg,
927 bool isPrintf) {
Ted Kremenek4fe64412010-09-09 03:51:39 +0000928 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +0000929 if (E->isTypeDependent() || E->isValueDependent())
930 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000931
Peter Collingbournef111d932011-04-15 00:35:48 +0000932 E = E->IgnoreParens();
933
Ted Kremenekd30ef872009-01-12 23:09:09 +0000934 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +0000935 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +0000936 case Stmt::ConditionalOperatorClass: {
John McCall56ca35d2011-02-17 10:25:35 +0000937 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
Ted Kremenek826a3452010-07-16 02:11:22 +0000938 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg,
939 format_idx, firstDataArg, isPrintf)
John McCall56ca35d2011-02-17 10:25:35 +0000940 && SemaCheckStringLiteral(C->getFalseExpr(), TheCall, HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +0000941 format_idx, firstDataArg, isPrintf);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000942 }
943
Ted Kremenek95355bb2010-09-09 03:51:42 +0000944 case Stmt::IntegerLiteralClass:
945 // Technically -Wformat-nonliteral does not warn about this case.
946 // The behavior of printf and friends in this case is implementation
947 // dependent. Ideally if the format string cannot be null then
948 // it should have a 'nonnull' attribute in the function prototype.
949 return true;
950
Ted Kremenekd30ef872009-01-12 23:09:09 +0000951 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +0000952 E = cast<ImplicitCastExpr>(E)->getSubExpr();
953 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000954 }
955
John McCall56ca35d2011-02-17 10:25:35 +0000956 case Stmt::OpaqueValueExprClass:
957 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
958 E = src;
959 goto tryAgain;
960 }
961 return false;
962
Ted Kremenekb43e8ad2011-02-24 23:03:04 +0000963 case Stmt::PredefinedExprClass:
964 // While __func__, etc., are technically not string literals, they
965 // cannot contain format specifiers and thus are not a security
966 // liability.
967 return true;
968
Ted Kremenek082d9362009-03-20 21:35:28 +0000969 case Stmt::DeclRefExprClass: {
970 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000971
Ted Kremenek082d9362009-03-20 21:35:28 +0000972 // As an exception, do not flag errors for variables binding to
973 // const string literals.
974 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
975 bool isConstant = false;
976 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +0000977
Ted Kremenek082d9362009-03-20 21:35:28 +0000978 if (const ArrayType *AT = Context.getAsArrayType(T)) {
979 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000980 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000981 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +0000982 PT->getPointeeType().isConstant(Context);
983 }
Mike Stump1eb44332009-09-09 15:08:12 +0000984
Ted Kremenek082d9362009-03-20 21:35:28 +0000985 if (isConstant) {
Sebastian Redl31310a22010-02-01 20:16:42 +0000986 if (const Expr *Init = VD->getAnyInitializer())
Ted Kremenek082d9362009-03-20 21:35:28 +0000987 return SemaCheckStringLiteral(Init, TheCall,
Ted Kremenek826a3452010-07-16 02:11:22 +0000988 HasVAListArg, format_idx, firstDataArg,
989 isPrintf);
Ted Kremenek082d9362009-03-20 21:35:28 +0000990 }
Mike Stump1eb44332009-09-09 15:08:12 +0000991
Anders Carlssond966a552009-06-28 19:55:58 +0000992 // For vprintf* functions (i.e., HasVAListArg==true), we add a
993 // special check to see if the format string is a function parameter
994 // of the function calling the printf function. If the function
995 // has an attribute indicating it is a printf-like function, then we
996 // should suppress warnings concerning non-literals being used in a call
997 // to a vprintf function. For example:
998 //
999 // void
1000 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1001 // va_list ap;
1002 // va_start(ap, fmt);
1003 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1004 // ...
1005 //
1006 //
1007 // FIXME: We don't have full attribute support yet, so just check to see
1008 // if the argument is a DeclRefExpr that references a parameter. We'll
1009 // add proper support for checking the attribute later.
1010 if (HasVAListArg)
1011 if (isa<ParmVarDecl>(VD))
1012 return true;
Ted Kremenek082d9362009-03-20 21:35:28 +00001013 }
Mike Stump1eb44332009-09-09 15:08:12 +00001014
Ted Kremenek082d9362009-03-20 21:35:28 +00001015 return false;
1016 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001017
Anders Carlsson8f031b32009-06-27 04:05:33 +00001018 case Stmt::CallExprClass: {
1019 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001020 if (const ImplicitCastExpr *ICE
Anders Carlsson8f031b32009-06-27 04:05:33 +00001021 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
1022 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
1023 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001024 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001025 unsigned ArgIndex = FA->getFormatIdx();
1026 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001027
1028 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001029 format_idx, firstDataArg, isPrintf);
Anders Carlsson8f031b32009-06-27 04:05:33 +00001030 }
1031 }
1032 }
1033 }
Mike Stump1eb44332009-09-09 15:08:12 +00001034
Anders Carlsson8f031b32009-06-27 04:05:33 +00001035 return false;
1036 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001037 case Stmt::ObjCStringLiteralClass:
1038 case Stmt::StringLiteralClass: {
1039 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001040
Ted Kremenek082d9362009-03-20 21:35:28 +00001041 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001042 StrE = ObjCFExpr->getString();
1043 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001044 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001045
Ted Kremenekd30ef872009-01-12 23:09:09 +00001046 if (StrE) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001047 CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx,
1048 firstDataArg, isPrintf);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001049 return true;
1050 }
Mike Stump1eb44332009-09-09 15:08:12 +00001051
Ted Kremenekd30ef872009-01-12 23:09:09 +00001052 return false;
1053 }
Mike Stump1eb44332009-09-09 15:08:12 +00001054
Ted Kremenek082d9362009-03-20 21:35:28 +00001055 default:
1056 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001057 }
1058}
1059
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001060void
Mike Stump1eb44332009-09-09 15:08:12 +00001061Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001062 const Expr * const *ExprArgs,
1063 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001064 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1065 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001066 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001067 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001068 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001069 Expr::NPC_ValueDependentIsNotNull))
Nick Lewycky909a70d2011-03-25 01:44:32 +00001070 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001071 }
1072}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001073
Ted Kremenek826a3452010-07-16 02:11:22 +00001074/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1075/// functions) for correct use of format strings.
Chris Lattner59907c42007-08-10 20:18:51 +00001076void
Ted Kremenek826a3452010-07-16 02:11:22 +00001077Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
1078 unsigned format_idx, unsigned firstDataArg,
1079 bool isPrintf) {
1080
Ted Kremenek082d9362009-03-20 21:35:28 +00001081 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +00001082
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001083 // The way the format attribute works in GCC, the implicit this argument
1084 // of member functions is counted. However, it doesn't appear in our own
1085 // lists, so decrement format_idx in that case.
1086 if (isa<CXXMemberCallExpr>(TheCall)) {
Chandler Carruth9263a302010-11-16 08:49:43 +00001087 const CXXMethodDecl *method_decl =
1088 dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl());
1089 if (method_decl && method_decl->isInstance()) {
1090 // Catch a format attribute mistakenly referring to the object argument.
1091 if (format_idx == 0)
1092 return;
1093 --format_idx;
1094 if(firstDataArg != 0)
1095 --firstDataArg;
1096 }
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001097 }
1098
Ted Kremenek826a3452010-07-16 02:11:22 +00001099 // CHECK: printf/scanf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +00001100 if (format_idx >= TheCall->getNumArgs()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001101 Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001102 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001103 return;
1104 }
Mike Stump1eb44332009-09-09 15:08:12 +00001105
Ted Kremenek082d9362009-03-20 21:35:28 +00001106 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001107
Chris Lattner59907c42007-08-10 20:18:51 +00001108 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001109 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001110 // Dynamically generated format strings are difficult to
1111 // automatically vet at compile time. Requiring that format strings
1112 // are string literals: (1) permits the checking of format strings by
1113 // the compiler and thereby (2) can practically remove the source of
1114 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001115
Mike Stump1eb44332009-09-09 15:08:12 +00001116 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001117 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001118 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001119 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001120 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
Ted Kremenek826a3452010-07-16 02:11:22 +00001121 firstDataArg, isPrintf))
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001122 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001123
Chris Lattner655f1412009-04-29 04:59:47 +00001124 // If there are no arguments specified, warn with -Wformat-security, otherwise
1125 // warn only with -Wformat-nonliteral.
1126 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump1eb44332009-09-09 15:08:12 +00001127 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001128 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001129 << OrigFormatExpr->getSourceRange();
1130 else
Mike Stump1eb44332009-09-09 15:08:12 +00001131 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001132 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001133 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001134}
Ted Kremenek71895b92007-08-14 17:39:48 +00001135
Ted Kremeneke0e53132010-01-28 23:39:18 +00001136namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001137class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1138protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001139 Sema &S;
1140 const StringLiteral *FExpr;
1141 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001142 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001143 const unsigned NumDataArgs;
1144 const bool IsObjCLiteral;
1145 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001146 const bool HasVAListArg;
1147 const CallExpr *TheCall;
1148 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001149 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001150 bool usesPositionalArgs;
1151 bool atFirstArg;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001152public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001153 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001154 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001155 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001156 const char *beg, bool hasVAListArg,
1157 const CallExpr *theCall, unsigned formatIdx)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001158 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek6ee76532010-03-25 03:59:12 +00001159 FirstDataArg(firstDataArg),
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001160 NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001161 IsObjCLiteral(isObjCLiteral), Beg(beg),
1162 HasVAListArg(hasVAListArg),
Ted Kremenekefaff192010-02-27 01:41:03 +00001163 TheCall(theCall), FormatIdx(formatIdx),
1164 usesPositionalArgs(false), atFirstArg(true) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001165 CoveredArgs.resize(numDataArgs);
1166 CoveredArgs.reset();
1167 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001168
Ted Kremenek07d161f2010-01-29 01:50:07 +00001169 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001170
Ted Kremenek826a3452010-07-16 02:11:22 +00001171 void HandleIncompleteSpecifier(const char *startSpecifier,
1172 unsigned specifierLen);
1173
Ted Kremenekefaff192010-02-27 01:41:03 +00001174 virtual void HandleInvalidPosition(const char *startSpecifier,
1175 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001176 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001177
1178 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1179
Ted Kremeneke0e53132010-01-28 23:39:18 +00001180 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001181
Ted Kremenek826a3452010-07-16 02:11:22 +00001182protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001183 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1184 const char *startSpec,
1185 unsigned specifierLen,
1186 const char *csStart, unsigned csLen);
1187
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001188 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00001189 CharSourceRange getSpecifierRange(const char *startSpecifier,
1190 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001191 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001192
Ted Kremenek0d277352010-01-29 01:06:55 +00001193 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00001194
1195 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1196 const analyze_format_string::ConversionSpecifier &CS,
1197 const char *startSpecifier, unsigned specifierLen,
1198 unsigned argIndex);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001199};
1200}
1201
Ted Kremenek826a3452010-07-16 02:11:22 +00001202SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001203 return OrigFormatExpr->getSourceRange();
1204}
1205
Ted Kremenek826a3452010-07-16 02:11:22 +00001206CharSourceRange CheckFormatHandler::
1207getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001208 SourceLocation Start = getLocationOfByte(startSpecifier);
1209 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1210
1211 // Advance the end SourceLocation by one due to half-open ranges.
1212 End = End.getFileLocWithOffset(1);
1213
1214 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001215}
1216
Ted Kremenek826a3452010-07-16 02:11:22 +00001217SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001218 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001219}
1220
Ted Kremenek826a3452010-07-16 02:11:22 +00001221void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1222 unsigned specifierLen){
Ted Kremenek808015a2010-01-29 03:16:21 +00001223 SourceLocation Loc = getLocationOfByte(startSpecifier);
1224 S.Diag(Loc, diag::warn_printf_incomplete_specifier)
Ted Kremenek826a3452010-07-16 02:11:22 +00001225 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek808015a2010-01-29 03:16:21 +00001226}
1227
Ted Kremenekefaff192010-02-27 01:41:03 +00001228void
Ted Kremenek826a3452010-07-16 02:11:22 +00001229CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1230 analyze_format_string::PositionContext p) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001231 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek826a3452010-07-16 02:11:22 +00001232 S.Diag(Loc, diag::warn_format_invalid_positional_specifier)
1233 << (unsigned) p << getSpecifierRange(startPos, posLen);
Ted Kremenekefaff192010-02-27 01:41:03 +00001234}
1235
Ted Kremenek826a3452010-07-16 02:11:22 +00001236void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00001237 unsigned posLen) {
1238 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek826a3452010-07-16 02:11:22 +00001239 S.Diag(Loc, diag::warn_format_zero_positional_specifier)
1240 << getSpecifierRange(startPos, posLen);
Ted Kremenekefaff192010-02-27 01:41:03 +00001241}
1242
Ted Kremenek826a3452010-07-16 02:11:22 +00001243void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Ted Kremenek0c069442011-03-15 21:18:48 +00001244 if (!IsObjCLiteral) {
1245 // The presence of a null character is likely an error.
1246 S.Diag(getLocationOfByte(nullCharacter),
1247 diag::warn_printf_format_string_contains_null_char)
1248 << getFormatStringRange();
1249 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001250}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001251
Ted Kremenek826a3452010-07-16 02:11:22 +00001252const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
1253 return TheCall->getArg(FirstDataArg + i);
1254}
1255
1256void CheckFormatHandler::DoneProcessing() {
1257 // Does the number of data arguments exceed the number of
1258 // format conversions in the format string?
1259 if (!HasVAListArg) {
1260 // Find any arguments that weren't covered.
1261 CoveredArgs.flip();
1262 signed notCoveredArg = CoveredArgs.find_first();
1263 if (notCoveredArg >= 0) {
1264 assert((unsigned)notCoveredArg < NumDataArgs);
1265 S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(),
1266 diag::warn_printf_data_arg_not_used)
1267 << getFormatStringRange();
1268 }
1269 }
1270}
1271
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001272bool
1273CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1274 SourceLocation Loc,
1275 const char *startSpec,
1276 unsigned specifierLen,
1277 const char *csStart,
1278 unsigned csLen) {
1279
1280 bool keepGoing = true;
1281 if (argIndex < NumDataArgs) {
1282 // Consider the argument coverered, even though the specifier doesn't
1283 // make sense.
1284 CoveredArgs.set(argIndex);
1285 }
1286 else {
1287 // If argIndex exceeds the number of data arguments we
1288 // don't issue a warning because that is just a cascade of warnings (and
1289 // they may have intended '%%' anyway). We don't want to continue processing
1290 // the format string after this point, however, as we will like just get
1291 // gibberish when trying to match arguments.
1292 keepGoing = false;
1293 }
1294
1295 S.Diag(Loc, diag::warn_format_invalid_conversion)
1296 << llvm::StringRef(csStart, csLen)
1297 << getSpecifierRange(startSpec, specifierLen);
1298
1299 return keepGoing;
1300}
1301
Ted Kremenek666a1972010-07-26 19:45:42 +00001302bool
1303CheckFormatHandler::CheckNumArgs(
1304 const analyze_format_string::FormatSpecifier &FS,
1305 const analyze_format_string::ConversionSpecifier &CS,
1306 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1307
1308 if (argIndex >= NumDataArgs) {
1309 if (FS.usesPositionalArg()) {
1310 S.Diag(getLocationOfByte(CS.getStart()),
1311 diag::warn_printf_positional_arg_exceeds_data_args)
1312 << (argIndex+1) << NumDataArgs
1313 << getSpecifierRange(startSpecifier, specifierLen);
1314 }
1315 else {
1316 S.Diag(getLocationOfByte(CS.getStart()),
1317 diag::warn_printf_insufficient_data_args)
1318 << getSpecifierRange(startSpecifier, specifierLen);
1319 }
1320
1321 return false;
1322 }
1323 return true;
1324}
1325
Ted Kremenek826a3452010-07-16 02:11:22 +00001326//===--- CHECK: Printf format string checking ------------------------------===//
1327
1328namespace {
1329class CheckPrintfHandler : public CheckFormatHandler {
1330public:
1331 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1332 const Expr *origFormatExpr, unsigned firstDataArg,
1333 unsigned numDataArgs, bool isObjCLiteral,
1334 const char *beg, bool hasVAListArg,
1335 const CallExpr *theCall, unsigned formatIdx)
1336 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1337 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1338 theCall, formatIdx) {}
1339
1340
1341 bool HandleInvalidPrintfConversionSpecifier(
1342 const analyze_printf::PrintfSpecifier &FS,
1343 const char *startSpecifier,
1344 unsigned specifierLen);
1345
1346 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1347 const char *startSpecifier,
1348 unsigned specifierLen);
1349
1350 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1351 const char *startSpecifier, unsigned specifierLen);
1352 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1353 const analyze_printf::OptionalAmount &Amt,
1354 unsigned type,
1355 const char *startSpecifier, unsigned specifierLen);
1356 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1357 const analyze_printf::OptionalFlag &flag,
1358 const char *startSpecifier, unsigned specifierLen);
1359 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1360 const analyze_printf::OptionalFlag &ignoredFlag,
1361 const analyze_printf::OptionalFlag &flag,
1362 const char *startSpecifier, unsigned specifierLen);
1363};
1364}
1365
1366bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1367 const analyze_printf::PrintfSpecifier &FS,
1368 const char *startSpecifier,
1369 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001370 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001371 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001372
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001373 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1374 getLocationOfByte(CS.getStart()),
1375 startSpecifier, specifierLen,
1376 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001377}
1378
Ted Kremenek826a3452010-07-16 02:11:22 +00001379bool CheckPrintfHandler::HandleAmount(
1380 const analyze_format_string::OptionalAmount &Amt,
1381 unsigned k, const char *startSpecifier,
1382 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001383
1384 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001385 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001386 unsigned argIndex = Amt.getArgIndex();
1387 if (argIndex >= NumDataArgs) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001388 S.Diag(getLocationOfByte(Amt.getStart()),
1389 diag::warn_printf_asterisk_missing_arg)
Ted Kremenek826a3452010-07-16 02:11:22 +00001390 << k << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek0d277352010-01-29 01:06:55 +00001391 // Don't do any more checking. We will just emit
1392 // spurious errors.
1393 return false;
1394 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001395
Ted Kremenek0d277352010-01-29 01:06:55 +00001396 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00001397 // Although not in conformance with C99, we also allow the argument to be
1398 // an 'unsigned int' as that is a reasonably safe case. GCC also
1399 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001400 CoveredArgs.set(argIndex);
1401 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00001402 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001403
1404 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1405 assert(ATR.isValid());
1406
1407 if (!ATR.matchesType(S.Context, T)) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001408 S.Diag(getLocationOfByte(Amt.getStart()),
1409 diag::warn_printf_asterisk_wrong_type)
1410 << k
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001411 << ATR.getRepresentativeType(S.Context) << T
Ted Kremenek826a3452010-07-16 02:11:22 +00001412 << getSpecifierRange(startSpecifier, specifierLen)
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001413 << Arg->getSourceRange();
Ted Kremenek0d277352010-01-29 01:06:55 +00001414 // Don't do any more checking. We will just emit
1415 // spurious errors.
1416 return false;
1417 }
1418 }
1419 }
1420 return true;
1421}
Ted Kremenek0d277352010-01-29 01:06:55 +00001422
Tom Caree4ee9662010-06-17 19:00:27 +00001423void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00001424 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001425 const analyze_printf::OptionalAmount &Amt,
1426 unsigned type,
1427 const char *startSpecifier,
1428 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001429 const analyze_printf::PrintfConversionSpecifier &CS =
1430 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001431 switch (Amt.getHowSpecified()) {
1432 case analyze_printf::OptionalAmount::Constant:
1433 S.Diag(getLocationOfByte(Amt.getStart()),
1434 diag::warn_printf_nonsensical_optional_amount)
1435 << type
1436 << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001437 << getSpecifierRange(startSpecifier, specifierLen)
1438 << FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
Tom Caree4ee9662010-06-17 19:00:27 +00001439 Amt.getConstantLength()));
1440 break;
1441
1442 default:
1443 S.Diag(getLocationOfByte(Amt.getStart()),
1444 diag::warn_printf_nonsensical_optional_amount)
1445 << type
1446 << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001447 << getSpecifierRange(startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001448 break;
1449 }
1450}
1451
Ted Kremenek826a3452010-07-16 02:11:22 +00001452void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001453 const analyze_printf::OptionalFlag &flag,
1454 const char *startSpecifier,
1455 unsigned specifierLen) {
1456 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001457 const analyze_printf::PrintfConversionSpecifier &CS =
1458 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001459 S.Diag(getLocationOfByte(flag.getPosition()),
1460 diag::warn_printf_nonsensical_flag)
1461 << flag.toString() << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001462 << getSpecifierRange(startSpecifier, specifierLen)
1463 << FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1));
Tom Caree4ee9662010-06-17 19:00:27 +00001464}
1465
1466void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00001467 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001468 const analyze_printf::OptionalFlag &ignoredFlag,
1469 const analyze_printf::OptionalFlag &flag,
1470 const char *startSpecifier,
1471 unsigned specifierLen) {
1472 // Warn about ignored flag with a fixit removal.
1473 S.Diag(getLocationOfByte(ignoredFlag.getPosition()),
1474 diag::warn_printf_ignored_flag)
1475 << ignoredFlag.toString() << flag.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001476 << getSpecifierRange(startSpecifier, specifierLen)
1477 << FixItHint::CreateRemoval(getSpecifierRange(
Tom Caree4ee9662010-06-17 19:00:27 +00001478 ignoredFlag.getPosition(), 1));
1479}
1480
Ted Kremeneke0e53132010-01-28 23:39:18 +00001481bool
Ted Kremenek826a3452010-07-16 02:11:22 +00001482CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001483 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001484 const char *startSpecifier,
1485 unsigned specifierLen) {
1486
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001487 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00001488 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001489 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00001490
Ted Kremenekbaa40062010-07-19 22:01:06 +00001491 if (FS.consumesDataArgument()) {
1492 if (atFirstArg) {
1493 atFirstArg = false;
1494 usesPositionalArgs = FS.usesPositionalArg();
1495 }
1496 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1497 // Cannot mix-and-match positional and non-positional arguments.
1498 S.Diag(getLocationOfByte(CS.getStart()),
1499 diag::warn_format_mix_positional_nonpositional_args)
1500 << getSpecifierRange(startSpecifier, specifierLen);
1501 return false;
1502 }
Ted Kremenek0d277352010-01-29 01:06:55 +00001503 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001504
Ted Kremenekefaff192010-02-27 01:41:03 +00001505 // First check if the field width, precision, and conversion specifier
1506 // have matching data arguments.
1507 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1508 startSpecifier, specifierLen)) {
1509 return false;
1510 }
1511
1512 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1513 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001514 return false;
1515 }
1516
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001517 if (!CS.consumesDataArgument()) {
1518 // FIXME: Technically specifying a precision or field width here
1519 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001520 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001521 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001522
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001523 // Consume the argument.
1524 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00001525 if (argIndex < NumDataArgs) {
1526 // The check to see if the argIndex is valid will come later.
1527 // We set the bit here because we may exit early from this
1528 // function if we encounter some other error.
1529 CoveredArgs.set(argIndex);
1530 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001531
1532 // Check for using an Objective-C specific conversion specifier
1533 // in a non-ObjC literal.
1534 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001535 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
1536 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001537 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001538
Tom Caree4ee9662010-06-17 19:00:27 +00001539 // Check for invalid use of field width
1540 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001541 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00001542 startSpecifier, specifierLen);
1543 }
1544
1545 // Check for invalid use of precision
1546 if (!FS.hasValidPrecision()) {
1547 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
1548 startSpecifier, specifierLen);
1549 }
1550
1551 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00001552 if (!FS.hasValidThousandsGroupingPrefix())
1553 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001554 if (!FS.hasValidLeadingZeros())
1555 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
1556 if (!FS.hasValidPlusPrefix())
1557 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00001558 if (!FS.hasValidSpacePrefix())
1559 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001560 if (!FS.hasValidAlternativeForm())
1561 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
1562 if (!FS.hasValidLeftJustified())
1563 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
1564
1565 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00001566 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
1567 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
1568 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001569 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
1570 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
1571 startSpecifier, specifierLen);
1572
1573 // Check the length modifier is valid with the given conversion specifier.
1574 const LengthModifier &LM = FS.getLengthModifier();
1575 if (!FS.hasValidLengthModifier())
1576 S.Diag(getLocationOfByte(LM.getStart()),
Ted Kremenek649aecf2010-07-20 20:03:43 +00001577 diag::warn_format_nonsensical_length)
Tom Caree4ee9662010-06-17 19:00:27 +00001578 << LM.toString() << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001579 << getSpecifierRange(startSpecifier, specifierLen)
1580 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
Tom Caree4ee9662010-06-17 19:00:27 +00001581 LM.getLength()));
1582
1583 // Are we using '%n'?
Ted Kremenek35d353b2010-07-20 20:04:10 +00001584 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Caree4ee9662010-06-17 19:00:27 +00001585 // Issue a warning about this being a possible security issue.
Ted Kremeneke82d8042010-01-29 01:35:25 +00001586 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
Ted Kremenek826a3452010-07-16 02:11:22 +00001587 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremeneke82d8042010-01-29 01:35:25 +00001588 // Continue checking the other format specifiers.
1589 return true;
1590 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001591
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001592 // The remaining checks depend on the data arguments.
1593 if (HasVAListArg)
1594 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001595
Ted Kremenek666a1972010-07-26 19:45:42 +00001596 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001597 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001598
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001599 // Now type check the data expression that matches the
1600 // format specifier.
1601 const Expr *Ex = getDataArg(argIndex);
1602 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
1603 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
1604 // Check if we didn't match because of an implicit cast from a 'char'
1605 // or 'short' to an 'int'. This is done because printf is a varargs
1606 // function.
1607 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00001608 if (ICE->getType() == S.Context.IntTy) {
1609 // All further checking is done on the subexpression.
1610 Ex = ICE->getSubExpr();
1611 if (ATR.matchesType(S.Context, Ex->getType()))
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001612 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00001613 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001614
1615 // We may be able to offer a FixItHint if it is a supported type.
1616 PrintfSpecifier fixedFS = FS;
1617 bool success = fixedFS.fixType(Ex->getType());
1618
1619 if (success) {
1620 // Get the fix string from the fixed format specifier
1621 llvm::SmallString<128> buf;
1622 llvm::raw_svector_ostream os(buf);
1623 fixedFS.toString(os);
1624
Ted Kremenek9325eaf2010-08-24 22:24:51 +00001625 // FIXME: getRepresentativeType() perhaps should return a string
1626 // instead of a QualType to better handle when the representative
1627 // type is 'wint_t' (which is defined in the system headers).
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001628 S.Diag(getLocationOfByte(CS.getStart()),
1629 diag::warn_printf_conversion_argument_type_mismatch)
1630 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1631 << getSpecifierRange(startSpecifier, specifierLen)
1632 << Ex->getSourceRange()
1633 << FixItHint::CreateReplacement(
1634 getSpecifierRange(startSpecifier, specifierLen),
1635 os.str());
1636 }
1637 else {
1638 S.Diag(getLocationOfByte(CS.getStart()),
1639 diag::warn_printf_conversion_argument_type_mismatch)
1640 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1641 << getSpecifierRange(startSpecifier, specifierLen)
1642 << Ex->getSourceRange();
1643 }
1644 }
1645
Ted Kremeneke0e53132010-01-28 23:39:18 +00001646 return true;
1647}
1648
Ted Kremenek826a3452010-07-16 02:11:22 +00001649//===--- CHECK: Scanf format string checking ------------------------------===//
1650
1651namespace {
1652class CheckScanfHandler : public CheckFormatHandler {
1653public:
1654 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
1655 const Expr *origFormatExpr, unsigned firstDataArg,
1656 unsigned numDataArgs, bool isObjCLiteral,
1657 const char *beg, bool hasVAListArg,
1658 const CallExpr *theCall, unsigned formatIdx)
1659 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1660 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1661 theCall, formatIdx) {}
1662
1663 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
1664 const char *startSpecifier,
1665 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001666
1667 bool HandleInvalidScanfConversionSpecifier(
1668 const analyze_scanf::ScanfSpecifier &FS,
1669 const char *startSpecifier,
1670 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00001671
1672 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00001673};
Ted Kremenek07d161f2010-01-29 01:50:07 +00001674}
Ted Kremeneke0e53132010-01-28 23:39:18 +00001675
Ted Kremenekb7c21012010-07-16 18:28:03 +00001676void CheckScanfHandler::HandleIncompleteScanList(const char *start,
1677 const char *end) {
1678 S.Diag(getLocationOfByte(end), diag::warn_scanf_scanlist_incomplete)
1679 << getSpecifierRange(start, end - start);
1680}
1681
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001682bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
1683 const analyze_scanf::ScanfSpecifier &FS,
1684 const char *startSpecifier,
1685 unsigned specifierLen) {
1686
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001687 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001688 FS.getConversionSpecifier();
1689
1690 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1691 getLocationOfByte(CS.getStart()),
1692 startSpecifier, specifierLen,
1693 CS.getStart(), CS.getLength());
1694}
1695
Ted Kremenek826a3452010-07-16 02:11:22 +00001696bool CheckScanfHandler::HandleScanfSpecifier(
1697 const analyze_scanf::ScanfSpecifier &FS,
1698 const char *startSpecifier,
1699 unsigned specifierLen) {
1700
1701 using namespace analyze_scanf;
1702 using namespace analyze_format_string;
1703
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001704 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001705
Ted Kremenekbaa40062010-07-19 22:01:06 +00001706 // Handle case where '%' and '*' don't consume an argument. These shouldn't
1707 // be used to decide if we are using positional arguments consistently.
1708 if (FS.consumesDataArgument()) {
1709 if (atFirstArg) {
1710 atFirstArg = false;
1711 usesPositionalArgs = FS.usesPositionalArg();
1712 }
1713 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1714 // Cannot mix-and-match positional and non-positional arguments.
1715 S.Diag(getLocationOfByte(CS.getStart()),
1716 diag::warn_format_mix_positional_nonpositional_args)
1717 << getSpecifierRange(startSpecifier, specifierLen);
1718 return false;
1719 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001720 }
1721
1722 // Check if the field with is non-zero.
1723 const OptionalAmount &Amt = FS.getFieldWidth();
1724 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
1725 if (Amt.getConstantAmount() == 0) {
1726 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
1727 Amt.getConstantLength());
1728 S.Diag(getLocationOfByte(Amt.getStart()),
1729 diag::warn_scanf_nonzero_width)
1730 << R << FixItHint::CreateRemoval(R);
1731 }
1732 }
1733
1734 if (!FS.consumesDataArgument()) {
1735 // FIXME: Technically specifying a precision or field width here
1736 // makes no sense. Worth issuing a warning at some point.
1737 return true;
1738 }
1739
1740 // Consume the argument.
1741 unsigned argIndex = FS.getArgIndex();
1742 if (argIndex < NumDataArgs) {
1743 // The check to see if the argIndex is valid will come later.
1744 // We set the bit here because we may exit early from this
1745 // function if we encounter some other error.
1746 CoveredArgs.set(argIndex);
1747 }
1748
Ted Kremenek1e51c202010-07-20 20:04:47 +00001749 // Check the length modifier is valid with the given conversion specifier.
1750 const LengthModifier &LM = FS.getLengthModifier();
1751 if (!FS.hasValidLengthModifier()) {
1752 S.Diag(getLocationOfByte(LM.getStart()),
1753 diag::warn_format_nonsensical_length)
1754 << LM.toString() << CS.toString()
1755 << getSpecifierRange(startSpecifier, specifierLen)
1756 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
1757 LM.getLength()));
1758 }
1759
Ted Kremenek826a3452010-07-16 02:11:22 +00001760 // The remaining checks depend on the data arguments.
1761 if (HasVAListArg)
1762 return true;
1763
Ted Kremenek666a1972010-07-26 19:45:42 +00001764 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00001765 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00001766
1767 // FIXME: Check that the argument type matches the format specifier.
1768
1769 return true;
1770}
1771
1772void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001773 const Expr *OrigFormatExpr,
1774 const CallExpr *TheCall, bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001775 unsigned format_idx, unsigned firstDataArg,
1776 bool isPrintf) {
1777
Ted Kremeneke0e53132010-01-28 23:39:18 +00001778 // CHECK: is the format string a wide literal?
1779 if (FExpr->isWide()) {
1780 Diag(FExpr->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001781 diag::warn_format_string_is_wide_literal)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001782 << OrigFormatExpr->getSourceRange();
1783 return;
1784 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001785
Ted Kremeneke0e53132010-01-28 23:39:18 +00001786 // Str - The format string. NOTE: this is NOT null-terminated!
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001787 llvm::StringRef StrRef = FExpr->getString();
1788 const char *Str = StrRef.data();
1789 unsigned StrLen = StrRef.size();
Ted Kremenek826a3452010-07-16 02:11:22 +00001790
Ted Kremeneke0e53132010-01-28 23:39:18 +00001791 // CHECK: empty format string?
Ted Kremeneke0e53132010-01-28 23:39:18 +00001792 if (StrLen == 0) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001793 Diag(FExpr->getLocStart(), diag::warn_empty_format_string)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001794 << OrigFormatExpr->getSourceRange();
1795 return;
1796 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001797
1798 if (isPrintf) {
1799 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1800 TheCall->getNumArgs() - firstDataArg,
1801 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1802 HasVAListArg, TheCall, format_idx);
1803
1804 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen))
1805 H.DoneProcessing();
1806 }
1807 else {
1808 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1809 TheCall->getNumArgs() - firstDataArg,
1810 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1811 HasVAListArg, TheCall, format_idx);
1812
1813 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen))
1814 H.DoneProcessing();
1815 }
Ted Kremenekce7024e2010-01-28 01:18:22 +00001816}
1817
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001818//===--- CHECK: Standard memory functions ---------------------------------===//
1819
Douglas Gregor2a053a32011-05-03 20:05:22 +00001820/// \brief Determine whether the given type is a dynamic class type (e.g.,
1821/// whether it has a vtable).
1822static bool isDynamicClassType(QualType T) {
1823 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
1824 if (CXXRecordDecl *Definition = Record->getDefinition())
1825 if (Definition->isDynamicClass())
1826 return true;
1827
1828 return false;
1829}
1830
Chandler Carruth000d4282011-06-16 09:09:40 +00001831/// \brief If E is a sizeof expression returns the argument expression,
1832/// otherwise returns NULL.
1833static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00001834 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00001835 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
1836 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
1837 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00001838
Chandler Carruth000d4282011-06-16 09:09:40 +00001839 return 0;
1840}
1841
1842/// \brief If E is a sizeof expression returns the argument type.
1843static QualType getSizeOfArgType(const Expr* E) {
1844 if (const UnaryExprOrTypeTraitExpr *SizeOf =
1845 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
1846 if (SizeOf->getKind() == clang::UETT_SizeOf)
1847 return SizeOf->getTypeOfArgument();
1848
1849 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00001850}
1851
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001852/// \brief Check for dangerous or invalid arguments to memset().
1853///
Chandler Carruth929f0132011-06-03 06:23:57 +00001854/// This issues warnings on known problematic, dangerous or unspecified
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00001855/// arguments to the standard 'memset', 'memcpy', and 'memmove' function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001856///
1857/// \param Call The call expression to diagnose.
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00001858void Sema::CheckMemsetcpymoveArguments(const CallExpr *Call,
1859 const IdentifierInfo *FnName) {
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00001860 // It is possible to have a non-standard definition of memset. Validate
1861 // we have the proper number of arguments, and if not, abort further
1862 // checking.
1863 if (Call->getNumArgs() != 3)
1864 return;
1865
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00001866 unsigned LastArg = FnName->isStr("memset")? 1 : 2;
Nico Webere4a1c642011-06-14 16:14:58 +00001867 const Expr *LenExpr = Call->getArg(2)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00001868
1869 // We have special checking when the length is a sizeof expression.
1870 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
1871 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
1872 llvm::FoldingSetNodeID SizeOfArgID;
1873
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00001874 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
1875 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00001876 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001877
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00001878 QualType DestTy = Dest->getType();
1879 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
1880 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00001881
Chandler Carruth000d4282011-06-16 09:09:40 +00001882 // Never warn about void type pointers. This can be used to suppress
1883 // false positives.
1884 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00001885 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001886
Chandler Carruth000d4282011-06-16 09:09:40 +00001887 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
1888 // actually comparing the expressions for equality. Because computing the
1889 // expression IDs can be expensive, we only do this if the diagnostic is
1890 // enabled.
1891 if (SizeOfArg &&
1892 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
1893 SizeOfArg->getExprLoc())) {
1894 // We only compute IDs for expressions if the warning is enabled, and
1895 // cache the sizeof arg's ID.
1896 if (SizeOfArgID == llvm::FoldingSetNodeID())
1897 SizeOfArg->Profile(SizeOfArgID, Context, true);
1898 llvm::FoldingSetNodeID DestID;
1899 Dest->Profile(DestID, Context, true);
1900 if (DestID == SizeOfArgID) {
1901 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
1902 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
1903 if (UnaryOp->getOpcode() == UO_AddrOf)
1904 ActionIdx = 1; // If its an address-of operator, just remove it.
1905 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
1906 ActionIdx = 2; // If the pointee's size is sizeof(char),
1907 // suggest an explicit length.
1908 DiagRuntimeBehavior(SizeOfArg->getExprLoc(), Dest,
1909 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
1910 << FnName << ArgIdx << ActionIdx
1911 << Dest->getSourceRange()
1912 << SizeOfArg->getSourceRange());
1913 break;
1914 }
1915 }
1916
1917 // Also check for cases where the sizeof argument is the exact same
1918 // type as the memory argument, and where it points to a user-defined
1919 // record type.
1920 if (SizeOfArgTy != QualType()) {
1921 if (PointeeTy->isRecordType() &&
1922 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
1923 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
1924 PDiag(diag::warn_sizeof_pointer_type_memaccess)
1925 << FnName << SizeOfArgTy << ArgIdx
1926 << PointeeTy << Dest->getSourceRange()
1927 << LenExpr->getSourceRange());
1928 break;
1929 }
Nico Webere4a1c642011-06-14 16:14:58 +00001930 }
1931
John McCallf85e1932011-06-15 23:02:42 +00001932 unsigned DiagID;
1933
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00001934 // Always complain about dynamic classes.
John McCallf85e1932011-06-15 23:02:42 +00001935 if (isDynamicClassType(PointeeTy))
1936 DiagID = diag::warn_dyn_class_memaccess;
1937 else if (PointeeTy.hasNonTrivialObjCLifetime() &&
1938 !FnName->isStr("memset"))
1939 DiagID = diag::warn_arc_object_memaccess;
1940 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00001941 continue;
John McCallf85e1932011-06-15 23:02:42 +00001942
1943 DiagRuntimeBehavior(
1944 Dest->getExprLoc(), Dest,
1945 PDiag(DiagID)
1946 << ArgIdx << FnName << PointeeTy
1947 << Call->getCallee()->getSourceRange());
Chandler Carruth43fa33b2011-04-29 09:46:08 +00001948
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00001949 DiagRuntimeBehavior(
1950 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00001951 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00001952 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
1953 break;
1954 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001955 }
1956}
1957
Ted Kremenek06de2762007-08-17 16:46:58 +00001958//===--- CHECK: Return Address of Stack Variable --------------------------===//
1959
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001960static Expr *EvalVal(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars);
1961static Expr *EvalAddr(Expr* E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00001962
1963/// CheckReturnStackAddr - Check if a return statement returns the address
1964/// of a stack variable.
1965void
1966Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1967 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00001968
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001969 Expr *stackE = 0;
1970 llvm::SmallVector<DeclRefExpr *, 8> refVars;
1971
1972 // Perform checking for returned stack addresses, local blocks,
1973 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00001974 if (lhsType->isPointerType() ||
1975 (!getLangOptions().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001976 stackE = EvalAddr(RetValExp, refVars);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001977 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001978 stackE = EvalVal(RetValExp, refVars);
1979 }
1980
1981 if (stackE == 0)
1982 return; // Nothing suspicious was found.
1983
1984 SourceLocation diagLoc;
1985 SourceRange diagRange;
1986 if (refVars.empty()) {
1987 diagLoc = stackE->getLocStart();
1988 diagRange = stackE->getSourceRange();
1989 } else {
1990 // We followed through a reference variable. 'stackE' contains the
1991 // problematic expression but we will warn at the return statement pointing
1992 // at the reference variable. We will later display the "trail" of
1993 // reference variables using notes.
1994 diagLoc = refVars[0]->getLocStart();
1995 diagRange = refVars[0]->getSourceRange();
1996 }
1997
1998 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
1999 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
2000 : diag::warn_ret_stack_addr)
2001 << DR->getDecl()->getDeclName() << diagRange;
2002 } else if (isa<BlockExpr>(stackE)) { // local block.
2003 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
2004 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
2005 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
2006 } else { // local temporary.
2007 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
2008 : diag::warn_ret_local_temp_addr)
2009 << diagRange;
2010 }
2011
2012 // Display the "trail" of reference variables that we followed until we
2013 // found the problematic expression using notes.
2014 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
2015 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
2016 // If this var binds to another reference var, show the range of the next
2017 // var, otherwise the var binds to the problematic expression, in which case
2018 // show the range of the expression.
2019 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
2020 : stackE->getSourceRange();
2021 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
2022 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00002023 }
2024}
2025
2026/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
2027/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002028/// to a location on the stack, a local block, an address of a label, or a
2029/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00002030/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002031/// encounter a subexpression that (1) clearly does not lead to one of the
2032/// above problematic expressions (2) is something we cannot determine leads to
2033/// a problematic expression based on such local checking.
2034///
2035/// Both EvalAddr and EvalVal follow through reference variables to evaluate
2036/// the expression that they point to. Such variables are added to the
2037/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00002038///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002039/// EvalAddr processes expressions that are pointers that are used as
2040/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002041/// At the base case of the recursion is a check for the above problematic
2042/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00002043///
2044/// This implementation handles:
2045///
2046/// * pointer-to-pointer casts
2047/// * implicit conversions from array references to pointers
2048/// * taking the address of fields
2049/// * arbitrary interplay between "&" and "*" operators
2050/// * pointer arithmetic from an address of a stack variable
2051/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002052static Expr *EvalAddr(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars) {
2053 if (E->isTypeDependent())
2054 return NULL;
2055
Ted Kremenek06de2762007-08-17 16:46:58 +00002056 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00002057 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00002058 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002059 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002060 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00002061
Peter Collingbournef111d932011-04-15 00:35:48 +00002062 E = E->IgnoreParens();
2063
Ted Kremenek06de2762007-08-17 16:46:58 +00002064 // Our "symbolic interpreter" is just a dispatch off the currently
2065 // viewed AST node. We then recursively traverse the AST by calling
2066 // EvalAddr and EvalVal appropriately.
2067 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002068 case Stmt::DeclRefExprClass: {
2069 DeclRefExpr *DR = cast<DeclRefExpr>(E);
2070
2071 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
2072 // If this is a reference variable, follow through to the expression that
2073 // it points to.
2074 if (V->hasLocalStorage() &&
2075 V->getType()->isReferenceType() && V->hasInit()) {
2076 // Add the reference variable to the "trail".
2077 refVars.push_back(DR);
2078 return EvalAddr(V->getInit(), refVars);
2079 }
2080
2081 return NULL;
2082 }
Ted Kremenek06de2762007-08-17 16:46:58 +00002083
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002084 case Stmt::UnaryOperatorClass: {
2085 // The only unary operator that make sense to handle here
2086 // is AddrOf. All others don't make sense as pointers.
2087 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002088
John McCall2de56d12010-08-25 11:45:40 +00002089 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002090 return EvalVal(U->getSubExpr(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002091 else
Ted Kremenek06de2762007-08-17 16:46:58 +00002092 return NULL;
2093 }
Mike Stump1eb44332009-09-09 15:08:12 +00002094
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002095 case Stmt::BinaryOperatorClass: {
2096 // Handle pointer arithmetic. All other binary operators are not valid
2097 // in this context.
2098 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00002099 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00002100
John McCall2de56d12010-08-25 11:45:40 +00002101 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002102 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00002103
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002104 Expr *Base = B->getLHS();
2105
2106 // Determine which argument is the real pointer base. It could be
2107 // the RHS argument instead of the LHS.
2108 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00002109
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002110 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002111 return EvalAddr(Base, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002112 }
Steve Naroff61f40a22008-09-10 19:17:48 +00002113
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002114 // For conditional operators we need to see if either the LHS or RHS are
2115 // valid DeclRefExpr*s. If one of them is valid, we return it.
2116 case Stmt::ConditionalOperatorClass: {
2117 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002118
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002119 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002120 if (Expr *lhsExpr = C->getLHS()) {
2121 // In C++, we can have a throw-expression, which has 'void' type.
2122 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002123 if (Expr* LHS = EvalAddr(lhsExpr, refVars))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002124 return LHS;
2125 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002126
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002127 // In C++, we can have a throw-expression, which has 'void' type.
2128 if (C->getRHS()->getType()->isVoidType())
2129 return NULL;
2130
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002131 return EvalAddr(C->getRHS(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002132 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002133
2134 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00002135 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002136 return E; // local block.
2137 return NULL;
2138
2139 case Stmt::AddrLabelExprClass:
2140 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00002141
Ted Kremenek54b52742008-08-07 00:49:01 +00002142 // For casts, we need to handle conversions from arrays to
2143 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00002144 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002145 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00002146 case Stmt::CXXFunctionalCastExprClass:
2147 case Stmt::ObjCBridgedCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002148 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00002149 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002150
Steve Naroffdd972f22008-09-05 22:11:13 +00002151 if (SubExpr->getType()->isPointerType() ||
2152 SubExpr->getType()->isBlockPointerType() ||
2153 SubExpr->getType()->isObjCQualifiedIdType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002154 return EvalAddr(SubExpr, refVars);
Ted Kremenek54b52742008-08-07 00:49:01 +00002155 else if (T->isArrayType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002156 return EvalVal(SubExpr, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002157 else
Ted Kremenek54b52742008-08-07 00:49:01 +00002158 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002159 }
Mike Stump1eb44332009-09-09 15:08:12 +00002160
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002161 // C++ casts. For dynamic casts, static casts, and const casts, we
2162 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00002163 // through the cast. In the case the dynamic cast doesn't fail (and
2164 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002165 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00002166 // FIXME: The comment about is wrong; we're not always converting
2167 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00002168 // handle references to objects.
2169 case Stmt::CXXStaticCastExprClass:
2170 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00002171 case Stmt::CXXConstCastExprClass:
2172 case Stmt::CXXReinterpretCastExprClass: {
2173 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00002174 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002175 return EvalAddr(S, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002176 else
2177 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002178 }
Mike Stump1eb44332009-09-09 15:08:12 +00002179
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002180 // Everything else: we simply don't reason about them.
2181 default:
2182 return NULL;
2183 }
Ted Kremenek06de2762007-08-17 16:46:58 +00002184}
Mike Stump1eb44332009-09-09 15:08:12 +00002185
Ted Kremenek06de2762007-08-17 16:46:58 +00002186
2187/// EvalVal - This function is complements EvalAddr in the mutual recursion.
2188/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002189static Expr *EvalVal(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002190do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002191 // We should only be called for evaluating non-pointer expressions, or
2192 // expressions with a pointer type that are not used as references but instead
2193 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00002194
Ted Kremenek06de2762007-08-17 16:46:58 +00002195 // Our "symbolic interpreter" is just a dispatch off the currently
2196 // viewed AST node. We then recursively traverse the AST by calling
2197 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00002198
2199 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00002200 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002201 case Stmt::ImplicitCastExprClass: {
2202 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00002203 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002204 E = IE->getSubExpr();
2205 continue;
2206 }
2207 return NULL;
2208 }
2209
Douglas Gregora2813ce2009-10-23 18:54:35 +00002210 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002211 // When we hit a DeclRefExpr we are looking at code that refers to a
2212 // variable's name. If it's not a reference variable we check if it has
2213 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00002214 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002215
Ted Kremenek06de2762007-08-17 16:46:58 +00002216 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002217 if (V->hasLocalStorage()) {
2218 if (!V->getType()->isReferenceType())
2219 return DR;
2220
2221 // Reference variable, follow through to the expression that
2222 // it points to.
2223 if (V->hasInit()) {
2224 // Add the reference variable to the "trail".
2225 refVars.push_back(DR);
2226 return EvalVal(V->getInit(), refVars);
2227 }
2228 }
Mike Stump1eb44332009-09-09 15:08:12 +00002229
Ted Kremenek06de2762007-08-17 16:46:58 +00002230 return NULL;
2231 }
Mike Stump1eb44332009-09-09 15:08:12 +00002232
Ted Kremenek06de2762007-08-17 16:46:58 +00002233 case Stmt::UnaryOperatorClass: {
2234 // The only unary operator that make sense to handle here
2235 // is Deref. All others don't resolve to a "name." This includes
2236 // handling all sorts of rvalues passed to a unary operator.
2237 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002238
John McCall2de56d12010-08-25 11:45:40 +00002239 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002240 return EvalAddr(U->getSubExpr(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002241
2242 return NULL;
2243 }
Mike Stump1eb44332009-09-09 15:08:12 +00002244
Ted Kremenek06de2762007-08-17 16:46:58 +00002245 case Stmt::ArraySubscriptExprClass: {
2246 // Array subscripts are potential references to data on the stack. We
2247 // retrieve the DeclRefExpr* for the array variable if it indeed
2248 // has local storage.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002249 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002250 }
Mike Stump1eb44332009-09-09 15:08:12 +00002251
Ted Kremenek06de2762007-08-17 16:46:58 +00002252 case Stmt::ConditionalOperatorClass: {
2253 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002254 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00002255 ConditionalOperator *C = cast<ConditionalOperator>(E);
2256
Anders Carlsson39073232007-11-30 19:04:31 +00002257 // Handle the GNU extension for missing LHS.
2258 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002259 if (Expr *LHS = EvalVal(lhsExpr, refVars))
Anders Carlsson39073232007-11-30 19:04:31 +00002260 return LHS;
2261
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002262 return EvalVal(C->getRHS(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002263 }
Mike Stump1eb44332009-09-09 15:08:12 +00002264
Ted Kremenek06de2762007-08-17 16:46:58 +00002265 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00002266 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00002267 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002268
Ted Kremenek06de2762007-08-17 16:46:58 +00002269 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00002270 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00002271 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00002272
2273 // Check whether the member type is itself a reference, in which case
2274 // we're not going to refer to the member, but to what the member refers to.
2275 if (M->getMemberDecl()->getType()->isReferenceType())
2276 return NULL;
2277
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002278 return EvalVal(M->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002279 }
Mike Stump1eb44332009-09-09 15:08:12 +00002280
Ted Kremenek06de2762007-08-17 16:46:58 +00002281 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002282 // Check that we don't return or take the address of a reference to a
2283 // temporary. This is only useful in C++.
2284 if (!E->isTypeDependent() && E->isRValue())
2285 return E;
2286
2287 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00002288 return NULL;
2289 }
Ted Kremenek68957a92010-08-04 20:01:07 +00002290} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00002291}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002292
2293//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
2294
2295/// Check for comparisons of floating point operands using != and ==.
2296/// Issue a warning if these are no self-comparisons, as they are not likely
2297/// to do what the programmer intended.
2298void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
2299 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002300
John McCallf6a16482010-12-04 03:47:34 +00002301 Expr* LeftExprSansParen = lex->IgnoreParenImpCasts();
2302 Expr* RightExprSansParen = rex->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002303
2304 // Special case: check for x == x (which is OK).
2305 // Do not emit warnings for such cases.
2306 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
2307 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
2308 if (DRL->getDecl() == DRR->getDecl())
2309 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002310
2311
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002312 // Special case: check for comparisons against literals that can be exactly
2313 // represented by APFloat. In such cases, do not emit a warning. This
2314 // is a heuristic: often comparison against such literals are used to
2315 // detect if a value in a variable has not changed. This clearly can
2316 // lead to false negatives.
2317 if (EmitWarning) {
2318 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
2319 if (FLL->isExact())
2320 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002321 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002322 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
2323 if (FLR->isExact())
2324 EmitWarning = false;
2325 }
2326 }
Mike Stump1eb44332009-09-09 15:08:12 +00002327
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002328 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002329 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002330 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002331 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002332 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002333
Sebastian Redl0eb23302009-01-19 00:08:26 +00002334 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002335 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002336 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002337 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002338
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002339 // Emit the diagnostic.
2340 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002341 Diag(loc, diag::warn_floatingpoint_eq)
2342 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002343}
John McCallba26e582010-01-04 23:21:16 +00002344
John McCallf2370c92010-01-06 05:24:50 +00002345//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
2346//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00002347
John McCallf2370c92010-01-06 05:24:50 +00002348namespace {
John McCallba26e582010-01-04 23:21:16 +00002349
John McCallf2370c92010-01-06 05:24:50 +00002350/// Structure recording the 'active' range of an integer-valued
2351/// expression.
2352struct IntRange {
2353 /// The number of bits active in the int.
2354 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00002355
John McCallf2370c92010-01-06 05:24:50 +00002356 /// True if the int is known not to have negative values.
2357 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00002358
John McCallf2370c92010-01-06 05:24:50 +00002359 IntRange(unsigned Width, bool NonNegative)
2360 : Width(Width), NonNegative(NonNegative)
2361 {}
John McCallba26e582010-01-04 23:21:16 +00002362
John McCall1844a6e2010-11-10 23:38:19 +00002363 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00002364 static IntRange forBoolType() {
2365 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00002366 }
2367
John McCall1844a6e2010-11-10 23:38:19 +00002368 /// Returns the range of an opaque value of the given integral type.
2369 static IntRange forValueOfType(ASTContext &C, QualType T) {
2370 return forValueOfCanonicalType(C,
2371 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00002372 }
2373
John McCall1844a6e2010-11-10 23:38:19 +00002374 /// Returns the range of an opaque value of a canonical integral type.
2375 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00002376 assert(T->isCanonicalUnqualified());
2377
2378 if (const VectorType *VT = dyn_cast<VectorType>(T))
2379 T = VT->getElementType().getTypePtr();
2380 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2381 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00002382
John McCall091f23f2010-11-09 22:22:12 +00002383 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00002384 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
2385 EnumDecl *Enum = ET->getDecl();
John McCall091f23f2010-11-09 22:22:12 +00002386 if (!Enum->isDefinition())
2387 return IntRange(C.getIntWidth(QualType(T, 0)), false);
2388
John McCall323ed742010-05-06 08:58:33 +00002389 unsigned NumPositive = Enum->getNumPositiveBits();
2390 unsigned NumNegative = Enum->getNumNegativeBits();
2391
2392 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
2393 }
John McCallf2370c92010-01-06 05:24:50 +00002394
2395 const BuiltinType *BT = cast<BuiltinType>(T);
2396 assert(BT->isInteger());
2397
2398 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2399 }
2400
John McCall1844a6e2010-11-10 23:38:19 +00002401 /// Returns the "target" range of a canonical integral type, i.e.
2402 /// the range of values expressible in the type.
2403 ///
2404 /// This matches forValueOfCanonicalType except that enums have the
2405 /// full range of their type, not the range of their enumerators.
2406 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
2407 assert(T->isCanonicalUnqualified());
2408
2409 if (const VectorType *VT = dyn_cast<VectorType>(T))
2410 T = VT->getElementType().getTypePtr();
2411 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2412 T = CT->getElementType().getTypePtr();
2413 if (const EnumType *ET = dyn_cast<EnumType>(T))
2414 T = ET->getDecl()->getIntegerType().getTypePtr();
2415
2416 const BuiltinType *BT = cast<BuiltinType>(T);
2417 assert(BT->isInteger());
2418
2419 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2420 }
2421
2422 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002423 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00002424 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00002425 L.NonNegative && R.NonNegative);
2426 }
2427
John McCall1844a6e2010-11-10 23:38:19 +00002428 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002429 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00002430 return IntRange(std::min(L.Width, R.Width),
2431 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00002432 }
2433};
2434
2435IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
2436 if (value.isSigned() && value.isNegative())
2437 return IntRange(value.getMinSignedBits(), false);
2438
2439 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002440 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00002441
2442 // isNonNegative() just checks the sign bit without considering
2443 // signedness.
2444 return IntRange(value.getActiveBits(), true);
2445}
2446
John McCall0acc3112010-01-06 22:57:21 +00002447IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCallf2370c92010-01-06 05:24:50 +00002448 unsigned MaxWidth) {
2449 if (result.isInt())
2450 return GetValueRange(C, result.getInt(), MaxWidth);
2451
2452 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00002453 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
2454 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
2455 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
2456 R = IntRange::join(R, El);
2457 }
John McCallf2370c92010-01-06 05:24:50 +00002458 return R;
2459 }
2460
2461 if (result.isComplexInt()) {
2462 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
2463 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
2464 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00002465 }
2466
2467 // This can happen with lossless casts to intptr_t of "based" lvalues.
2468 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00002469 // FIXME: The only reason we need to pass the type in here is to get
2470 // the sign right on this one case. It would be nice if APValue
2471 // preserved this.
John McCallf2370c92010-01-06 05:24:50 +00002472 assert(result.isLValue());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00002473 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00002474}
John McCallf2370c92010-01-06 05:24:50 +00002475
2476/// Pseudo-evaluate the given integer expression, estimating the
2477/// range of values it might take.
2478///
2479/// \param MaxWidth - the width to which the value will be truncated
2480IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
2481 E = E->IgnoreParens();
2482
2483 // Try a full evaluation first.
2484 Expr::EvalResult result;
2485 if (E->Evaluate(result, C))
John McCall0acc3112010-01-06 22:57:21 +00002486 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00002487
2488 // I think we only want to look through implicit casts here; if the
2489 // user has an explicit widening cast, we should treat the value as
2490 // being of the new, wider type.
2491 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00002492 if (CE->getCastKind() == CK_NoOp)
John McCallf2370c92010-01-06 05:24:50 +00002493 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
2494
John McCall1844a6e2010-11-10 23:38:19 +00002495 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00002496
John McCall2de56d12010-08-25 11:45:40 +00002497 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00002498
John McCallf2370c92010-01-06 05:24:50 +00002499 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00002500 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00002501 return OutputTypeRange;
2502
2503 IntRange SubRange
2504 = GetExprRange(C, CE->getSubExpr(),
2505 std::min(MaxWidth, OutputTypeRange.Width));
2506
2507 // Bail out if the subexpr's range is as wide as the cast type.
2508 if (SubRange.Width >= OutputTypeRange.Width)
2509 return OutputTypeRange;
2510
2511 // Otherwise, we take the smaller width, and we're non-negative if
2512 // either the output type or the subexpr is.
2513 return IntRange(SubRange.Width,
2514 SubRange.NonNegative || OutputTypeRange.NonNegative);
2515 }
2516
2517 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2518 // If we can fold the condition, just take that operand.
2519 bool CondResult;
2520 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
2521 return GetExprRange(C, CondResult ? CO->getTrueExpr()
2522 : CO->getFalseExpr(),
2523 MaxWidth);
2524
2525 // Otherwise, conservatively merge.
2526 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
2527 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
2528 return IntRange::join(L, R);
2529 }
2530
2531 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2532 switch (BO->getOpcode()) {
2533
2534 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00002535 case BO_LAnd:
2536 case BO_LOr:
2537 case BO_LT:
2538 case BO_GT:
2539 case BO_LE:
2540 case BO_GE:
2541 case BO_EQ:
2542 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00002543 return IntRange::forBoolType();
2544
John McCallc0cd21d2010-02-23 19:22:29 +00002545 // The type of these compound assignments is the type of the LHS,
2546 // so the RHS is not necessarily an integer.
John McCall2de56d12010-08-25 11:45:40 +00002547 case BO_MulAssign:
2548 case BO_DivAssign:
2549 case BO_RemAssign:
2550 case BO_AddAssign:
2551 case BO_SubAssign:
John McCall1844a6e2010-11-10 23:38:19 +00002552 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00002553
John McCallf2370c92010-01-06 05:24:50 +00002554 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00002555 case BO_PtrMemD:
2556 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00002557 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002558
John McCall60fad452010-01-06 22:07:33 +00002559 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00002560 case BO_And:
2561 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00002562 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
2563 GetExprRange(C, BO->getRHS(), MaxWidth));
2564
John McCallf2370c92010-01-06 05:24:50 +00002565 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00002566 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00002567 // ...except that we want to treat '1 << (blah)' as logically
2568 // positive. It's an important idiom.
2569 if (IntegerLiteral *I
2570 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
2571 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00002572 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00002573 return IntRange(R.Width, /*NonNegative*/ true);
2574 }
2575 }
2576 // fallthrough
2577
John McCall2de56d12010-08-25 11:45:40 +00002578 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00002579 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002580
John McCall60fad452010-01-06 22:07:33 +00002581 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00002582 case BO_Shr:
2583 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00002584 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2585
2586 // If the shift amount is a positive constant, drop the width by
2587 // that much.
2588 llvm::APSInt shift;
2589 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
2590 shift.isNonNegative()) {
2591 unsigned zext = shift.getZExtValue();
2592 if (zext >= L.Width)
2593 L.Width = (L.NonNegative ? 0 : 1);
2594 else
2595 L.Width -= zext;
2596 }
2597
2598 return L;
2599 }
2600
2601 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00002602 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00002603 return GetExprRange(C, BO->getRHS(), MaxWidth);
2604
John McCall60fad452010-01-06 22:07:33 +00002605 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00002606 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00002607 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00002608 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002609 // fallthrough
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002610
John McCallf2370c92010-01-06 05:24:50 +00002611 default:
2612 break;
2613 }
2614
2615 // Treat every other operator as if it were closed on the
2616 // narrowest type that encompasses both operands.
2617 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2618 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
2619 return IntRange::join(L, R);
2620 }
2621
2622 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2623 switch (UO->getOpcode()) {
2624 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00002625 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00002626 return IntRange::forBoolType();
2627
2628 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00002629 case UO_Deref:
2630 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00002631 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002632
2633 default:
2634 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
2635 }
2636 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002637
2638 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00002639 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002640 }
John McCallf2370c92010-01-06 05:24:50 +00002641
2642 FieldDecl *BitField = E->getBitField();
2643 if (BitField) {
2644 llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C);
2645 unsigned BitWidth = BitWidthAP.getZExtValue();
2646
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00002647 return IntRange(BitWidth,
2648 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00002649 }
2650
John McCall1844a6e2010-11-10 23:38:19 +00002651 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002652}
John McCall51313c32010-01-04 23:31:57 +00002653
John McCall323ed742010-05-06 08:58:33 +00002654IntRange GetExprRange(ASTContext &C, Expr *E) {
2655 return GetExprRange(C, E, C.getIntWidth(E->getType()));
2656}
2657
John McCall51313c32010-01-04 23:31:57 +00002658/// Checks whether the given value, which currently has the given
2659/// source semantics, has the same value when coerced through the
2660/// target semantics.
John McCallf2370c92010-01-06 05:24:50 +00002661bool IsSameFloatAfterCast(const llvm::APFloat &value,
2662 const llvm::fltSemantics &Src,
2663 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002664 llvm::APFloat truncated = value;
2665
2666 bool ignored;
2667 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
2668 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
2669
2670 return truncated.bitwiseIsEqual(value);
2671}
2672
2673/// Checks whether the given value, which currently has the given
2674/// source semantics, has the same value when coerced through the
2675/// target semantics.
2676///
2677/// The value might be a vector of floats (or a complex number).
John McCallf2370c92010-01-06 05:24:50 +00002678bool IsSameFloatAfterCast(const APValue &value,
2679 const llvm::fltSemantics &Src,
2680 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002681 if (value.isFloat())
2682 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
2683
2684 if (value.isVector()) {
2685 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
2686 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
2687 return false;
2688 return true;
2689 }
2690
2691 assert(value.isComplexFloat());
2692 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
2693 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
2694}
2695
John McCallb4eb64d2010-10-08 02:01:28 +00002696void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00002697
Ted Kremeneke3b159c2010-09-23 21:43:44 +00002698static bool IsZero(Sema &S, Expr *E) {
2699 // Suppress cases where we are comparing against an enum constant.
2700 if (const DeclRefExpr *DR =
2701 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
2702 if (isa<EnumConstantDecl>(DR->getDecl()))
2703 return false;
2704
2705 // Suppress cases where the '0' value is expanded from a macro.
2706 if (E->getLocStart().isMacroID())
2707 return false;
2708
John McCall323ed742010-05-06 08:58:33 +00002709 llvm::APSInt Value;
2710 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
2711}
2712
John McCall372e1032010-10-06 00:25:24 +00002713static bool HasEnumType(Expr *E) {
2714 // Strip off implicit integral promotions.
2715 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00002716 if (ICE->getCastKind() != CK_IntegralCast &&
2717 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00002718 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00002719 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00002720 }
2721
2722 return E->getType()->isEnumeralType();
2723}
2724
John McCall323ed742010-05-06 08:58:33 +00002725void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002726 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00002727 if (E->isValueDependent())
2728 return;
2729
John McCall2de56d12010-08-25 11:45:40 +00002730 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00002731 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002732 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00002733 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002734 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00002735 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002736 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00002737 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002738 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00002739 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002740 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00002741 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002742 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00002743 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002744 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00002745 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2746 }
2747}
2748
2749/// Analyze the operands of the given comparison. Implements the
2750/// fallback case from AnalyzeComparison.
2751void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00002752 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
2753 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00002754}
John McCall51313c32010-01-04 23:31:57 +00002755
John McCallba26e582010-01-04 23:21:16 +00002756/// \brief Implements -Wsign-compare.
2757///
2758/// \param lex the left-hand expression
2759/// \param rex the right-hand expression
2760/// \param OpLoc the location of the joining operator
John McCalld1b47bf2010-03-11 19:43:18 +00002761/// \param BinOpc binary opcode or 0
John McCall323ed742010-05-06 08:58:33 +00002762void AnalyzeComparison(Sema &S, BinaryOperator *E) {
2763 // The type the comparison is being performed in.
2764 QualType T = E->getLHS()->getType();
2765 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
2766 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00002767
John McCall323ed742010-05-06 08:58:33 +00002768 // We don't do anything special if this isn't an unsigned integral
2769 // comparison: we're only interested in integral comparisons, and
2770 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00002771 //
2772 // We also don't care about value-dependent expressions or expressions
2773 // whose result is a constant.
2774 if (!T->hasUnsignedIntegerRepresentation()
2775 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCall323ed742010-05-06 08:58:33 +00002776 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00002777
John McCall323ed742010-05-06 08:58:33 +00002778 Expr *lex = E->getLHS()->IgnoreParenImpCasts();
2779 Expr *rex = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00002780
John McCall323ed742010-05-06 08:58:33 +00002781 // Check to see if one of the (unmodified) operands is of different
2782 // signedness.
2783 Expr *signedOperand, *unsignedOperand;
Douglas Gregorf6094622010-07-23 15:58:24 +00002784 if (lex->getType()->hasSignedIntegerRepresentation()) {
2785 assert(!rex->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00002786 "unsigned comparison between two signed integer expressions?");
2787 signedOperand = lex;
2788 unsignedOperand = rex;
Douglas Gregorf6094622010-07-23 15:58:24 +00002789 } else if (rex->getType()->hasSignedIntegerRepresentation()) {
John McCall323ed742010-05-06 08:58:33 +00002790 signedOperand = rex;
2791 unsignedOperand = lex;
John McCallba26e582010-01-04 23:21:16 +00002792 } else {
John McCall323ed742010-05-06 08:58:33 +00002793 CheckTrivialUnsignedComparison(S, E);
2794 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00002795 }
2796
John McCall323ed742010-05-06 08:58:33 +00002797 // Otherwise, calculate the effective range of the signed operand.
2798 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00002799
John McCall323ed742010-05-06 08:58:33 +00002800 // Go ahead and analyze implicit conversions in the operands. Note
2801 // that we skip the implicit conversions on both sides.
John McCallb4eb64d2010-10-08 02:01:28 +00002802 AnalyzeImplicitConversions(S, lex, E->getOperatorLoc());
2803 AnalyzeImplicitConversions(S, rex, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00002804
John McCall323ed742010-05-06 08:58:33 +00002805 // If the signed range is non-negative, -Wsign-compare won't fire,
2806 // but we should still check for comparisons which are always true
2807 // or false.
2808 if (signedRange.NonNegative)
2809 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00002810
2811 // For (in)equality comparisons, if the unsigned operand is a
2812 // constant which cannot collide with a overflowed signed operand,
2813 // then reinterpreting the signed operand as unsigned will not
2814 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00002815 if (E->isEqualityOp()) {
2816 unsigned comparisonWidth = S.Context.getIntWidth(T);
2817 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00002818
John McCall323ed742010-05-06 08:58:33 +00002819 // We should never be unable to prove that the unsigned operand is
2820 // non-negative.
2821 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
2822
2823 if (unsignedRange.Width < comparisonWidth)
2824 return;
2825 }
2826
2827 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
2828 << lex->getType() << rex->getType()
2829 << lex->getSourceRange() << rex->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00002830}
2831
John McCall15d7d122010-11-11 03:21:53 +00002832/// Analyzes an attempt to assign the given value to a bitfield.
2833///
2834/// Returns true if there was something fishy about the attempt.
2835bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
2836 SourceLocation InitLoc) {
2837 assert(Bitfield->isBitField());
2838 if (Bitfield->isInvalidDecl())
2839 return false;
2840
John McCall91b60142010-11-11 05:33:51 +00002841 // White-list bool bitfields.
2842 if (Bitfield->getType()->isBooleanType())
2843 return false;
2844
Douglas Gregor46ff3032011-02-04 13:09:01 +00002845 // Ignore value- or type-dependent expressions.
2846 if (Bitfield->getBitWidth()->isValueDependent() ||
2847 Bitfield->getBitWidth()->isTypeDependent() ||
2848 Init->isValueDependent() ||
2849 Init->isTypeDependent())
2850 return false;
2851
John McCall15d7d122010-11-11 03:21:53 +00002852 Expr *OriginalInit = Init->IgnoreParenImpCasts();
2853
2854 llvm::APSInt Width(32);
2855 Expr::EvalResult InitValue;
2856 if (!Bitfield->getBitWidth()->isIntegerConstantExpr(Width, S.Context) ||
John McCall91b60142010-11-11 05:33:51 +00002857 !OriginalInit->Evaluate(InitValue, S.Context) ||
John McCall15d7d122010-11-11 03:21:53 +00002858 !InitValue.Val.isInt())
2859 return false;
2860
2861 const llvm::APSInt &Value = InitValue.Val.getInt();
2862 unsigned OriginalWidth = Value.getBitWidth();
2863 unsigned FieldWidth = Width.getZExtValue();
2864
2865 if (OriginalWidth <= FieldWidth)
2866 return false;
2867
Jay Foad9f71a8f2010-12-07 08:25:34 +00002868 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
John McCall15d7d122010-11-11 03:21:53 +00002869
2870 // It's fairly common to write values into signed bitfields
2871 // that, if sign-extended, would end up becoming a different
2872 // value. We don't want to warn about that.
2873 if (Value.isSigned() && Value.isNegative())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002874 TruncatedValue = TruncatedValue.sext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00002875 else
Jay Foad9f71a8f2010-12-07 08:25:34 +00002876 TruncatedValue = TruncatedValue.zext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00002877
2878 if (Value == TruncatedValue)
2879 return false;
2880
2881 std::string PrettyValue = Value.toString(10);
2882 std::string PrettyTrunc = TruncatedValue.toString(10);
2883
2884 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
2885 << PrettyValue << PrettyTrunc << OriginalInit->getType()
2886 << Init->getSourceRange();
2887
2888 return true;
2889}
2890
John McCallbeb22aa2010-11-09 23:24:47 +00002891/// Analyze the given simple or compound assignment for warning-worthy
2892/// operations.
2893void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
2894 // Just recurse on the LHS.
2895 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
2896
2897 // We want to recurse on the RHS as normal unless we're assigning to
2898 // a bitfield.
2899 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00002900 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
2901 E->getOperatorLoc())) {
2902 // Recurse, ignoring any implicit conversions on the RHS.
2903 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
2904 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00002905 }
2906 }
2907
2908 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
2909}
2910
John McCall51313c32010-01-04 23:31:57 +00002911/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00002912void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
2913 SourceLocation CContext, unsigned diag) {
2914 S.Diag(E->getExprLoc(), diag)
2915 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
2916}
2917
Chandler Carruthe1b02e02011-04-05 06:47:57 +00002918/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
2919void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
2920 unsigned diag) {
2921 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag);
2922}
2923
Chandler Carruthf65076e2011-04-10 08:36:24 +00002924/// Diagnose an implicit cast from a literal expression. Also attemps to supply
2925/// fixit hints when the cast wouldn't lose information to simply write the
2926/// expression with the expected type.
2927void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
2928 SourceLocation CContext) {
2929 // Emit the primary warning first, then try to emit a fixit hint note if
2930 // reasonable.
2931 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
2932 << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext);
2933
2934 const llvm::APFloat &Value = FL->getValue();
2935
2936 // Don't attempt to fix PPC double double literals.
2937 if (&Value.getSemantics() == &llvm::APFloat::PPCDoubleDouble)
2938 return;
2939
2940 // Try to convert this exactly to an 64-bit integer. FIXME: It would be
2941 // nice to support arbitrarily large integers here.
2942 bool isExact = false;
2943 uint64_t IntegerPart;
2944 if (Value.convertToInteger(&IntegerPart, 64, /*isSigned=*/true,
2945 llvm::APFloat::rmTowardZero, &isExact)
2946 != llvm::APFloat::opOK || !isExact)
2947 return;
2948
2949 llvm::APInt IntegerValue(64, IntegerPart, /*isSigned=*/true);
2950
2951 std::string LiteralValue = IntegerValue.toString(10, /*isSigned=*/true);
2952 S.Diag(FL->getExprLoc(), diag::note_fix_integral_float_as_integer)
2953 << FixItHint::CreateReplacement(FL->getSourceRange(), LiteralValue);
2954}
2955
John McCall091f23f2010-11-09 22:22:12 +00002956std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
2957 if (!Range.Width) return "0";
2958
2959 llvm::APSInt ValueInRange = Value;
2960 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002961 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00002962 return ValueInRange.toString(10);
2963}
2964
Ted Kremenekef9ff882011-03-10 20:03:42 +00002965static bool isFromSystemMacro(Sema &S, SourceLocation loc) {
2966 SourceManager &smgr = S.Context.getSourceManager();
2967 return loc.isMacroID() && smgr.isInSystemHeader(smgr.getSpellingLoc(loc));
2968}
Chandler Carruthf65076e2011-04-10 08:36:24 +00002969
John McCall323ed742010-05-06 08:58:33 +00002970void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00002971 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00002972 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00002973
John McCall323ed742010-05-06 08:58:33 +00002974 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
2975 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
2976 if (Source == Target) return;
2977 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00002978
Ted Kremenekef9ff882011-03-10 20:03:42 +00002979 // If the conversion context location is invalid don't complain.
2980 // We also don't want to emit a warning if the issue occurs from the
2981 // instantiation of a system macro. The problem is that 'getSpellingLoc()'
2982 // is slow, so we delay this check as long as possible. Once we detect
2983 // we are in that scenario, we just return.
2984 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00002985 return;
2986
John McCall51313c32010-01-04 23:31:57 +00002987 // Never diagnose implicit casts to bool.
2988 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
2989 return;
2990
2991 // Strip vector types.
2992 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00002993 if (!isa<VectorType>(Target)) {
2994 if (isFromSystemMacro(S, CC))
2995 return;
John McCallb4eb64d2010-10-08 02:01:28 +00002996 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00002997 }
Chris Lattnerb792b302011-06-14 04:51:15 +00002998
2999 // If the vector cast is cast between two vectors of the same size, it is
3000 // a bitcast, not a conversion.
3001 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
3002 return;
John McCall51313c32010-01-04 23:31:57 +00003003
3004 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
3005 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
3006 }
3007
3008 // Strip complex types.
3009 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003010 if (!isa<ComplexType>(Target)) {
3011 if (isFromSystemMacro(S, CC))
3012 return;
3013
John McCallb4eb64d2010-10-08 02:01:28 +00003014 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003015 }
John McCall51313c32010-01-04 23:31:57 +00003016
3017 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
3018 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
3019 }
3020
3021 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
3022 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
3023
3024 // If the source is floating point...
3025 if (SourceBT && SourceBT->isFloatingPoint()) {
3026 // ...and the target is floating point...
3027 if (TargetBT && TargetBT->isFloatingPoint()) {
3028 // ...then warn if we're dropping FP rank.
3029
3030 // Builtin FP kinds are ordered by increasing FP rank.
3031 if (SourceBT->getKind() > TargetBT->getKind()) {
3032 // Don't warn about float constants that are precisely
3033 // representable in the target type.
3034 Expr::EvalResult result;
John McCall323ed742010-05-06 08:58:33 +00003035 if (E->Evaluate(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00003036 // Value might be a float, a float vector, or a float complex.
3037 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00003038 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
3039 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00003040 return;
3041 }
3042
Ted Kremenekef9ff882011-03-10 20:03:42 +00003043 if (isFromSystemMacro(S, CC))
3044 return;
3045
John McCallb4eb64d2010-10-08 02:01:28 +00003046 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00003047 }
3048 return;
3049 }
3050
Ted Kremenekef9ff882011-03-10 20:03:42 +00003051 // If the target is integral, always warn.
Chandler Carrutha5b93322011-02-17 11:05:49 +00003052 if ((TargetBT && TargetBT->isInteger())) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003053 if (isFromSystemMacro(S, CC))
3054 return;
3055
Chandler Carrutha5b93322011-02-17 11:05:49 +00003056 Expr *InnerE = E->IgnoreParenImpCasts();
Chandler Carruthf65076e2011-04-10 08:36:24 +00003057 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
3058 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00003059 } else {
3060 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
3061 }
3062 }
John McCall51313c32010-01-04 23:31:57 +00003063
3064 return;
3065 }
3066
John McCallf2370c92010-01-06 05:24:50 +00003067 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00003068 return;
3069
Richard Trieu1838ca52011-05-29 19:59:02 +00003070 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
3071 == Expr::NPCK_GNUNull) && Target->isIntegerType()) {
3072 S.Diag(E->getExprLoc(), diag::warn_impcast_null_pointer_to_integer)
3073 << E->getSourceRange() << clang::SourceRange(CC);
3074 return;
3075 }
3076
John McCall323ed742010-05-06 08:58:33 +00003077 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00003078 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00003079
3080 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00003081 // If the source is a constant, use a default-on diagnostic.
3082 // TODO: this should happen for bitfield stores, too.
3083 llvm::APSInt Value(32);
3084 if (E->isIntegerConstantExpr(Value, S.Context)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003085 if (isFromSystemMacro(S, CC))
3086 return;
3087
John McCall091f23f2010-11-09 22:22:12 +00003088 std::string PrettySourceValue = Value.toString(10);
3089 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
3090
3091 S.Diag(E->getExprLoc(), diag::warn_impcast_integer_precision_constant)
3092 << PrettySourceValue << PrettyTargetValue
3093 << E->getType() << T << E->getSourceRange() << clang::SourceRange(CC);
3094 return;
3095 }
3096
Chris Lattnerb792b302011-06-14 04:51:15 +00003097 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
Ted Kremenekef9ff882011-03-10 20:03:42 +00003098 if (isFromSystemMacro(S, CC))
3099 return;
3100
John McCallf2370c92010-01-06 05:24:50 +00003101 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCallb4eb64d2010-10-08 02:01:28 +00003102 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32);
3103 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00003104 }
3105
3106 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
3107 (!TargetRange.NonNegative && SourceRange.NonNegative &&
3108 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003109
3110 if (isFromSystemMacro(S, CC))
3111 return;
3112
John McCall323ed742010-05-06 08:58:33 +00003113 unsigned DiagID = diag::warn_impcast_integer_sign;
3114
3115 // Traditionally, gcc has warned about this under -Wsign-compare.
3116 // We also want to warn about it in -Wconversion.
3117 // So if -Wconversion is off, use a completely identical diagnostic
3118 // in the sign-compare group.
3119 // The conditional-checking code will
3120 if (ICContext) {
3121 DiagID = diag::warn_impcast_integer_sign_conditional;
3122 *ICContext = true;
3123 }
3124
John McCallb4eb64d2010-10-08 02:01:28 +00003125 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00003126 }
3127
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003128 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003129 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
3130 // type, to give us better diagnostics.
3131 QualType SourceType = E->getType();
3132 if (!S.getLangOptions().CPlusPlus) {
3133 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3134 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3135 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
3136 SourceType = S.Context.getTypeDeclType(Enum);
3137 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
3138 }
3139 }
3140
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003141 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
3142 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
3143 if ((SourceEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00003144 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003145 (TargetEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00003146 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00003147 SourceEnum != TargetEnum) {
3148 if (isFromSystemMacro(S, CC))
3149 return;
3150
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003151 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003152 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003153 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003154
John McCall51313c32010-01-04 23:31:57 +00003155 return;
3156}
3157
John McCall323ed742010-05-06 08:58:33 +00003158void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
3159
3160void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00003161 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00003162 E = E->IgnoreParenImpCasts();
3163
3164 if (isa<ConditionalOperator>(E))
3165 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
3166
John McCallb4eb64d2010-10-08 02:01:28 +00003167 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003168 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00003169 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00003170 return;
3171}
3172
3173void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00003174 SourceLocation CC = E->getQuestionLoc();
3175
3176 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00003177
3178 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00003179 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
3180 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003181
3182 // If -Wconversion would have warned about either of the candidates
3183 // for a signedness conversion to the context type...
3184 if (!Suspicious) return;
3185
3186 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003187 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
3188 CC))
John McCall323ed742010-05-06 08:58:33 +00003189 return;
3190
3191 // ...and -Wsign-compare isn't...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003192 if (!S.Diags.getDiagnosticLevel(diag::warn_mixed_sign_conditional, CC))
John McCall323ed742010-05-06 08:58:33 +00003193 return;
3194
3195 // ...then check whether it would have warned about either of the
3196 // candidates for a signedness conversion to the condition type.
3197 if (E->getType() != T) {
3198 Suspicious = false;
3199 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00003200 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003201 if (!Suspicious)
3202 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00003203 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003204 if (!Suspicious)
3205 return;
3206 }
3207
3208 // If so, emit a diagnostic under -Wsign-compare.
3209 Expr *lex = E->getTrueExpr()->IgnoreParenImpCasts();
3210 Expr *rex = E->getFalseExpr()->IgnoreParenImpCasts();
3211 S.Diag(E->getQuestionLoc(), diag::warn_mixed_sign_conditional)
3212 << lex->getType() << rex->getType()
3213 << lex->getSourceRange() << rex->getSourceRange();
3214}
3215
3216/// AnalyzeImplicitConversions - Find and report any interesting
3217/// implicit conversions in the given expression. There are a couple
3218/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00003219void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00003220 QualType T = OrigE->getType();
3221 Expr *E = OrigE->IgnoreParenImpCasts();
3222
3223 // For conditional operators, we analyze the arguments as if they
3224 // were being fed directly into the output.
3225 if (isa<ConditionalOperator>(E)) {
3226 ConditionalOperator *CO = cast<ConditionalOperator>(E);
3227 CheckConditionalOperator(S, CO, T);
3228 return;
3229 }
3230
3231 // Go ahead and check any implicit conversions we might have skipped.
3232 // The non-canonical typecheck is just an optimization;
3233 // CheckImplicitConversion will filter out dead implicit conversions.
3234 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00003235 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00003236
3237 // Now continue drilling into this expression.
3238
3239 // Skip past explicit casts.
3240 if (isa<ExplicitCastExpr>(E)) {
3241 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00003242 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003243 }
3244
John McCallbeb22aa2010-11-09 23:24:47 +00003245 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3246 // Do a somewhat different check with comparison operators.
3247 if (BO->isComparisonOp())
3248 return AnalyzeComparison(S, BO);
3249
3250 // And with assignments and compound assignments.
3251 if (BO->isAssignmentOp())
3252 return AnalyzeAssignment(S, BO);
3253 }
John McCall323ed742010-05-06 08:58:33 +00003254
3255 // These break the otherwise-useful invariant below. Fortunately,
3256 // we don't really need to recurse into them, because any internal
3257 // expressions should have been analyzed already when they were
3258 // built into statements.
3259 if (isa<StmtExpr>(E)) return;
3260
3261 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003262 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00003263
3264 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00003265 CC = E->getExprLoc();
John McCall7502c1d2011-02-13 04:07:26 +00003266 for (Stmt::child_range I = E->children(); I; ++I)
John McCallb4eb64d2010-10-08 02:01:28 +00003267 AnalyzeImplicitConversions(S, cast<Expr>(*I), CC);
John McCall323ed742010-05-06 08:58:33 +00003268}
3269
3270} // end anonymous namespace
3271
3272/// Diagnoses "dangerous" implicit conversions within the given
3273/// expression (which is a full expression). Implements -Wconversion
3274/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00003275///
3276/// \param CC the "context" location of the implicit conversion, i.e.
3277/// the most location of the syntactic entity requiring the implicit
3278/// conversion
3279void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00003280 // Don't diagnose in unevaluated contexts.
3281 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
3282 return;
3283
3284 // Don't diagnose for value- or type-dependent expressions.
3285 if (E->isTypeDependent() || E->isValueDependent())
3286 return;
3287
John McCallb4eb64d2010-10-08 02:01:28 +00003288 // This is not the right CC for (e.g.) a variable initialization.
3289 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003290}
3291
John McCall15d7d122010-11-11 03:21:53 +00003292void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
3293 FieldDecl *BitField,
3294 Expr *Init) {
3295 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
3296}
3297
Mike Stumpf8c49212010-01-21 03:59:47 +00003298/// CheckParmsForFunctionDef - Check that the parameters of the given
3299/// function are appropriate for the definition of a function. This
3300/// takes care of any checks that cannot be performed on the
3301/// declaration itself, e.g., that the types of each of the function
3302/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00003303bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
3304 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00003305 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00003306 for (; P != PEnd; ++P) {
3307 ParmVarDecl *Param = *P;
3308
Mike Stumpf8c49212010-01-21 03:59:47 +00003309 // C99 6.7.5.3p4: the parameters in a parameter type list in a
3310 // function declarator that is part of a function definition of
3311 // that function shall not have incomplete type.
3312 //
3313 // This is also C++ [dcl.fct]p6.
3314 if (!Param->isInvalidDecl() &&
3315 RequireCompleteType(Param->getLocation(), Param->getType(),
3316 diag::err_typecheck_decl_incomplete_type)) {
3317 Param->setInvalidDecl();
3318 HasInvalidParm = true;
3319 }
3320
3321 // C99 6.9.1p5: If the declarator includes a parameter type list, the
3322 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00003323 if (CheckParameterNames &&
3324 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00003325 !Param->isImplicit() &&
3326 !getLangOptions().CPlusPlus)
3327 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00003328
3329 // C99 6.7.5.3p12:
3330 // If the function declarator is not part of a definition of that
3331 // function, parameters may have incomplete type and may use the [*]
3332 // notation in their sequences of declarator specifiers to specify
3333 // variable length array types.
3334 QualType PType = Param->getOriginalType();
3335 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
3336 if (AT->getSizeModifier() == ArrayType::Star) {
3337 // FIXME: This diagnosic should point the the '[*]' if source-location
3338 // information is added for it.
3339 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
3340 }
3341 }
Mike Stumpf8c49212010-01-21 03:59:47 +00003342 }
3343
3344 return HasInvalidParm;
3345}
John McCallb7f4ffe2010-08-12 21:44:57 +00003346
3347/// CheckCastAlign - Implements -Wcast-align, which warns when a
3348/// pointer cast increases the alignment requirements.
3349void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
3350 // This is actually a lot of work to potentially be doing on every
3351 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003352 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
3353 TRange.getBegin())
John McCallb7f4ffe2010-08-12 21:44:57 +00003354 == Diagnostic::Ignored)
3355 return;
3356
3357 // Ignore dependent types.
3358 if (T->isDependentType() || Op->getType()->isDependentType())
3359 return;
3360
3361 // Require that the destination be a pointer type.
3362 const PointerType *DestPtr = T->getAs<PointerType>();
3363 if (!DestPtr) return;
3364
3365 // If the destination has alignment 1, we're done.
3366 QualType DestPointee = DestPtr->getPointeeType();
3367 if (DestPointee->isIncompleteType()) return;
3368 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
3369 if (DestAlign.isOne()) return;
3370
3371 // Require that the source be a pointer type.
3372 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
3373 if (!SrcPtr) return;
3374 QualType SrcPointee = SrcPtr->getPointeeType();
3375
3376 // Whitelist casts from cv void*. We already implicitly
3377 // whitelisted casts to cv void*, since they have alignment 1.
3378 // Also whitelist casts involving incomplete types, which implicitly
3379 // includes 'void'.
3380 if (SrcPointee->isIncompleteType()) return;
3381
3382 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
3383 if (SrcAlign >= DestAlign) return;
3384
3385 Diag(TRange.getBegin(), diag::warn_cast_align)
3386 << Op->getType() << T
3387 << static_cast<unsigned>(SrcAlign.getQuantity())
3388 << static_cast<unsigned>(DestAlign.getQuantity())
3389 << TRange << Op->getSourceRange();
3390}
3391
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003392static void CheckArrayAccess_Check(Sema &S,
3393 const clang::ArraySubscriptExpr *E) {
Chandler Carruth35001ca2011-02-17 21:10:52 +00003394 const Expr *BaseExpr = E->getBase()->IgnoreParenImpCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00003395 const ConstantArrayType *ArrayTy =
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003396 S.Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00003397 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00003398 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00003399
Chandler Carruth34064582011-02-17 20:55:08 +00003400 const Expr *IndexExpr = E->getIdx();
3401 if (IndexExpr->isValueDependent())
Ted Kremeneka0125d82011-02-16 01:57:07 +00003402 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003403 llvm::APSInt index;
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003404 if (!IndexExpr->isIntegerConstantExpr(index, S.Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00003405 return;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00003406
Ted Kremenek9e060ca2011-02-23 23:06:04 +00003407 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00003408 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00003409 if (!size.isStrictlyPositive())
3410 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003411 if (size.getBitWidth() > index.getBitWidth())
3412 index = index.sext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00003413 else if (size.getBitWidth() < index.getBitWidth())
3414 size = size.sext(index.getBitWidth());
3415
Chandler Carruth34064582011-02-17 20:55:08 +00003416 if (index.slt(size))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00003417 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003418
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003419 S.DiagRuntimeBehavior(E->getBase()->getLocStart(), BaseExpr,
3420 S.PDiag(diag::warn_array_index_exceeds_bounds)
3421 << index.toString(10, true)
3422 << size.toString(10, true)
3423 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00003424 } else {
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003425 S.DiagRuntimeBehavior(E->getBase()->getLocStart(), BaseExpr,
3426 S.PDiag(diag::warn_array_index_precedes_bounds)
3427 << index.toString(10, true)
3428 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00003429 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00003430
3431 const NamedDecl *ND = NULL;
3432 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
3433 ND = dyn_cast<NamedDecl>(DRE->getDecl());
3434 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
3435 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
3436 if (ND)
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003437 S.DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
3438 S.PDiag(diag::note_array_index_out_of_bounds)
3439 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00003440}
3441
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003442void Sema::CheckArrayAccess(const Expr *expr) {
Peter Collingbournef111d932011-04-15 00:35:48 +00003443 while (true) {
3444 expr = expr->IgnoreParens();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003445 switch (expr->getStmtClass()) {
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003446 case Stmt::ArraySubscriptExprClass:
3447 CheckArrayAccess_Check(*this, cast<ArraySubscriptExpr>(expr));
3448 return;
3449 case Stmt::ConditionalOperatorClass: {
3450 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
3451 if (const Expr *lhs = cond->getLHS())
3452 CheckArrayAccess(lhs);
3453 if (const Expr *rhs = cond->getRHS())
3454 CheckArrayAccess(rhs);
3455 return;
3456 }
3457 default:
3458 return;
3459 }
Peter Collingbournef111d932011-04-15 00:35:48 +00003460 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003461}
John McCallf85e1932011-06-15 23:02:42 +00003462
3463//===--- CHECK: Objective-C retain cycles ----------------------------------//
3464
3465namespace {
3466 struct RetainCycleOwner {
3467 RetainCycleOwner() : Variable(0), Indirect(false) {}
3468 VarDecl *Variable;
3469 SourceRange Range;
3470 SourceLocation Loc;
3471 bool Indirect;
3472
3473 void setLocsFrom(Expr *e) {
3474 Loc = e->getExprLoc();
3475 Range = e->getSourceRange();
3476 }
3477 };
3478}
3479
3480/// Consider whether capturing the given variable can possibly lead to
3481/// a retain cycle.
3482static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
3483 // In ARC, it's captured strongly iff the variable has __strong
3484 // lifetime. In MRR, it's captured strongly if the variable is
3485 // __block and has an appropriate type.
3486 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
3487 return false;
3488
3489 owner.Variable = var;
3490 owner.setLocsFrom(ref);
3491 return true;
3492}
3493
3494static bool findRetainCycleOwner(Expr *e, RetainCycleOwner &owner) {
3495 while (true) {
3496 e = e->IgnoreParens();
3497 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
3498 switch (cast->getCastKind()) {
3499 case CK_BitCast:
3500 case CK_LValueBitCast:
3501 case CK_LValueToRValue:
3502 e = cast->getSubExpr();
3503 continue;
3504
3505 case CK_GetObjCProperty: {
3506 // Bail out if this isn't a strong explicit property.
3507 const ObjCPropertyRefExpr *pre = cast->getSubExpr()->getObjCProperty();
3508 if (pre->isImplicitProperty()) return false;
3509 ObjCPropertyDecl *property = pre->getExplicitProperty();
3510 if (!(property->getPropertyAttributes() &
3511 (ObjCPropertyDecl::OBJC_PR_retain |
3512 ObjCPropertyDecl::OBJC_PR_copy |
3513 ObjCPropertyDecl::OBJC_PR_strong)) &&
3514 !(property->getPropertyIvarDecl() &&
3515 property->getPropertyIvarDecl()->getType()
3516 .getObjCLifetime() == Qualifiers::OCL_Strong))
3517 return false;
3518
3519 owner.Indirect = true;
3520 e = const_cast<Expr*>(pre->getBase());
3521 continue;
3522 }
3523
3524 default:
3525 return false;
3526 }
3527 }
3528
3529 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
3530 ObjCIvarDecl *ivar = ref->getDecl();
3531 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
3532 return false;
3533
3534 // Try to find a retain cycle in the base.
3535 if (!findRetainCycleOwner(ref->getBase(), owner))
3536 return false;
3537
3538 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
3539 owner.Indirect = true;
3540 return true;
3541 }
3542
3543 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
3544 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
3545 if (!var) return false;
3546 return considerVariable(var, ref, owner);
3547 }
3548
3549 if (BlockDeclRefExpr *ref = dyn_cast<BlockDeclRefExpr>(e)) {
3550 owner.Variable = ref->getDecl();
3551 owner.setLocsFrom(ref);
3552 return true;
3553 }
3554
3555 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
3556 if (member->isArrow()) return false;
3557
3558 // Don't count this as an indirect ownership.
3559 e = member->getBase();
3560 continue;
3561 }
3562
3563 // Array ivars?
3564
3565 return false;
3566 }
3567}
3568
3569namespace {
3570 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
3571 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
3572 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
3573 Variable(variable), Capturer(0) {}
3574
3575 VarDecl *Variable;
3576 Expr *Capturer;
3577
3578 void VisitDeclRefExpr(DeclRefExpr *ref) {
3579 if (ref->getDecl() == Variable && !Capturer)
3580 Capturer = ref;
3581 }
3582
3583 void VisitBlockDeclRefExpr(BlockDeclRefExpr *ref) {
3584 if (ref->getDecl() == Variable && !Capturer)
3585 Capturer = ref;
3586 }
3587
3588 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
3589 if (Capturer) return;
3590 Visit(ref->getBase());
3591 if (Capturer && ref->isFreeIvar())
3592 Capturer = ref;
3593 }
3594
3595 void VisitBlockExpr(BlockExpr *block) {
3596 // Look inside nested blocks
3597 if (block->getBlockDecl()->capturesVariable(Variable))
3598 Visit(block->getBlockDecl()->getBody());
3599 }
3600 };
3601}
3602
3603/// Check whether the given argument is a block which captures a
3604/// variable.
3605static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
3606 assert(owner.Variable && owner.Loc.isValid());
3607
3608 e = e->IgnoreParenCasts();
3609 BlockExpr *block = dyn_cast<BlockExpr>(e);
3610 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
3611 return 0;
3612
3613 FindCaptureVisitor visitor(S.Context, owner.Variable);
3614 visitor.Visit(block->getBlockDecl()->getBody());
3615 return visitor.Capturer;
3616}
3617
3618static void diagnoseRetainCycle(Sema &S, Expr *capturer,
3619 RetainCycleOwner &owner) {
3620 assert(capturer);
3621 assert(owner.Variable && owner.Loc.isValid());
3622
3623 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
3624 << owner.Variable << capturer->getSourceRange();
3625 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
3626 << owner.Indirect << owner.Range;
3627}
3628
3629/// Check for a keyword selector that starts with the word 'add' or
3630/// 'set'.
3631static bool isSetterLikeSelector(Selector sel) {
3632 if (sel.isUnarySelector()) return false;
3633
3634 llvm::StringRef str = sel.getNameForSlot(0);
3635 while (!str.empty() && str.front() == '_') str = str.substr(1);
3636 if (str.startswith("set") || str.startswith("add"))
3637 str = str.substr(3);
3638 else
3639 return false;
3640
3641 if (str.empty()) return true;
3642 return !islower(str.front());
3643}
3644
3645/// Check a message send to see if it's likely to cause a retain cycle.
3646void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
3647 // Only check instance methods whose selector looks like a setter.
3648 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
3649 return;
3650
3651 // Try to find a variable that the receiver is strongly owned by.
3652 RetainCycleOwner owner;
3653 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
3654 if (!findRetainCycleOwner(msg->getInstanceReceiver(), owner))
3655 return;
3656 } else {
3657 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
3658 owner.Variable = getCurMethodDecl()->getSelfDecl();
3659 owner.Loc = msg->getSuperLoc();
3660 owner.Range = msg->getSuperLoc();
3661 }
3662
3663 // Check whether the receiver is captured by any of the arguments.
3664 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
3665 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
3666 return diagnoseRetainCycle(*this, capturer, owner);
3667}
3668
3669/// Check a property assign to see if it's likely to cause a retain cycle.
3670void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
3671 RetainCycleOwner owner;
3672 if (!findRetainCycleOwner(receiver, owner))
3673 return;
3674
3675 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
3676 diagnoseRetainCycle(*this, capturer, owner);
3677}
3678
3679void Sema::checkUnsafeAssigns(SourceLocation Loc,
3680 QualType LHS, Expr *RHS) {
3681 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
3682 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
3683 return;
3684 if (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS))
3685 if (cast->getCastKind() == CK_ObjCConsumeObject)
3686 Diag(Loc, diag::warn_arc_retained_assign)
3687 << (LT == Qualifiers::OCL_ExplicitNone)
3688 << RHS->getSourceRange();
3689}
3690