blob: a9d79bb70a0254505bf876b68f5f9ca0c81e029a [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
John McCall5f8d6042011-08-27 01:09:30 +000015#include "clang/Sema/Initialization.h"
Douglas Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/Sema.h"
John McCall2d887082010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Eli Friedman276b0612011-10-11 02:20:01 +000018#include "clang/Sema/Initialization.h"
John McCall781472f2010-08-25 08:40:02 +000019#include "clang/Sema/ScopeInfo.h"
Ted Kremenek826a3452010-07-16 02:11:22 +000020#include "clang/Analysis/Analyses/FormatString.h"
Chris Lattner59907c42007-08-10 20:18:51 +000021#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000022#include "clang/AST/CharUnits.h"
John McCall384aff82010-08-25 07:42:41 +000023#include "clang/AST/DeclCXX.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000024#include "clang/AST/DeclObjC.h"
Ted Kremenek23245122007-08-20 16:18:38 +000025#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000026#include "clang/AST/ExprObjC.h"
John McCallf85e1932011-06-15 23:02:42 +000027#include "clang/AST/EvaluatedExprVisitor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000028#include "clang/AST/DeclObjC.h"
29#include "clang/AST/StmtCXX.h"
30#include "clang/AST/StmtObjC.h"
Chris Lattner59907c42007-08-10 20:18:51 +000031#include "clang/Lex/Preprocessor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000032#include "llvm/ADT/BitVector.h"
33#include "llvm/ADT/STLExtras.h"
Tom Care3bfc5f42010-06-09 04:11:11 +000034#include "llvm/Support/raw_ostream.h"
Eric Christopher691ebc32010-04-17 02:26:23 +000035#include "clang/Basic/TargetBuiltins.h"
Nate Begeman26a31422010-06-08 02:47:44 +000036#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian7da71022010-09-07 19:38:13 +000037#include "clang/Basic/ConvertUTF.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000038#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000039using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000040using namespace sema;
Chris Lattner59907c42007-08-10 20:18:51 +000041
Chris Lattner60800082009-02-18 17:49:48 +000042SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
43 unsigned ByteNo) const {
Chris Lattner08f92e32010-11-17 07:37:15 +000044 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
45 PP.getLangOptions(), PP.getTargetInfo());
Chris Lattner60800082009-02-18 17:49:48 +000046}
Chris Lattner08f92e32010-11-17 07:37:15 +000047
Chris Lattner60800082009-02-18 17:49:48 +000048
Ryan Flynn4403a5e2009-08-06 03:00:50 +000049/// CheckablePrintfAttr - does a function call have a "printf" attribute
50/// and arguments that merit checking?
51bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) {
52 if (Format->getType() == "printf") return true;
53 if (Format->getType() == "printf0") {
54 // printf0 allows null "format" string; if so don't check format/args
55 unsigned format_idx = Format->getFormatIdx() - 1;
Sebastian Redl4a2614e2009-11-17 18:02:24 +000056 // Does the index refer to the implicit object argument?
57 if (isa<CXXMemberCallExpr>(TheCall)) {
58 if (format_idx == 0)
59 return false;
60 --format_idx;
61 }
Ryan Flynn4403a5e2009-08-06 03:00:50 +000062 if (format_idx < TheCall->getNumArgs()) {
63 Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts();
Ted Kremenekefaff192010-02-27 01:41:03 +000064 if (!Format->isNullPointerConstant(Context,
65 Expr::NPC_ValueDependentIsNull))
Ryan Flynn4403a5e2009-08-06 03:00:50 +000066 return true;
67 }
68 }
69 return false;
70}
Chris Lattner60800082009-02-18 17:49:48 +000071
John McCall8e10f3b2011-02-26 05:39:39 +000072/// Checks that a call expression's argument count is the desired number.
73/// This is useful when doing custom type-checking. Returns true on error.
74static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
75 unsigned argCount = call->getNumArgs();
76 if (argCount == desiredArgCount) return false;
77
78 if (argCount < desiredArgCount)
79 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
80 << 0 /*function call*/ << desiredArgCount << argCount
81 << call->getSourceRange();
82
83 // Highlight all the excess arguments.
84 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
85 call->getArg(argCount - 1)->getLocEnd());
86
87 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
88 << 0 /*function call*/ << desiredArgCount << argCount
89 << call->getArg(1)->getSourceRange();
90}
91
Julien Lerouge77f68bb2011-09-09 22:41:49 +000092/// CheckBuiltinAnnotationString - Checks that string argument to the builtin
93/// annotation is a non wide string literal.
94static bool CheckBuiltinAnnotationString(Sema &S, Expr *Arg) {
95 Arg = Arg->IgnoreParenCasts();
96 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
97 if (!Literal || !Literal->isAscii()) {
98 S.Diag(Arg->getLocStart(), diag::err_builtin_annotation_not_string_constant)
99 << Arg->getSourceRange();
100 return true;
101 }
102 return false;
103}
104
John McCall60d7b3a2010-08-24 06:29:42 +0000105ExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +0000106Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCall60d7b3a2010-08-24 06:29:42 +0000107 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +0000108
Chris Lattner946928f2010-10-01 23:23:24 +0000109 // Find out if any arguments are required to be integer constant expressions.
110 unsigned ICEArguments = 0;
111 ASTContext::GetBuiltinTypeError Error;
112 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
113 if (Error != ASTContext::GE_None)
114 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
115
116 // If any arguments are required to be ICE's, check and diagnose.
117 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
118 // Skip arguments not required to be ICE's.
119 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
120
121 llvm::APSInt Result;
122 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
123 return true;
124 ICEArguments &= ~(1 << ArgNo);
125 }
126
Anders Carlssond406bf02009-08-16 01:56:34 +0000127 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000128 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000129 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000130 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000131 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000132 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000133 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000134 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000135 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000136 if (SemaBuiltinVAStart(TheCall))
137 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000138 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000139 case Builtin::BI__builtin_isgreater:
140 case Builtin::BI__builtin_isgreaterequal:
141 case Builtin::BI__builtin_isless:
142 case Builtin::BI__builtin_islessequal:
143 case Builtin::BI__builtin_islessgreater:
144 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000145 if (SemaBuiltinUnorderedCompare(TheCall))
146 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000147 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000148 case Builtin::BI__builtin_fpclassify:
149 if (SemaBuiltinFPClassification(TheCall, 6))
150 return ExprError();
151 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000152 case Builtin::BI__builtin_isfinite:
153 case Builtin::BI__builtin_isinf:
154 case Builtin::BI__builtin_isinf_sign:
155 case Builtin::BI__builtin_isnan:
156 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000157 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000158 return ExprError();
159 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000160 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000161 return SemaBuiltinShuffleVector(TheCall);
162 // TheCall will be freed by the smart pointer here, but that's fine, since
163 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000164 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000165 if (SemaBuiltinPrefetch(TheCall))
166 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000167 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000168 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000169 if (SemaBuiltinObjectSize(TheCall))
170 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000171 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000172 case Builtin::BI__builtin_longjmp:
173 if (SemaBuiltinLongjmp(TheCall))
174 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000175 break;
John McCall8e10f3b2011-02-26 05:39:39 +0000176
177 case Builtin::BI__builtin_classify_type:
178 if (checkArgCount(*this, TheCall, 1)) return true;
179 TheCall->setType(Context.IntTy);
180 break;
Chris Lattner75c29a02010-10-12 17:47:42 +0000181 case Builtin::BI__builtin_constant_p:
John McCall8e10f3b2011-02-26 05:39:39 +0000182 if (checkArgCount(*this, TheCall, 1)) return true;
183 TheCall->setType(Context.IntTy);
Chris Lattner75c29a02010-10-12 17:47:42 +0000184 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000185 case Builtin::BI__sync_fetch_and_add:
186 case Builtin::BI__sync_fetch_and_sub:
187 case Builtin::BI__sync_fetch_and_or:
188 case Builtin::BI__sync_fetch_and_and:
189 case Builtin::BI__sync_fetch_and_xor:
190 case Builtin::BI__sync_add_and_fetch:
191 case Builtin::BI__sync_sub_and_fetch:
192 case Builtin::BI__sync_and_and_fetch:
193 case Builtin::BI__sync_or_and_fetch:
194 case Builtin::BI__sync_xor_and_fetch:
195 case Builtin::BI__sync_val_compare_and_swap:
196 case Builtin::BI__sync_bool_compare_and_swap:
197 case Builtin::BI__sync_lock_test_and_set:
198 case Builtin::BI__sync_lock_release:
Chris Lattner23aa9c82011-04-09 03:57:26 +0000199 case Builtin::BI__sync_swap:
Chandler Carruthd2014572010-07-09 18:59:35 +0000200 return SemaBuiltinAtomicOverloaded(move(TheCallResult));
Eli Friedman276b0612011-10-11 02:20:01 +0000201 case Builtin::BI__atomic_load:
202 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Load);
203 case Builtin::BI__atomic_store:
204 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Store);
205 case Builtin::BI__atomic_exchange:
206 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xchg);
207 case Builtin::BI__atomic_compare_exchange_strong:
208 return SemaAtomicOpsOverloaded(move(TheCallResult),
209 AtomicExpr::CmpXchgStrong);
210 case Builtin::BI__atomic_compare_exchange_weak:
211 return SemaAtomicOpsOverloaded(move(TheCallResult),
212 AtomicExpr::CmpXchgWeak);
213 case Builtin::BI__atomic_fetch_add:
214 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Add);
215 case Builtin::BI__atomic_fetch_sub:
216 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Sub);
217 case Builtin::BI__atomic_fetch_and:
218 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::And);
219 case Builtin::BI__atomic_fetch_or:
220 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Or);
221 case Builtin::BI__atomic_fetch_xor:
222 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xor);
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000223 case Builtin::BI__builtin_annotation:
224 if (CheckBuiltinAnnotationString(*this, TheCall->getArg(1)))
225 return ExprError();
226 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000227 }
228
229 // Since the target specific builtins for each arch overlap, only check those
230 // of the arch we are compiling for.
231 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000232 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman26a31422010-06-08 02:47:44 +0000233 case llvm::Triple::arm:
234 case llvm::Triple::thumb:
235 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
236 return ExprError();
237 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000238 default:
239 break;
240 }
241 }
242
243 return move(TheCallResult);
244}
245
Nate Begeman61eecf52010-06-14 05:21:25 +0000246// Get the valid immediate range for the specified NEON type code.
247static unsigned RFT(unsigned t, bool shift = false) {
248 bool quad = t & 0x10;
249
250 switch (t & 0x7) {
251 case 0: // i8
Nate Begemand69ec162010-06-17 02:26:59 +0000252 return shift ? 7 : (8 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000253 case 1: // i16
Nate Begemand69ec162010-06-17 02:26:59 +0000254 return shift ? 15 : (4 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000255 case 2: // i32
Nate Begemand69ec162010-06-17 02:26:59 +0000256 return shift ? 31 : (2 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000257 case 3: // i64
Nate Begemand69ec162010-06-17 02:26:59 +0000258 return shift ? 63 : (1 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000259 case 4: // f32
260 assert(!shift && "cannot shift float types!");
Nate Begemand69ec162010-06-17 02:26:59 +0000261 return (2 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000262 case 5: // poly8
Bob Wilson42499f92010-12-10 19:45:06 +0000263 return shift ? 7 : (8 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000264 case 6: // poly16
Bob Wilson42499f92010-12-10 19:45:06 +0000265 return shift ? 15 : (4 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000266 case 7: // float16
267 assert(!shift && "cannot shift float types!");
Nate Begemand69ec162010-06-17 02:26:59 +0000268 return (4 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000269 }
270 return 0;
271}
272
Nate Begeman26a31422010-06-08 02:47:44 +0000273bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000274 llvm::APSInt Result;
275
Nate Begeman0d15c532010-06-13 04:47:52 +0000276 unsigned mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000277 unsigned TV = 0;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000278 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000279#define GET_NEON_OVERLOAD_CHECK
280#include "clang/Basic/arm_neon.inc"
281#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000282 }
283
Nate Begeman0d15c532010-06-13 04:47:52 +0000284 // For NEON intrinsics which are overloaded on vector element type, validate
285 // the immediate which specifies which variant to emit.
286 if (mask) {
287 unsigned ArgNo = TheCall->getNumArgs()-1;
288 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
289 return true;
290
Nate Begeman61eecf52010-06-14 05:21:25 +0000291 TV = Result.getLimitedValue(32);
292 if ((TV > 31) || (mask & (1 << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000293 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
294 << TheCall->getArg(ArgNo)->getSourceRange();
295 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000296
Nate Begeman0d15c532010-06-13 04:47:52 +0000297 // For NEON intrinsics which take an immediate value as part of the
298 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000299 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000300 switch (BuiltinID) {
301 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000302 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
303 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000304 case ARM::BI__builtin_arm_vcvtr_f:
305 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000306#define GET_NEON_IMMEDIATE_CHECK
307#include "clang/Basic/arm_neon.inc"
308#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000309 };
310
Nate Begeman61eecf52010-06-14 05:21:25 +0000311 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000312 if (SemaBuiltinConstantArg(TheCall, i, Result))
313 return true;
314
Nate Begeman61eecf52010-06-14 05:21:25 +0000315 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000316 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000317 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000318 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000319 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000320
Nate Begeman99c40bb2010-08-03 21:32:34 +0000321 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000322 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000323}
Daniel Dunbarde454282008-10-02 18:44:07 +0000324
Anders Carlssond406bf02009-08-16 01:56:34 +0000325/// CheckFunctionCall - Check a direct function call for various correctness
326/// and safety properties not strictly enforced by the C type system.
327bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
328 // Get the IdentifierInfo* for the called function.
329 IdentifierInfo *FnInfo = FDecl->getIdentifier();
330
331 // None of the checks below are needed for functions that don't have
332 // simple names (e.g., C++ conversion functions).
333 if (!FnInfo)
334 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000335
Daniel Dunbarde454282008-10-02 18:44:07 +0000336 // FIXME: This mechanism should be abstracted to be less fragile and
337 // more efficient. For example, just map function ids to custom
338 // handlers.
339
Ted Kremenekc82faca2010-09-09 04:33:05 +0000340 // Printf and scanf checking.
341 for (specific_attr_iterator<FormatAttr>
342 i = FDecl->specific_attr_begin<FormatAttr>(),
343 e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
344
345 const FormatAttr *Format = *i;
Ted Kremenek826a3452010-07-16 02:11:22 +0000346 const bool b = Format->getType() == "scanf";
347 if (b || CheckablePrintfAttr(Format, TheCall)) {
Ted Kremenek3d692df2009-02-27 17:58:43 +0000348 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek826a3452010-07-16 02:11:22 +0000349 CheckPrintfScanfArguments(TheCall, HasVAListArg,
350 Format->getFormatIdx() - 1,
351 HasVAListArg ? 0 : Format->getFirstArg() - 1,
352 !b);
Douglas Gregor3c385e52009-02-14 18:57:46 +0000353 }
Chris Lattner59907c42007-08-10 20:18:51 +0000354 }
Mike Stump1eb44332009-09-09 15:08:12 +0000355
Ted Kremenekc82faca2010-09-09 04:33:05 +0000356 for (specific_attr_iterator<NonNullAttr>
357 i = FDecl->specific_attr_begin<NonNullAttr>(),
358 e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +0000359 CheckNonNullArguments(*i, TheCall->getArgs(),
360 TheCall->getCallee()->getLocStart());
Ted Kremenekc82faca2010-09-09 04:33:05 +0000361 }
Sebastian Redl0eb23302009-01-19 00:08:26 +0000362
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000363 // Builtin handling
Douglas Gregor707a23e2011-06-16 17:56:04 +0000364 int CMF = -1;
365 switch (FDecl->getBuiltinID()) {
366 case Builtin::BI__builtin_memset:
367 case Builtin::BI__builtin___memset_chk:
368 case Builtin::BImemset:
369 CMF = CMF_Memset;
370 break;
371
372 case Builtin::BI__builtin_memcpy:
373 case Builtin::BI__builtin___memcpy_chk:
374 case Builtin::BImemcpy:
375 CMF = CMF_Memcpy;
376 break;
377
378 case Builtin::BI__builtin_memmove:
379 case Builtin::BI__builtin___memmove_chk:
380 case Builtin::BImemmove:
381 CMF = CMF_Memmove;
382 break;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000383
384 case Builtin::BIstrlcpy:
385 case Builtin::BIstrlcat:
386 CheckStrlcpycatArguments(TheCall, FnInfo);
387 break;
Douglas Gregor707a23e2011-06-16 17:56:04 +0000388
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +0000389 case Builtin::BI__builtin_memcmp:
390 CMF = CMF_Memcmp;
391 break;
392
Douglas Gregor707a23e2011-06-16 17:56:04 +0000393 default:
394 if (FDecl->getLinkage() == ExternalLinkage &&
395 (!getLangOptions().CPlusPlus || FDecl->isExternC())) {
396 if (FnInfo->isStr("memset"))
397 CMF = CMF_Memset;
398 else if (FnInfo->isStr("memcpy"))
399 CMF = CMF_Memcpy;
400 else if (FnInfo->isStr("memmove"))
401 CMF = CMF_Memmove;
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +0000402 else if (FnInfo->isStr("memcmp"))
403 CMF = CMF_Memcmp;
Douglas Gregor707a23e2011-06-16 17:56:04 +0000404 }
405 break;
Douglas Gregor06bc9eb2011-05-03 20:37:33 +0000406 }
Douglas Gregor707a23e2011-06-16 17:56:04 +0000407
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000408 // Memset/memcpy/memmove handling
Douglas Gregor707a23e2011-06-16 17:56:04 +0000409 if (CMF != -1)
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +0000410 CheckMemaccessArguments(TheCall, CheckedMemoryFunction(CMF), FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000411
Anders Carlssond406bf02009-08-16 01:56:34 +0000412 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000413}
414
Anders Carlssond406bf02009-08-16 01:56:34 +0000415bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000416 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000417 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000418 if (!Format)
Anders Carlssond406bf02009-08-16 01:56:34 +0000419 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000420
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000421 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
422 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000423 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000424
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000425 QualType Ty = V->getType();
426 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000427 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000428
Ted Kremenek826a3452010-07-16 02:11:22 +0000429 const bool b = Format->getType() == "scanf";
430 if (!b && !CheckablePrintfAttr(Format, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +0000431 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000432
Anders Carlssond406bf02009-08-16 01:56:34 +0000433 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek826a3452010-07-16 02:11:22 +0000434 CheckPrintfScanfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
435 HasVAListArg ? 0 : Format->getFirstArg() - 1, !b);
Anders Carlssond406bf02009-08-16 01:56:34 +0000436
437 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000438}
439
Eli Friedman276b0612011-10-11 02:20:01 +0000440ExprResult
441Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::AtomicOp Op) {
442 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
443 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
444 Expr *Ptr, *Order, *Val1, *Val2, *OrderFail;
445
446 // All these operations take one of the following four forms:
447 // T __atomic_load(_Atomic(T)*, int) (loads)
448 // T* __atomic_add(_Atomic(T*)*, ptrdiff_t, int) (pointer add/sub)
449 // int __atomic_compare_exchange_strong(_Atomic(T)*, T*, T, int, int)
450 // (cmpxchg)
451 // T __atomic_exchange(_Atomic(T)*, T, int) (everything else)
452 // where T is an appropriate type, and the int paremeterss are for orderings.
453 unsigned NumVals = 1;
454 unsigned NumOrders = 1;
455 if (Op == AtomicExpr::Load) {
456 NumVals = 0;
457 } else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong) {
458 NumVals = 2;
459 NumOrders = 2;
460 }
461
462 if (TheCall->getNumArgs() < NumVals+NumOrders+1) {
463 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
464 << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
465 << TheCall->getCallee()->getSourceRange();
466 return ExprError();
467 } else if (TheCall->getNumArgs() > NumVals+NumOrders+1) {
468 Diag(TheCall->getArg(NumVals+NumOrders+1)->getLocStart(),
469 diag::err_typecheck_call_too_many_args)
470 << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
471 << TheCall->getCallee()->getSourceRange();
472 return ExprError();
473 }
474
475 // Inspect the first argument of the atomic operation. This should always be
476 // a pointer to an _Atomic type.
477 Ptr = TheCall->getArg(0);
478 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
479 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
480 if (!pointerType) {
481 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
482 << Ptr->getType() << Ptr->getSourceRange();
483 return ExprError();
484 }
485
486 QualType AtomTy = pointerType->getPointeeType();
487 if (!AtomTy->isAtomicType()) {
488 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
489 << Ptr->getType() << Ptr->getSourceRange();
490 return ExprError();
491 }
492 QualType ValType = AtomTy->getAs<AtomicType>()->getValueType();
493
494 if ((Op == AtomicExpr::Add || Op == AtomicExpr::Sub) &&
495 !ValType->isIntegerType() && !ValType->isPointerType()) {
496 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
497 << Ptr->getType() << Ptr->getSourceRange();
498 return ExprError();
499 }
500
501 if (!ValType->isIntegerType() &&
502 (Op == AtomicExpr::And || Op == AtomicExpr::Or || Op == AtomicExpr::Xor)){
503 Diag(DRE->getLocStart(), diag::err_atomic_op_logical_needs_atomic_int)
504 << Ptr->getType() << Ptr->getSourceRange();
505 return ExprError();
506 }
507
508 switch (ValType.getObjCLifetime()) {
509 case Qualifiers::OCL_None:
510 case Qualifiers::OCL_ExplicitNone:
511 // okay
512 break;
513
514 case Qualifiers::OCL_Weak:
515 case Qualifiers::OCL_Strong:
516 case Qualifiers::OCL_Autoreleasing:
517 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
518 << ValType << Ptr->getSourceRange();
519 return ExprError();
520 }
521
522 QualType ResultType = ValType;
523 if (Op == AtomicExpr::Store)
524 ResultType = Context.VoidTy;
525 else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong)
526 ResultType = Context.BoolTy;
527
528 // The first argument --- the pointer --- has a fixed type; we
529 // deduce the types of the rest of the arguments accordingly. Walk
530 // the remaining arguments, converting them to the deduced value type.
531 for (unsigned i = 1; i != NumVals+NumOrders+1; ++i) {
532 ExprResult Arg = TheCall->getArg(i);
533 QualType Ty;
534 if (i < NumVals+1) {
535 // The second argument to a cmpxchg is a pointer to the data which will
536 // be exchanged. The second argument to a pointer add/subtract is the
537 // amount to add/subtract, which must be a ptrdiff_t. The third
538 // argument to a cmpxchg and the second argument in all other cases
539 // is the type of the value.
540 if (i == 1 && (Op == AtomicExpr::CmpXchgWeak ||
541 Op == AtomicExpr::CmpXchgStrong))
542 Ty = Context.getPointerType(ValType.getUnqualifiedType());
543 else if (!ValType->isIntegerType() &&
544 (Op == AtomicExpr::Add || Op == AtomicExpr::Sub))
545 Ty = Context.getPointerDiffType();
546 else
547 Ty = ValType;
548 } else {
549 // The order(s) are always converted to int.
550 Ty = Context.IntTy;
551 }
552 InitializedEntity Entity =
553 InitializedEntity::InitializeParameter(Context, Ty, false);
554 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
555 if (Arg.isInvalid())
556 return true;
557 TheCall->setArg(i, Arg.get());
558 }
559
560 if (Op == AtomicExpr::Load) {
561 Order = TheCall->getArg(1);
562 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
563 Ptr, Order, ResultType, Op,
564 TheCall->getRParenLoc(), false,
565 false));
566 } else if (Op != AtomicExpr::CmpXchgWeak && Op != AtomicExpr::CmpXchgStrong) {
567 Val1 = TheCall->getArg(1);
568 Order = TheCall->getArg(2);
569 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
570 Ptr, Val1, Order, ResultType, Op,
571 TheCall->getRParenLoc(), false,
572 false));
573 } else {
574 Val1 = TheCall->getArg(1);
575 Val2 = TheCall->getArg(2);
576 Order = TheCall->getArg(3);
577 OrderFail = TheCall->getArg(4);
578 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
579 Ptr, Val1, Val2, Order, OrderFail,
580 ResultType, Op,
581 TheCall->getRParenLoc(), false,
582 false));
583 }
584}
585
586
John McCall5f8d6042011-08-27 01:09:30 +0000587/// checkBuiltinArgument - Given a call to a builtin function, perform
588/// normal type-checking on the given argument, updating the call in
589/// place. This is useful when a builtin function requires custom
590/// type-checking for some of its arguments but not necessarily all of
591/// them.
592///
593/// Returns true on error.
594static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
595 FunctionDecl *Fn = E->getDirectCallee();
596 assert(Fn && "builtin call without direct callee!");
597
598 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
599 InitializedEntity Entity =
600 InitializedEntity::InitializeParameter(S.Context, Param);
601
602 ExprResult Arg = E->getArg(0);
603 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
604 if (Arg.isInvalid())
605 return true;
606
607 E->setArg(ArgIndex, Arg.take());
608 return false;
609}
610
Chris Lattner5caa3702009-05-08 06:58:22 +0000611/// SemaBuiltinAtomicOverloaded - We have a call to a function like
612/// __sync_fetch_and_add, which is an overloaded function based on the pointer
613/// type of its first argument. The main ActOnCallExpr routines have already
614/// promoted the types of arguments because all of these calls are prototyped as
615/// void(...).
616///
617/// This function goes through and does final semantic checking for these
618/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000619ExprResult
620Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000621 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000622 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
623 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
624
625 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000626 if (TheCall->getNumArgs() < 1) {
627 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
628 << 0 << 1 << TheCall->getNumArgs()
629 << TheCall->getCallee()->getSourceRange();
630 return ExprError();
631 }
Mike Stump1eb44332009-09-09 15:08:12 +0000632
Chris Lattner5caa3702009-05-08 06:58:22 +0000633 // Inspect the first argument of the atomic builtin. This should always be
634 // a pointer type, whose element is an integral scalar or pointer type.
635 // Because it is a pointer type, we don't have to worry about any implicit
636 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000637 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000638 Expr *FirstArg = TheCall->getArg(0);
John McCallf85e1932011-06-15 23:02:42 +0000639 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
640 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000641 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
642 << FirstArg->getType() << FirstArg->getSourceRange();
643 return ExprError();
644 }
Mike Stump1eb44332009-09-09 15:08:12 +0000645
John McCallf85e1932011-06-15 23:02:42 +0000646 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000647 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000648 !ValType->isBlockPointerType()) {
649 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
650 << FirstArg->getType() << FirstArg->getSourceRange();
651 return ExprError();
652 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000653
John McCallf85e1932011-06-15 23:02:42 +0000654 switch (ValType.getObjCLifetime()) {
655 case Qualifiers::OCL_None:
656 case Qualifiers::OCL_ExplicitNone:
657 // okay
658 break;
659
660 case Qualifiers::OCL_Weak:
661 case Qualifiers::OCL_Strong:
662 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000663 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +0000664 << ValType << FirstArg->getSourceRange();
665 return ExprError();
666 }
667
John McCallb45ae252011-10-05 07:41:44 +0000668 // Strip any qualifiers off ValType.
669 ValType = ValType.getUnqualifiedType();
670
Chandler Carruth8d13d222010-07-18 20:54:12 +0000671 // The majority of builtins return a value, but a few have special return
672 // types, so allow them to override appropriately below.
673 QualType ResultType = ValType;
674
Chris Lattner5caa3702009-05-08 06:58:22 +0000675 // We need to figure out which concrete builtin this maps onto. For example,
676 // __sync_fetch_and_add with a 2 byte object turns into
677 // __sync_fetch_and_add_2.
678#define BUILTIN_ROW(x) \
679 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
680 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000681
Chris Lattner5caa3702009-05-08 06:58:22 +0000682 static const unsigned BuiltinIndices[][5] = {
683 BUILTIN_ROW(__sync_fetch_and_add),
684 BUILTIN_ROW(__sync_fetch_and_sub),
685 BUILTIN_ROW(__sync_fetch_and_or),
686 BUILTIN_ROW(__sync_fetch_and_and),
687 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +0000688
Chris Lattner5caa3702009-05-08 06:58:22 +0000689 BUILTIN_ROW(__sync_add_and_fetch),
690 BUILTIN_ROW(__sync_sub_and_fetch),
691 BUILTIN_ROW(__sync_and_and_fetch),
692 BUILTIN_ROW(__sync_or_and_fetch),
693 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000694
Chris Lattner5caa3702009-05-08 06:58:22 +0000695 BUILTIN_ROW(__sync_val_compare_and_swap),
696 BUILTIN_ROW(__sync_bool_compare_and_swap),
697 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +0000698 BUILTIN_ROW(__sync_lock_release),
699 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +0000700 };
Mike Stump1eb44332009-09-09 15:08:12 +0000701#undef BUILTIN_ROW
702
Chris Lattner5caa3702009-05-08 06:58:22 +0000703 // Determine the index of the size.
704 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000705 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000706 case 1: SizeIndex = 0; break;
707 case 2: SizeIndex = 1; break;
708 case 4: SizeIndex = 2; break;
709 case 8: SizeIndex = 3; break;
710 case 16: SizeIndex = 4; break;
711 default:
Chandler Carruthd2014572010-07-09 18:59:35 +0000712 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
713 << FirstArg->getType() << FirstArg->getSourceRange();
714 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +0000715 }
Mike Stump1eb44332009-09-09 15:08:12 +0000716
Chris Lattner5caa3702009-05-08 06:58:22 +0000717 // Each of these builtins has one pointer argument, followed by some number of
718 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
719 // that we ignore. Find out which row of BuiltinIndices to read from as well
720 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000721 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000722 unsigned BuiltinIndex, NumFixed = 1;
723 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000724 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Chris Lattner5caa3702009-05-08 06:58:22 +0000725 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
726 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
727 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
728 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
729 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000730
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000731 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
732 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
733 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
734 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 8; break;
735 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000736
Chris Lattner5caa3702009-05-08 06:58:22 +0000737 case Builtin::BI__sync_val_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000738 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +0000739 NumFixed = 2;
740 break;
741 case Builtin::BI__sync_bool_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000742 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +0000743 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000744 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000745 break;
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000746 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000747 case Builtin::BI__sync_lock_release:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000748 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000749 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000750 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000751 break;
Chris Lattner23aa9c82011-04-09 03:57:26 +0000752 case Builtin::BI__sync_swap: BuiltinIndex = 14; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000753 }
Mike Stump1eb44332009-09-09 15:08:12 +0000754
Chris Lattner5caa3702009-05-08 06:58:22 +0000755 // Now that we know how many fixed arguments we expect, first check that we
756 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +0000757 if (TheCall->getNumArgs() < 1+NumFixed) {
758 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
759 << 0 << 1+NumFixed << TheCall->getNumArgs()
760 << TheCall->getCallee()->getSourceRange();
761 return ExprError();
762 }
Mike Stump1eb44332009-09-09 15:08:12 +0000763
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000764 // Get the decl for the concrete builtin from this, we can tell what the
765 // concrete integer type we should convert to is.
766 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
767 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
768 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +0000769 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000770 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
771 TUScope, false, DRE->getLocStart()));
Chandler Carruthd2014572010-07-09 18:59:35 +0000772
John McCallf871d0c2010-08-07 06:22:56 +0000773 // The first argument --- the pointer --- has a fixed type; we
774 // deduce the types of the rest of the arguments accordingly. Walk
775 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +0000776 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +0000777 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +0000778
Chris Lattner5caa3702009-05-08 06:58:22 +0000779 // If the argument is an implicit cast, then there was a promotion due to
780 // "...", just remove it now.
John Wiegley429bb272011-04-08 18:41:53 +0000781 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg.get())) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000782 Arg = ICE->getSubExpr();
783 ICE->setSubExpr(0);
John Wiegley429bb272011-04-08 18:41:53 +0000784 TheCall->setArg(i+1, Arg.get());
Chris Lattner5caa3702009-05-08 06:58:22 +0000785 }
Mike Stump1eb44332009-09-09 15:08:12 +0000786
Chris Lattner5caa3702009-05-08 06:58:22 +0000787 // GCC does an implicit conversion to the pointer or integer ValType. This
788 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +0000789 // Initialize the argument.
790 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
791 ValType, /*consume*/ false);
792 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +0000793 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +0000794 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000795
Chris Lattner5caa3702009-05-08 06:58:22 +0000796 // Okay, we have something that *can* be converted to the right type. Check
797 // to see if there is a potentially weird extension going on here. This can
798 // happen when you do an atomic operation on something like an char* and
799 // pass in 42. The 42 gets converted to char. This is even more strange
800 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +0000801 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +0000802 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +0000803 }
Mike Stump1eb44332009-09-09 15:08:12 +0000804
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +0000805 ASTContext& Context = this->getASTContext();
806
807 // Create a new DeclRefExpr to refer to the new decl.
808 DeclRefExpr* NewDRE = DeclRefExpr::Create(
809 Context,
810 DRE->getQualifierLoc(),
811 NewBuiltinDecl,
812 DRE->getLocation(),
813 NewBuiltinDecl->getType(),
814 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +0000815
Chris Lattner5caa3702009-05-08 06:58:22 +0000816 // Set the callee in the CallExpr.
817 // FIXME: This leaks the original parens and implicit casts.
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +0000818 ExprResult PromotedCall = UsualUnaryConversions(NewDRE);
John Wiegley429bb272011-04-08 18:41:53 +0000819 if (PromotedCall.isInvalid())
820 return ExprError();
821 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +0000822
Chandler Carruthdb4325b2010-07-18 07:23:17 +0000823 // Change the result type of the call to match the original value type. This
824 // is arbitrary, but the codegen for these builtins ins design to handle it
825 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +0000826 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +0000827
828 return move(TheCallResult);
Chris Lattner5caa3702009-05-08 06:58:22 +0000829}
830
Chris Lattner69039812009-02-18 06:01:06 +0000831/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000832/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +0000833/// Note: It might also make sense to do the UTF-16 conversion here (would
834/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +0000835bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000836 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000837 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
838
Douglas Gregor5cee1192011-07-27 05:40:30 +0000839 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000840 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
841 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000842 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000843 }
Mike Stump1eb44332009-09-09 15:08:12 +0000844
Fariborz Jahanian7da71022010-09-07 19:38:13 +0000845 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000846 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +0000847 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000848 SmallVector<UTF16, 128> ToBuf(NumBytes);
Fariborz Jahanian7da71022010-09-07 19:38:13 +0000849 const UTF8 *FromPtr = (UTF8 *)String.data();
850 UTF16 *ToPtr = &ToBuf[0];
851
852 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
853 &ToPtr, ToPtr + NumBytes,
854 strictConversion);
855 // Check for conversion failure.
856 if (Result != conversionOK)
857 Diag(Arg->getLocStart(),
858 diag::warn_cfstring_truncated) << Arg->getSourceRange();
859 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000860 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000861}
862
Chris Lattnerc27c6652007-12-20 00:05:45 +0000863/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
864/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000865bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
866 Expr *Fn = TheCall->getCallee();
867 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000868 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000869 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000870 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
871 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +0000872 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000873 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000874 return true;
875 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000876
877 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +0000878 return Diag(TheCall->getLocEnd(),
879 diag::err_typecheck_call_too_few_args_at_least)
880 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000881 }
882
John McCall5f8d6042011-08-27 01:09:30 +0000883 // Type-check the first argument normally.
884 if (checkBuiltinArgument(*this, TheCall, 0))
885 return true;
886
Chris Lattnerc27c6652007-12-20 00:05:45 +0000887 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000888 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +0000889 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000890 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +0000891 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +0000892 else if (FunctionDecl *FD = getCurFunctionDecl())
893 isVariadic = FD->isVariadic();
894 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000895 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +0000896
Chris Lattnerc27c6652007-12-20 00:05:45 +0000897 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000898 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
899 return true;
900 }
Mike Stump1eb44332009-09-09 15:08:12 +0000901
Chris Lattner30ce3442007-12-19 23:59:04 +0000902 // Verify that the second argument to the builtin is the last argument of the
903 // current function or method.
904 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000905 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +0000906
Anders Carlsson88cf2262008-02-11 04:20:54 +0000907 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
908 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000909 // FIXME: This isn't correct for methods (results in bogus warning).
910 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000911 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000912 if (CurBlock)
913 LastArg = *(CurBlock->TheDecl->param_end()-1);
914 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +0000915 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000916 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000917 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000918 SecondArgIsLastNamedArgument = PV == LastArg;
919 }
920 }
Mike Stump1eb44332009-09-09 15:08:12 +0000921
Chris Lattner30ce3442007-12-19 23:59:04 +0000922 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +0000923 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000924 diag::warn_second_parameter_of_va_start_not_last_named_argument);
925 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000926}
Chris Lattner30ce3442007-12-19 23:59:04 +0000927
Chris Lattner1b9a0792007-12-20 00:26:33 +0000928/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
929/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000930bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
931 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000932 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000933 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000934 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +0000935 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000936 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000937 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000938 << SourceRange(TheCall->getArg(2)->getLocStart(),
939 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000940
John Wiegley429bb272011-04-08 18:41:53 +0000941 ExprResult OrigArg0 = TheCall->getArg(0);
942 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000943
Chris Lattner1b9a0792007-12-20 00:26:33 +0000944 // Do standard promotions between the two arguments, returning their common
945 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000946 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +0000947 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
948 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +0000949
950 // Make sure any conversions are pushed back into the call; this is
951 // type safe since unordered compare builtins are declared as "_Bool
952 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +0000953 TheCall->setArg(0, OrigArg0.get());
954 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +0000955
John Wiegley429bb272011-04-08 18:41:53 +0000956 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +0000957 return false;
958
Chris Lattner1b9a0792007-12-20 00:26:33 +0000959 // If the common type isn't a real floating type, then the arguments were
960 // invalid for this operation.
961 if (!Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +0000962 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000963 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +0000964 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
965 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000966
Chris Lattner1b9a0792007-12-20 00:26:33 +0000967 return false;
968}
969
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000970/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
971/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000972/// to check everything. We expect the last argument to be a floating point
973/// value.
974bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
975 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +0000976 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000977 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000978 if (TheCall->getNumArgs() > NumArgs)
979 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000980 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000981 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000982 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000983 (*(TheCall->arg_end()-1))->getLocEnd());
984
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000985 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +0000986
Eli Friedman9ac6f622009-08-31 20:06:00 +0000987 if (OrigArg->isTypeDependent())
988 return false;
989
Chris Lattner81368fb2010-05-06 05:50:07 +0000990 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +0000991 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000992 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000993 diag::err_typecheck_call_invalid_unary_fp)
994 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000995
Chris Lattner81368fb2010-05-06 05:50:07 +0000996 // If this is an implicit conversion from float -> double, remove it.
997 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
998 Expr *CastArg = Cast->getSubExpr();
999 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1000 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1001 "promotion from float to double is the only expected cast here");
1002 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001003 TheCall->setArg(NumArgs-1, CastArg);
1004 OrigArg = CastArg;
1005 }
1006 }
1007
Eli Friedman9ac6f622009-08-31 20:06:00 +00001008 return false;
1009}
1010
Eli Friedmand38617c2008-05-14 19:38:39 +00001011/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1012// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001013ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001014 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001015 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001016 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +00001017 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +00001018 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001019
Nate Begeman37b6a572010-06-08 00:16:34 +00001020 // Determine which of the following types of shufflevector we're checking:
1021 // 1) unary, vector mask: (lhs, mask)
1022 // 2) binary, vector mask: (lhs, rhs, mask)
1023 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1024 QualType resType = TheCall->getArg(0)->getType();
1025 unsigned numElements = 0;
1026
Douglas Gregorcde01732009-05-19 22:10:17 +00001027 if (!TheCall->getArg(0)->isTypeDependent() &&
1028 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001029 QualType LHSType = TheCall->getArg(0)->getType();
1030 QualType RHSType = TheCall->getArg(1)->getType();
1031
1032 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001033 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001034 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001035 TheCall->getArg(1)->getLocEnd());
1036 return ExprError();
1037 }
Nate Begeman37b6a572010-06-08 00:16:34 +00001038
1039 numElements = LHSType->getAs<VectorType>()->getNumElements();
1040 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001041
Nate Begeman37b6a572010-06-08 00:16:34 +00001042 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1043 // with mask. If so, verify that RHS is an integer vector type with the
1044 // same number of elts as lhs.
1045 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001046 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001047 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1048 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1049 << SourceRange(TheCall->getArg(1)->getLocStart(),
1050 TheCall->getArg(1)->getLocEnd());
1051 numResElements = numElements;
1052 }
1053 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001054 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001055 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001056 TheCall->getArg(1)->getLocEnd());
1057 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +00001058 } else if (numElements != numResElements) {
1059 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001060 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001061 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001062 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001063 }
1064
1065 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001066 if (TheCall->getArg(i)->isTypeDependent() ||
1067 TheCall->getArg(i)->isValueDependent())
1068 continue;
1069
Nate Begeman37b6a572010-06-08 00:16:34 +00001070 llvm::APSInt Result(32);
1071 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1072 return ExprError(Diag(TheCall->getLocStart(),
1073 diag::err_shufflevector_nonconstant_argument)
1074 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001075
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001076 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001077 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001078 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001079 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001080 }
1081
Chris Lattner5f9e2722011-07-23 10:55:15 +00001082 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001083
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001084 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001085 exprs.push_back(TheCall->getArg(i));
1086 TheCall->setArg(i, 0);
1087 }
1088
Nate Begemana88dc302009-08-12 02:10:25 +00001089 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begeman37b6a572010-06-08 00:16:34 +00001090 exprs.size(), resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001091 TheCall->getCallee()->getLocStart(),
1092 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001093}
Chris Lattner30ce3442007-12-19 23:59:04 +00001094
Daniel Dunbar4493f792008-07-21 22:59:13 +00001095/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1096// This is declared to take (const void*, ...) and can take two
1097// optional constant int args.
1098bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001099 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001100
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001101 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001102 return Diag(TheCall->getLocEnd(),
1103 diag::err_typecheck_call_too_many_args_at_most)
1104 << 0 /*function call*/ << 3 << NumArgs
1105 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001106
1107 // Argument 0 is checked for us and the remaining arguments must be
1108 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001109 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001110 Expr *Arg = TheCall->getArg(i);
Eric Christopher691ebc32010-04-17 02:26:23 +00001111
Eli Friedman9aef7262009-12-04 00:30:06 +00001112 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001113 if (SemaBuiltinConstantArg(TheCall, i, Result))
1114 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001115
Daniel Dunbar4493f792008-07-21 22:59:13 +00001116 // FIXME: gcc issues a warning and rewrites these to 0. These
1117 // seems especially odd for the third argument since the default
1118 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001119 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001120 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001121 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001122 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001123 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001124 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001125 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001126 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001127 }
1128 }
1129
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001130 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001131}
1132
Eric Christopher691ebc32010-04-17 02:26:23 +00001133/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1134/// TheCall is a constant expression.
1135bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1136 llvm::APSInt &Result) {
1137 Expr *Arg = TheCall->getArg(ArgNum);
1138 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1139 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1140
1141 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1142
1143 if (!Arg->isIntegerConstantExpr(Result, Context))
1144 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001145 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001146
Chris Lattner21fb98e2009-09-23 06:06:36 +00001147 return false;
1148}
1149
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001150/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1151/// int type). This simply type checks that type is one of the defined
1152/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001153// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001154bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001155 llvm::APSInt Result;
1156
1157 // Check constant-ness first.
1158 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1159 return true;
1160
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001161 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001162 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001163 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1164 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001165 }
1166
1167 return false;
1168}
1169
Eli Friedman586d6a82009-05-03 06:04:26 +00001170/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001171/// This checks that val is a constant 1.
1172bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1173 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001174 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001175
Eric Christopher691ebc32010-04-17 02:26:23 +00001176 // TODO: This is less than ideal. Overload this to take a value.
1177 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1178 return true;
1179
1180 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001181 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1182 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1183
1184 return false;
1185}
1186
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001187// Handle i > 1 ? "x" : "y", recursively.
Ted Kremenek082d9362009-03-20 21:35:28 +00001188bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
1189 bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001190 unsigned format_idx, unsigned firstDataArg,
1191 bool isPrintf) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001192 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001193 if (E->isTypeDependent() || E->isValueDependent())
1194 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001195
Peter Collingbournef111d932011-04-15 00:35:48 +00001196 E = E->IgnoreParens();
1197
Ted Kremenekd30ef872009-01-12 23:09:09 +00001198 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001199 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001200 case Stmt::ConditionalOperatorClass: {
John McCall56ca35d2011-02-17 10:25:35 +00001201 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
Ted Kremenek826a3452010-07-16 02:11:22 +00001202 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg,
1203 format_idx, firstDataArg, isPrintf)
John McCall56ca35d2011-02-17 10:25:35 +00001204 && SemaCheckStringLiteral(C->getFalseExpr(), TheCall, HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001205 format_idx, firstDataArg, isPrintf);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001206 }
1207
Ted Kremenek95355bb2010-09-09 03:51:42 +00001208 case Stmt::IntegerLiteralClass:
1209 // Technically -Wformat-nonliteral does not warn about this case.
1210 // The behavior of printf and friends in this case is implementation
1211 // dependent. Ideally if the format string cannot be null then
1212 // it should have a 'nonnull' attribute in the function prototype.
1213 return true;
1214
Ted Kremenekd30ef872009-01-12 23:09:09 +00001215 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001216 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1217 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001218 }
1219
John McCall56ca35d2011-02-17 10:25:35 +00001220 case Stmt::OpaqueValueExprClass:
1221 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1222 E = src;
1223 goto tryAgain;
1224 }
1225 return false;
1226
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001227 case Stmt::PredefinedExprClass:
1228 // While __func__, etc., are technically not string literals, they
1229 // cannot contain format specifiers and thus are not a security
1230 // liability.
1231 return true;
1232
Ted Kremenek082d9362009-03-20 21:35:28 +00001233 case Stmt::DeclRefExprClass: {
1234 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001235
Ted Kremenek082d9362009-03-20 21:35:28 +00001236 // As an exception, do not flag errors for variables binding to
1237 // const string literals.
1238 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1239 bool isConstant = false;
1240 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001241
Ted Kremenek082d9362009-03-20 21:35:28 +00001242 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1243 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001244 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001245 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001246 PT->getPointeeType().isConstant(Context);
1247 }
Mike Stump1eb44332009-09-09 15:08:12 +00001248
Ted Kremenek082d9362009-03-20 21:35:28 +00001249 if (isConstant) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001250 if (const Expr *Init = VD->getAnyInitializer())
Ted Kremenek082d9362009-03-20 21:35:28 +00001251 return SemaCheckStringLiteral(Init, TheCall,
Ted Kremenek826a3452010-07-16 02:11:22 +00001252 HasVAListArg, format_idx, firstDataArg,
1253 isPrintf);
Ted Kremenek082d9362009-03-20 21:35:28 +00001254 }
Mike Stump1eb44332009-09-09 15:08:12 +00001255
Anders Carlssond966a552009-06-28 19:55:58 +00001256 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1257 // special check to see if the format string is a function parameter
1258 // of the function calling the printf function. If the function
1259 // has an attribute indicating it is a printf-like function, then we
1260 // should suppress warnings concerning non-literals being used in a call
1261 // to a vprintf function. For example:
1262 //
1263 // void
1264 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1265 // va_list ap;
1266 // va_start(ap, fmt);
1267 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1268 // ...
1269 //
1270 //
1271 // FIXME: We don't have full attribute support yet, so just check to see
1272 // if the argument is a DeclRefExpr that references a parameter. We'll
1273 // add proper support for checking the attribute later.
1274 if (HasVAListArg)
1275 if (isa<ParmVarDecl>(VD))
1276 return true;
Ted Kremenek082d9362009-03-20 21:35:28 +00001277 }
Mike Stump1eb44332009-09-09 15:08:12 +00001278
Ted Kremenek082d9362009-03-20 21:35:28 +00001279 return false;
1280 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001281
Anders Carlsson8f031b32009-06-27 04:05:33 +00001282 case Stmt::CallExprClass: {
1283 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001284 if (const ImplicitCastExpr *ICE
Anders Carlsson8f031b32009-06-27 04:05:33 +00001285 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
1286 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
1287 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001288 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001289 unsigned ArgIndex = FA->getFormatIdx();
1290 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001291
1292 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001293 format_idx, firstDataArg, isPrintf);
Anders Carlsson8f031b32009-06-27 04:05:33 +00001294 }
1295 }
1296 }
1297 }
Mike Stump1eb44332009-09-09 15:08:12 +00001298
Anders Carlsson8f031b32009-06-27 04:05:33 +00001299 return false;
1300 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001301 case Stmt::ObjCStringLiteralClass:
1302 case Stmt::StringLiteralClass: {
1303 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001304
Ted Kremenek082d9362009-03-20 21:35:28 +00001305 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001306 StrE = ObjCFExpr->getString();
1307 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001308 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001309
Ted Kremenekd30ef872009-01-12 23:09:09 +00001310 if (StrE) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001311 CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx,
1312 firstDataArg, isPrintf);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001313 return true;
1314 }
Mike Stump1eb44332009-09-09 15:08:12 +00001315
Ted Kremenekd30ef872009-01-12 23:09:09 +00001316 return false;
1317 }
Mike Stump1eb44332009-09-09 15:08:12 +00001318
Ted Kremenek082d9362009-03-20 21:35:28 +00001319 default:
1320 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001321 }
1322}
1323
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001324void
Mike Stump1eb44332009-09-09 15:08:12 +00001325Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001326 const Expr * const *ExprArgs,
1327 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001328 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1329 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001330 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001331 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001332 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001333 Expr::NPC_ValueDependentIsNotNull))
Nick Lewycky909a70d2011-03-25 01:44:32 +00001334 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001335 }
1336}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001337
Ted Kremenek826a3452010-07-16 02:11:22 +00001338/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1339/// functions) for correct use of format strings.
Chris Lattner59907c42007-08-10 20:18:51 +00001340void
Ted Kremenek826a3452010-07-16 02:11:22 +00001341Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
1342 unsigned format_idx, unsigned firstDataArg,
1343 bool isPrintf) {
1344
Ted Kremenek082d9362009-03-20 21:35:28 +00001345 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +00001346
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001347 // The way the format attribute works in GCC, the implicit this argument
1348 // of member functions is counted. However, it doesn't appear in our own
1349 // lists, so decrement format_idx in that case.
1350 if (isa<CXXMemberCallExpr>(TheCall)) {
Chandler Carruth9263a302010-11-16 08:49:43 +00001351 const CXXMethodDecl *method_decl =
1352 dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl());
1353 if (method_decl && method_decl->isInstance()) {
1354 // Catch a format attribute mistakenly referring to the object argument.
1355 if (format_idx == 0)
1356 return;
1357 --format_idx;
1358 if(firstDataArg != 0)
1359 --firstDataArg;
1360 }
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001361 }
1362
Ted Kremenek826a3452010-07-16 02:11:22 +00001363 // CHECK: printf/scanf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +00001364 if (format_idx >= TheCall->getNumArgs()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001365 Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001366 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001367 return;
1368 }
Mike Stump1eb44332009-09-09 15:08:12 +00001369
Ted Kremenek082d9362009-03-20 21:35:28 +00001370 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001371
Chris Lattner59907c42007-08-10 20:18:51 +00001372 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001373 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001374 // Dynamically generated format strings are difficult to
1375 // automatically vet at compile time. Requiring that format strings
1376 // are string literals: (1) permits the checking of format strings by
1377 // the compiler and thereby (2) can practically remove the source of
1378 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001379
Mike Stump1eb44332009-09-09 15:08:12 +00001380 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001381 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001382 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001383 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001384 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
Ted Kremenek826a3452010-07-16 02:11:22 +00001385 firstDataArg, isPrintf))
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001386 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001387
Chris Lattner655f1412009-04-29 04:59:47 +00001388 // If there are no arguments specified, warn with -Wformat-security, otherwise
1389 // warn only with -Wformat-nonliteral.
1390 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump1eb44332009-09-09 15:08:12 +00001391 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001392 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001393 << OrigFormatExpr->getSourceRange();
1394 else
Mike Stump1eb44332009-09-09 15:08:12 +00001395 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001396 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001397 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001398}
Ted Kremenek71895b92007-08-14 17:39:48 +00001399
Ted Kremeneke0e53132010-01-28 23:39:18 +00001400namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001401class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1402protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001403 Sema &S;
1404 const StringLiteral *FExpr;
1405 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001406 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001407 const unsigned NumDataArgs;
1408 const bool IsObjCLiteral;
1409 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001410 const bool HasVAListArg;
1411 const CallExpr *TheCall;
1412 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001413 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001414 bool usesPositionalArgs;
1415 bool atFirstArg;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001416public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001417 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001418 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001419 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001420 const char *beg, bool hasVAListArg,
1421 const CallExpr *theCall, unsigned formatIdx)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001422 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek6ee76532010-03-25 03:59:12 +00001423 FirstDataArg(firstDataArg),
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001424 NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001425 IsObjCLiteral(isObjCLiteral), Beg(beg),
1426 HasVAListArg(hasVAListArg),
Ted Kremenekefaff192010-02-27 01:41:03 +00001427 TheCall(theCall), FormatIdx(formatIdx),
1428 usesPositionalArgs(false), atFirstArg(true) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001429 CoveredArgs.resize(numDataArgs);
1430 CoveredArgs.reset();
1431 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001432
Ted Kremenek07d161f2010-01-29 01:50:07 +00001433 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001434
Ted Kremenek826a3452010-07-16 02:11:22 +00001435 void HandleIncompleteSpecifier(const char *startSpecifier,
1436 unsigned specifierLen);
1437
Ted Kremenekefaff192010-02-27 01:41:03 +00001438 virtual void HandleInvalidPosition(const char *startSpecifier,
1439 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001440 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001441
1442 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1443
Ted Kremeneke0e53132010-01-28 23:39:18 +00001444 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001445
Ted Kremenek826a3452010-07-16 02:11:22 +00001446protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001447 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1448 const char *startSpec,
1449 unsigned specifierLen,
1450 const char *csStart, unsigned csLen);
1451
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001452 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00001453 CharSourceRange getSpecifierRange(const char *startSpecifier,
1454 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001455 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001456
Ted Kremenek0d277352010-01-29 01:06:55 +00001457 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00001458
1459 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1460 const analyze_format_string::ConversionSpecifier &CS,
1461 const char *startSpecifier, unsigned specifierLen,
1462 unsigned argIndex);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001463};
1464}
1465
Ted Kremenek826a3452010-07-16 02:11:22 +00001466SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001467 return OrigFormatExpr->getSourceRange();
1468}
1469
Ted Kremenek826a3452010-07-16 02:11:22 +00001470CharSourceRange CheckFormatHandler::
1471getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001472 SourceLocation Start = getLocationOfByte(startSpecifier);
1473 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1474
1475 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001476 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00001477
1478 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001479}
1480
Ted Kremenek826a3452010-07-16 02:11:22 +00001481SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001482 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001483}
1484
Ted Kremenek826a3452010-07-16 02:11:22 +00001485void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1486 unsigned specifierLen){
Ted Kremenek808015a2010-01-29 03:16:21 +00001487 SourceLocation Loc = getLocationOfByte(startSpecifier);
1488 S.Diag(Loc, diag::warn_printf_incomplete_specifier)
Ted Kremenek826a3452010-07-16 02:11:22 +00001489 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek808015a2010-01-29 03:16:21 +00001490}
1491
Ted Kremenekefaff192010-02-27 01:41:03 +00001492void
Ted Kremenek826a3452010-07-16 02:11:22 +00001493CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1494 analyze_format_string::PositionContext p) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001495 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek826a3452010-07-16 02:11:22 +00001496 S.Diag(Loc, diag::warn_format_invalid_positional_specifier)
1497 << (unsigned) p << getSpecifierRange(startPos, posLen);
Ted Kremenekefaff192010-02-27 01:41:03 +00001498}
1499
Ted Kremenek826a3452010-07-16 02:11:22 +00001500void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00001501 unsigned posLen) {
1502 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek826a3452010-07-16 02:11:22 +00001503 S.Diag(Loc, diag::warn_format_zero_positional_specifier)
1504 << getSpecifierRange(startPos, posLen);
Ted Kremenekefaff192010-02-27 01:41:03 +00001505}
1506
Ted Kremenek826a3452010-07-16 02:11:22 +00001507void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Ted Kremenek0c069442011-03-15 21:18:48 +00001508 if (!IsObjCLiteral) {
1509 // The presence of a null character is likely an error.
1510 S.Diag(getLocationOfByte(nullCharacter),
1511 diag::warn_printf_format_string_contains_null_char)
1512 << getFormatStringRange();
1513 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001514}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001515
Ted Kremenek826a3452010-07-16 02:11:22 +00001516const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
1517 return TheCall->getArg(FirstDataArg + i);
1518}
1519
1520void CheckFormatHandler::DoneProcessing() {
1521 // Does the number of data arguments exceed the number of
1522 // format conversions in the format string?
1523 if (!HasVAListArg) {
1524 // Find any arguments that weren't covered.
1525 CoveredArgs.flip();
1526 signed notCoveredArg = CoveredArgs.find_first();
1527 if (notCoveredArg >= 0) {
1528 assert((unsigned)notCoveredArg < NumDataArgs);
1529 S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(),
1530 diag::warn_printf_data_arg_not_used)
1531 << getFormatStringRange();
1532 }
1533 }
1534}
1535
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001536bool
1537CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1538 SourceLocation Loc,
1539 const char *startSpec,
1540 unsigned specifierLen,
1541 const char *csStart,
1542 unsigned csLen) {
1543
1544 bool keepGoing = true;
1545 if (argIndex < NumDataArgs) {
1546 // Consider the argument coverered, even though the specifier doesn't
1547 // make sense.
1548 CoveredArgs.set(argIndex);
1549 }
1550 else {
1551 // If argIndex exceeds the number of data arguments we
1552 // don't issue a warning because that is just a cascade of warnings (and
1553 // they may have intended '%%' anyway). We don't want to continue processing
1554 // the format string after this point, however, as we will like just get
1555 // gibberish when trying to match arguments.
1556 keepGoing = false;
1557 }
1558
1559 S.Diag(Loc, diag::warn_format_invalid_conversion)
Chris Lattner5f9e2722011-07-23 10:55:15 +00001560 << StringRef(csStart, csLen)
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001561 << getSpecifierRange(startSpec, specifierLen);
1562
1563 return keepGoing;
1564}
1565
Ted Kremenek666a1972010-07-26 19:45:42 +00001566bool
1567CheckFormatHandler::CheckNumArgs(
1568 const analyze_format_string::FormatSpecifier &FS,
1569 const analyze_format_string::ConversionSpecifier &CS,
1570 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1571
1572 if (argIndex >= NumDataArgs) {
1573 if (FS.usesPositionalArg()) {
1574 S.Diag(getLocationOfByte(CS.getStart()),
1575 diag::warn_printf_positional_arg_exceeds_data_args)
1576 << (argIndex+1) << NumDataArgs
1577 << getSpecifierRange(startSpecifier, specifierLen);
1578 }
1579 else {
1580 S.Diag(getLocationOfByte(CS.getStart()),
1581 diag::warn_printf_insufficient_data_args)
1582 << getSpecifierRange(startSpecifier, specifierLen);
1583 }
1584
1585 return false;
1586 }
1587 return true;
1588}
1589
Ted Kremenek826a3452010-07-16 02:11:22 +00001590//===--- CHECK: Printf format string checking ------------------------------===//
1591
1592namespace {
1593class CheckPrintfHandler : public CheckFormatHandler {
1594public:
1595 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1596 const Expr *origFormatExpr, unsigned firstDataArg,
1597 unsigned numDataArgs, bool isObjCLiteral,
1598 const char *beg, bool hasVAListArg,
1599 const CallExpr *theCall, unsigned formatIdx)
1600 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1601 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1602 theCall, formatIdx) {}
1603
1604
1605 bool HandleInvalidPrintfConversionSpecifier(
1606 const analyze_printf::PrintfSpecifier &FS,
1607 const char *startSpecifier,
1608 unsigned specifierLen);
1609
1610 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1611 const char *startSpecifier,
1612 unsigned specifierLen);
1613
1614 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1615 const char *startSpecifier, unsigned specifierLen);
1616 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1617 const analyze_printf::OptionalAmount &Amt,
1618 unsigned type,
1619 const char *startSpecifier, unsigned specifierLen);
1620 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1621 const analyze_printf::OptionalFlag &flag,
1622 const char *startSpecifier, unsigned specifierLen);
1623 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1624 const analyze_printf::OptionalFlag &ignoredFlag,
1625 const analyze_printf::OptionalFlag &flag,
1626 const char *startSpecifier, unsigned specifierLen);
1627};
1628}
1629
1630bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1631 const analyze_printf::PrintfSpecifier &FS,
1632 const char *startSpecifier,
1633 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001634 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001635 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001636
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001637 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1638 getLocationOfByte(CS.getStart()),
1639 startSpecifier, specifierLen,
1640 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001641}
1642
Ted Kremenek826a3452010-07-16 02:11:22 +00001643bool CheckPrintfHandler::HandleAmount(
1644 const analyze_format_string::OptionalAmount &Amt,
1645 unsigned k, const char *startSpecifier,
1646 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001647
1648 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001649 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001650 unsigned argIndex = Amt.getArgIndex();
1651 if (argIndex >= NumDataArgs) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001652 S.Diag(getLocationOfByte(Amt.getStart()),
1653 diag::warn_printf_asterisk_missing_arg)
Ted Kremenek826a3452010-07-16 02:11:22 +00001654 << k << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek0d277352010-01-29 01:06:55 +00001655 // Don't do any more checking. We will just emit
1656 // spurious errors.
1657 return false;
1658 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001659
Ted Kremenek0d277352010-01-29 01:06:55 +00001660 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00001661 // Although not in conformance with C99, we also allow the argument to be
1662 // an 'unsigned int' as that is a reasonably safe case. GCC also
1663 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001664 CoveredArgs.set(argIndex);
1665 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00001666 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001667
1668 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1669 assert(ATR.isValid());
1670
1671 if (!ATR.matchesType(S.Context, T)) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001672 S.Diag(getLocationOfByte(Amt.getStart()),
1673 diag::warn_printf_asterisk_wrong_type)
1674 << k
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001675 << ATR.getRepresentativeType(S.Context) << T
Ted Kremenek826a3452010-07-16 02:11:22 +00001676 << getSpecifierRange(startSpecifier, specifierLen)
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001677 << Arg->getSourceRange();
Ted Kremenek0d277352010-01-29 01:06:55 +00001678 // Don't do any more checking. We will just emit
1679 // spurious errors.
1680 return false;
1681 }
1682 }
1683 }
1684 return true;
1685}
Ted Kremenek0d277352010-01-29 01:06:55 +00001686
Tom Caree4ee9662010-06-17 19:00:27 +00001687void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00001688 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001689 const analyze_printf::OptionalAmount &Amt,
1690 unsigned type,
1691 const char *startSpecifier,
1692 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001693 const analyze_printf::PrintfConversionSpecifier &CS =
1694 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001695 switch (Amt.getHowSpecified()) {
1696 case analyze_printf::OptionalAmount::Constant:
1697 S.Diag(getLocationOfByte(Amt.getStart()),
1698 diag::warn_printf_nonsensical_optional_amount)
1699 << type
1700 << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001701 << getSpecifierRange(startSpecifier, specifierLen)
1702 << FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
Tom Caree4ee9662010-06-17 19:00:27 +00001703 Amt.getConstantLength()));
1704 break;
1705
1706 default:
1707 S.Diag(getLocationOfByte(Amt.getStart()),
1708 diag::warn_printf_nonsensical_optional_amount)
1709 << type
1710 << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001711 << getSpecifierRange(startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001712 break;
1713 }
1714}
1715
Ted Kremenek826a3452010-07-16 02:11:22 +00001716void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001717 const analyze_printf::OptionalFlag &flag,
1718 const char *startSpecifier,
1719 unsigned specifierLen) {
1720 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001721 const analyze_printf::PrintfConversionSpecifier &CS =
1722 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001723 S.Diag(getLocationOfByte(flag.getPosition()),
1724 diag::warn_printf_nonsensical_flag)
1725 << flag.toString() << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001726 << getSpecifierRange(startSpecifier, specifierLen)
1727 << FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1));
Tom Caree4ee9662010-06-17 19:00:27 +00001728}
1729
1730void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00001731 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001732 const analyze_printf::OptionalFlag &ignoredFlag,
1733 const analyze_printf::OptionalFlag &flag,
1734 const char *startSpecifier,
1735 unsigned specifierLen) {
1736 // Warn about ignored flag with a fixit removal.
1737 S.Diag(getLocationOfByte(ignoredFlag.getPosition()),
1738 diag::warn_printf_ignored_flag)
1739 << ignoredFlag.toString() << flag.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001740 << getSpecifierRange(startSpecifier, specifierLen)
1741 << FixItHint::CreateRemoval(getSpecifierRange(
Tom Caree4ee9662010-06-17 19:00:27 +00001742 ignoredFlag.getPosition(), 1));
1743}
1744
Ted Kremeneke0e53132010-01-28 23:39:18 +00001745bool
Ted Kremenek826a3452010-07-16 02:11:22 +00001746CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001747 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001748 const char *startSpecifier,
1749 unsigned specifierLen) {
1750
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001751 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00001752 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001753 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00001754
Ted Kremenekbaa40062010-07-19 22:01:06 +00001755 if (FS.consumesDataArgument()) {
1756 if (atFirstArg) {
1757 atFirstArg = false;
1758 usesPositionalArgs = FS.usesPositionalArg();
1759 }
1760 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1761 // Cannot mix-and-match positional and non-positional arguments.
1762 S.Diag(getLocationOfByte(CS.getStart()),
1763 diag::warn_format_mix_positional_nonpositional_args)
1764 << getSpecifierRange(startSpecifier, specifierLen);
1765 return false;
1766 }
Ted Kremenek0d277352010-01-29 01:06:55 +00001767 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001768
Ted Kremenekefaff192010-02-27 01:41:03 +00001769 // First check if the field width, precision, and conversion specifier
1770 // have matching data arguments.
1771 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1772 startSpecifier, specifierLen)) {
1773 return false;
1774 }
1775
1776 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1777 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001778 return false;
1779 }
1780
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001781 if (!CS.consumesDataArgument()) {
1782 // FIXME: Technically specifying a precision or field width here
1783 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001784 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001785 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001786
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001787 // Consume the argument.
1788 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00001789 if (argIndex < NumDataArgs) {
1790 // The check to see if the argIndex is valid will come later.
1791 // We set the bit here because we may exit early from this
1792 // function if we encounter some other error.
1793 CoveredArgs.set(argIndex);
1794 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001795
1796 // Check for using an Objective-C specific conversion specifier
1797 // in a non-ObjC literal.
1798 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001799 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
1800 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001801 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001802
Tom Caree4ee9662010-06-17 19:00:27 +00001803 // Check for invalid use of field width
1804 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001805 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00001806 startSpecifier, specifierLen);
1807 }
1808
1809 // Check for invalid use of precision
1810 if (!FS.hasValidPrecision()) {
1811 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
1812 startSpecifier, specifierLen);
1813 }
1814
1815 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00001816 if (!FS.hasValidThousandsGroupingPrefix())
1817 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001818 if (!FS.hasValidLeadingZeros())
1819 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
1820 if (!FS.hasValidPlusPrefix())
1821 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00001822 if (!FS.hasValidSpacePrefix())
1823 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001824 if (!FS.hasValidAlternativeForm())
1825 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
1826 if (!FS.hasValidLeftJustified())
1827 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
1828
1829 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00001830 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
1831 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
1832 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001833 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
1834 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
1835 startSpecifier, specifierLen);
1836
1837 // Check the length modifier is valid with the given conversion specifier.
1838 const LengthModifier &LM = FS.getLengthModifier();
1839 if (!FS.hasValidLengthModifier())
1840 S.Diag(getLocationOfByte(LM.getStart()),
Ted Kremenek649aecf2010-07-20 20:03:43 +00001841 diag::warn_format_nonsensical_length)
Tom Caree4ee9662010-06-17 19:00:27 +00001842 << LM.toString() << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001843 << getSpecifierRange(startSpecifier, specifierLen)
1844 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
Tom Caree4ee9662010-06-17 19:00:27 +00001845 LM.getLength()));
1846
1847 // Are we using '%n'?
Ted Kremenek35d353b2010-07-20 20:04:10 +00001848 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Caree4ee9662010-06-17 19:00:27 +00001849 // Issue a warning about this being a possible security issue.
Ted Kremeneke82d8042010-01-29 01:35:25 +00001850 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
Ted Kremenek826a3452010-07-16 02:11:22 +00001851 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremeneke82d8042010-01-29 01:35:25 +00001852 // Continue checking the other format specifiers.
1853 return true;
1854 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001855
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001856 // The remaining checks depend on the data arguments.
1857 if (HasVAListArg)
1858 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001859
Ted Kremenek666a1972010-07-26 19:45:42 +00001860 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001861 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001862
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001863 // Now type check the data expression that matches the
1864 // format specifier.
1865 const Expr *Ex = getDataArg(argIndex);
1866 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
1867 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
1868 // Check if we didn't match because of an implicit cast from a 'char'
1869 // or 'short' to an 'int'. This is done because printf is a varargs
1870 // function.
1871 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00001872 if (ICE->getType() == S.Context.IntTy) {
1873 // All further checking is done on the subexpression.
1874 Ex = ICE->getSubExpr();
1875 if (ATR.matchesType(S.Context, Ex->getType()))
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001876 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00001877 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001878
1879 // We may be able to offer a FixItHint if it is a supported type.
1880 PrintfSpecifier fixedFS = FS;
1881 bool success = fixedFS.fixType(Ex->getType());
1882
1883 if (success) {
1884 // Get the fix string from the fixed format specifier
1885 llvm::SmallString<128> buf;
1886 llvm::raw_svector_ostream os(buf);
1887 fixedFS.toString(os);
1888
Ted Kremenek9325eaf2010-08-24 22:24:51 +00001889 // FIXME: getRepresentativeType() perhaps should return a string
1890 // instead of a QualType to better handle when the representative
1891 // type is 'wint_t' (which is defined in the system headers).
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001892 S.Diag(getLocationOfByte(CS.getStart()),
1893 diag::warn_printf_conversion_argument_type_mismatch)
1894 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1895 << getSpecifierRange(startSpecifier, specifierLen)
1896 << Ex->getSourceRange()
1897 << FixItHint::CreateReplacement(
1898 getSpecifierRange(startSpecifier, specifierLen),
1899 os.str());
1900 }
1901 else {
1902 S.Diag(getLocationOfByte(CS.getStart()),
1903 diag::warn_printf_conversion_argument_type_mismatch)
1904 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1905 << getSpecifierRange(startSpecifier, specifierLen)
1906 << Ex->getSourceRange();
1907 }
1908 }
1909
Ted Kremeneke0e53132010-01-28 23:39:18 +00001910 return true;
1911}
1912
Ted Kremenek826a3452010-07-16 02:11:22 +00001913//===--- CHECK: Scanf format string checking ------------------------------===//
1914
1915namespace {
1916class CheckScanfHandler : public CheckFormatHandler {
1917public:
1918 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
1919 const Expr *origFormatExpr, unsigned firstDataArg,
1920 unsigned numDataArgs, bool isObjCLiteral,
1921 const char *beg, bool hasVAListArg,
1922 const CallExpr *theCall, unsigned formatIdx)
1923 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1924 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1925 theCall, formatIdx) {}
1926
1927 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
1928 const char *startSpecifier,
1929 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001930
1931 bool HandleInvalidScanfConversionSpecifier(
1932 const analyze_scanf::ScanfSpecifier &FS,
1933 const char *startSpecifier,
1934 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00001935
1936 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00001937};
Ted Kremenek07d161f2010-01-29 01:50:07 +00001938}
Ted Kremeneke0e53132010-01-28 23:39:18 +00001939
Ted Kremenekb7c21012010-07-16 18:28:03 +00001940void CheckScanfHandler::HandleIncompleteScanList(const char *start,
1941 const char *end) {
1942 S.Diag(getLocationOfByte(end), diag::warn_scanf_scanlist_incomplete)
1943 << getSpecifierRange(start, end - start);
1944}
1945
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001946bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
1947 const analyze_scanf::ScanfSpecifier &FS,
1948 const char *startSpecifier,
1949 unsigned specifierLen) {
1950
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001951 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001952 FS.getConversionSpecifier();
1953
1954 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1955 getLocationOfByte(CS.getStart()),
1956 startSpecifier, specifierLen,
1957 CS.getStart(), CS.getLength());
1958}
1959
Ted Kremenek826a3452010-07-16 02:11:22 +00001960bool CheckScanfHandler::HandleScanfSpecifier(
1961 const analyze_scanf::ScanfSpecifier &FS,
1962 const char *startSpecifier,
1963 unsigned specifierLen) {
1964
1965 using namespace analyze_scanf;
1966 using namespace analyze_format_string;
1967
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001968 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001969
Ted Kremenekbaa40062010-07-19 22:01:06 +00001970 // Handle case where '%' and '*' don't consume an argument. These shouldn't
1971 // be used to decide if we are using positional arguments consistently.
1972 if (FS.consumesDataArgument()) {
1973 if (atFirstArg) {
1974 atFirstArg = false;
1975 usesPositionalArgs = FS.usesPositionalArg();
1976 }
1977 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1978 // Cannot mix-and-match positional and non-positional arguments.
1979 S.Diag(getLocationOfByte(CS.getStart()),
1980 diag::warn_format_mix_positional_nonpositional_args)
1981 << getSpecifierRange(startSpecifier, specifierLen);
1982 return false;
1983 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001984 }
1985
1986 // Check if the field with is non-zero.
1987 const OptionalAmount &Amt = FS.getFieldWidth();
1988 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
1989 if (Amt.getConstantAmount() == 0) {
1990 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
1991 Amt.getConstantLength());
1992 S.Diag(getLocationOfByte(Amt.getStart()),
1993 diag::warn_scanf_nonzero_width)
1994 << R << FixItHint::CreateRemoval(R);
1995 }
1996 }
1997
1998 if (!FS.consumesDataArgument()) {
1999 // FIXME: Technically specifying a precision or field width here
2000 // makes no sense. Worth issuing a warning at some point.
2001 return true;
2002 }
2003
2004 // Consume the argument.
2005 unsigned argIndex = FS.getArgIndex();
2006 if (argIndex < NumDataArgs) {
2007 // The check to see if the argIndex is valid will come later.
2008 // We set the bit here because we may exit early from this
2009 // function if we encounter some other error.
2010 CoveredArgs.set(argIndex);
2011 }
2012
Ted Kremenek1e51c202010-07-20 20:04:47 +00002013 // Check the length modifier is valid with the given conversion specifier.
2014 const LengthModifier &LM = FS.getLengthModifier();
2015 if (!FS.hasValidLengthModifier()) {
2016 S.Diag(getLocationOfByte(LM.getStart()),
2017 diag::warn_format_nonsensical_length)
2018 << LM.toString() << CS.toString()
2019 << getSpecifierRange(startSpecifier, specifierLen)
2020 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
2021 LM.getLength()));
2022 }
2023
Ted Kremenek826a3452010-07-16 02:11:22 +00002024 // The remaining checks depend on the data arguments.
2025 if (HasVAListArg)
2026 return true;
2027
Ted Kremenek666a1972010-07-26 19:45:42 +00002028 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00002029 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00002030
2031 // FIXME: Check that the argument type matches the format specifier.
2032
2033 return true;
2034}
2035
2036void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002037 const Expr *OrigFormatExpr,
2038 const CallExpr *TheCall, bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00002039 unsigned format_idx, unsigned firstDataArg,
2040 bool isPrintf) {
2041
Ted Kremeneke0e53132010-01-28 23:39:18 +00002042 // CHECK: is the format string a wide literal?
Douglas Gregor5cee1192011-07-27 05:40:30 +00002043 if (!FExpr->isAscii()) {
Ted Kremeneke0e53132010-01-28 23:39:18 +00002044 Diag(FExpr->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00002045 diag::warn_format_string_is_wide_literal)
Ted Kremeneke0e53132010-01-28 23:39:18 +00002046 << OrigFormatExpr->getSourceRange();
2047 return;
2048 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002049
Ted Kremeneke0e53132010-01-28 23:39:18 +00002050 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00002051 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00002052 const char *Str = StrRef.data();
2053 unsigned StrLen = StrRef.size();
Ted Kremenek4cd57912011-09-29 05:52:16 +00002054 const unsigned numDataArgs = TheCall->getNumArgs() - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00002055
Ted Kremeneke0e53132010-01-28 23:39:18 +00002056 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00002057 if (StrLen == 0 && numDataArgs > 0) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002058 Diag(FExpr->getLocStart(), diag::warn_empty_format_string)
Ted Kremeneke0e53132010-01-28 23:39:18 +00002059 << OrigFormatExpr->getSourceRange();
2060 return;
2061 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002062
2063 if (isPrintf) {
2064 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremenek4cd57912011-09-29 05:52:16 +00002065 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
2066 Str, HasVAListArg, TheCall, format_idx);
Ted Kremenek826a3452010-07-16 02:11:22 +00002067
2068 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen))
2069 H.DoneProcessing();
2070 }
2071 else {
2072 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremenek4cd57912011-09-29 05:52:16 +00002073 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
2074 Str, HasVAListArg, TheCall, format_idx);
Ted Kremenek826a3452010-07-16 02:11:22 +00002075
2076 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen))
2077 H.DoneProcessing();
2078 }
Ted Kremenekce7024e2010-01-28 01:18:22 +00002079}
2080
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002081//===--- CHECK: Standard memory functions ---------------------------------===//
2082
Douglas Gregor2a053a32011-05-03 20:05:22 +00002083/// \brief Determine whether the given type is a dynamic class type (e.g.,
2084/// whether it has a vtable).
2085static bool isDynamicClassType(QualType T) {
2086 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
2087 if (CXXRecordDecl *Definition = Record->getDefinition())
2088 if (Definition->isDynamicClass())
2089 return true;
2090
2091 return false;
2092}
2093
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002094/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00002095/// otherwise returns NULL.
2096static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00002097 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00002098 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2099 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
2100 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002101
Chandler Carruth000d4282011-06-16 09:09:40 +00002102 return 0;
2103}
2104
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002105/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00002106static QualType getSizeOfArgType(const Expr* E) {
2107 if (const UnaryExprOrTypeTraitExpr *SizeOf =
2108 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2109 if (SizeOf->getKind() == clang::UETT_SizeOf)
2110 return SizeOf->getTypeOfArgument();
2111
2112 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00002113}
2114
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002115/// \brief Check for dangerous or invalid arguments to memset().
2116///
Chandler Carruth929f0132011-06-03 06:23:57 +00002117/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002118/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
2119/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002120///
2121/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002122void Sema::CheckMemaccessArguments(const CallExpr *Call,
2123 CheckedMemoryFunction CMF,
2124 IdentifierInfo *FnName) {
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002125 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00002126 // we have enough arguments, and if not, abort further checking.
2127 if (Call->getNumArgs() < 3)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002128 return;
2129
Douglas Gregor707a23e2011-06-16 17:56:04 +00002130 unsigned LastArg = (CMF == CMF_Memset? 1 : 2);
Nico Webere4a1c642011-06-14 16:14:58 +00002131 const Expr *LenExpr = Call->getArg(2)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00002132
2133 // We have special checking when the length is a sizeof expression.
2134 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
2135 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
2136 llvm::FoldingSetNodeID SizeOfArgID;
2137
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002138 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
2139 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002140 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002141
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002142 QualType DestTy = Dest->getType();
2143 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
2144 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00002145
Chandler Carruth000d4282011-06-16 09:09:40 +00002146 // Never warn about void type pointers. This can be used to suppress
2147 // false positives.
2148 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002149 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002150
Chandler Carruth000d4282011-06-16 09:09:40 +00002151 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
2152 // actually comparing the expressions for equality. Because computing the
2153 // expression IDs can be expensive, we only do this if the diagnostic is
2154 // enabled.
2155 if (SizeOfArg &&
2156 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
2157 SizeOfArg->getExprLoc())) {
2158 // We only compute IDs for expressions if the warning is enabled, and
2159 // cache the sizeof arg's ID.
2160 if (SizeOfArgID == llvm::FoldingSetNodeID())
2161 SizeOfArg->Profile(SizeOfArgID, Context, true);
2162 llvm::FoldingSetNodeID DestID;
2163 Dest->Profile(DestID, Context, true);
2164 if (DestID == SizeOfArgID) {
2165 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
2166 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
2167 if (UnaryOp->getOpcode() == UO_AddrOf)
2168 ActionIdx = 1; // If its an address-of operator, just remove it.
2169 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
2170 ActionIdx = 2; // If the pointee's size is sizeof(char),
2171 // suggest an explicit length.
2172 DiagRuntimeBehavior(SizeOfArg->getExprLoc(), Dest,
2173 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
2174 << FnName << ArgIdx << ActionIdx
2175 << Dest->getSourceRange()
2176 << SizeOfArg->getSourceRange());
2177 break;
2178 }
2179 }
2180
2181 // Also check for cases where the sizeof argument is the exact same
2182 // type as the memory argument, and where it points to a user-defined
2183 // record type.
2184 if (SizeOfArgTy != QualType()) {
2185 if (PointeeTy->isRecordType() &&
2186 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
2187 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
2188 PDiag(diag::warn_sizeof_pointer_type_memaccess)
2189 << FnName << SizeOfArgTy << ArgIdx
2190 << PointeeTy << Dest->getSourceRange()
2191 << LenExpr->getSourceRange());
2192 break;
2193 }
Nico Webere4a1c642011-06-14 16:14:58 +00002194 }
2195
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002196 // Always complain about dynamic classes.
John McCallf85e1932011-06-15 23:02:42 +00002197 if (isDynamicClassType(PointeeTy))
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002198 DiagRuntimeBehavior(
2199 Dest->getExprLoc(), Dest,
2200 PDiag(diag::warn_dyn_class_memaccess)
2201 << (CMF == CMF_Memcmp ? ArgIdx + 2 : ArgIdx) << FnName << PointeeTy
2202 // "overwritten" if we're warning about the destination for any call
2203 // but memcmp; otherwise a verb appropriate to the call.
2204 << (ArgIdx == 0 && CMF != CMF_Memcmp ? 0 : (unsigned)CMF)
2205 << Call->getCallee()->getSourceRange());
Douglas Gregor707a23e2011-06-16 17:56:04 +00002206 else if (PointeeTy.hasNonTrivialObjCLifetime() && CMF != CMF_Memset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002207 DiagRuntimeBehavior(
2208 Dest->getExprLoc(), Dest,
2209 PDiag(diag::warn_arc_object_memaccess)
2210 << ArgIdx << FnName << PointeeTy
2211 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00002212 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002213 continue;
John McCallf85e1932011-06-15 23:02:42 +00002214
2215 DiagRuntimeBehavior(
2216 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00002217 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002218 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
2219 break;
2220 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002221 }
2222}
2223
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002224// A little helper routine: ignore addition and subtraction of integer literals.
2225// This intentionally does not ignore all integer constant expressions because
2226// we don't want to remove sizeof().
2227static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
2228 Ex = Ex->IgnoreParenCasts();
2229
2230 for (;;) {
2231 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
2232 if (!BO || !BO->isAdditiveOp())
2233 break;
2234
2235 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
2236 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
2237
2238 if (isa<IntegerLiteral>(RHS))
2239 Ex = LHS;
2240 else if (isa<IntegerLiteral>(LHS))
2241 Ex = RHS;
2242 else
2243 break;
2244 }
2245
2246 return Ex;
2247}
2248
2249// Warn if the user has made the 'size' argument to strlcpy or strlcat
2250// be the size of the source, instead of the destination.
2251void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
2252 IdentifierInfo *FnName) {
2253
2254 // Don't crash if the user has the wrong number of arguments
2255 if (Call->getNumArgs() != 3)
2256 return;
2257
2258 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
2259 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
2260 const Expr *CompareWithSrc = NULL;
2261
2262 // Look for 'strlcpy(dst, x, sizeof(x))'
2263 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
2264 CompareWithSrc = Ex;
2265 else {
2266 // Look for 'strlcpy(dst, x, strlen(x))'
2267 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
2268 if (SizeCall->isBuiltinCall(Context) == Builtin::BIstrlen
2269 && SizeCall->getNumArgs() == 1)
2270 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
2271 }
2272 }
2273
2274 if (!CompareWithSrc)
2275 return;
2276
2277 // Determine if the argument to sizeof/strlen is equal to the source
2278 // argument. In principle there's all kinds of things you could do
2279 // here, for instance creating an == expression and evaluating it with
2280 // EvaluateAsBooleanCondition, but this uses a more direct technique:
2281 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
2282 if (!SrcArgDRE)
2283 return;
2284
2285 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
2286 if (!CompareWithSrcDRE ||
2287 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
2288 return;
2289
2290 const Expr *OriginalSizeArg = Call->getArg(2);
2291 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
2292 << OriginalSizeArg->getSourceRange() << FnName;
2293
2294 // Output a FIXIT hint if the destination is an array (rather than a
2295 // pointer to an array). This could be enhanced to handle some
2296 // pointers if we know the actual size, like if DstArg is 'array+2'
2297 // we could say 'sizeof(array)-2'.
2298 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Ted Kremenek8f746222011-08-18 22:48:41 +00002299 QualType DstArgTy = DstArg->getType();
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002300
Ted Kremenek8f746222011-08-18 22:48:41 +00002301 // Only handle constant-sized or VLAs, but not flexible members.
2302 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
2303 // Only issue the FIXIT for arrays of size > 1.
2304 if (CAT->getSize().getSExtValue() <= 1)
2305 return;
2306 } else if (!DstArgTy->isVariableArrayType()) {
2307 return;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002308 }
Ted Kremenek8f746222011-08-18 22:48:41 +00002309
2310 llvm::SmallString<128> sizeString;
2311 llvm::raw_svector_ostream OS(sizeString);
2312 OS << "sizeof(";
Douglas Gregor8987b232011-09-27 23:30:47 +00002313 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00002314 OS << ")";
2315
2316 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
2317 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
2318 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002319}
2320
Ted Kremenek06de2762007-08-17 16:46:58 +00002321//===--- CHECK: Return Address of Stack Variable --------------------------===//
2322
Chris Lattner5f9e2722011-07-23 10:55:15 +00002323static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars);
2324static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002325
2326/// CheckReturnStackAddr - Check if a return statement returns the address
2327/// of a stack variable.
2328void
2329Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
2330 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00002331
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002332 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002333 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002334
2335 // Perform checking for returned stack addresses, local blocks,
2336 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00002337 if (lhsType->isPointerType() ||
2338 (!getLangOptions().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002339 stackE = EvalAddr(RetValExp, refVars);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002340 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002341 stackE = EvalVal(RetValExp, refVars);
2342 }
2343
2344 if (stackE == 0)
2345 return; // Nothing suspicious was found.
2346
2347 SourceLocation diagLoc;
2348 SourceRange diagRange;
2349 if (refVars.empty()) {
2350 diagLoc = stackE->getLocStart();
2351 diagRange = stackE->getSourceRange();
2352 } else {
2353 // We followed through a reference variable. 'stackE' contains the
2354 // problematic expression but we will warn at the return statement pointing
2355 // at the reference variable. We will later display the "trail" of
2356 // reference variables using notes.
2357 diagLoc = refVars[0]->getLocStart();
2358 diagRange = refVars[0]->getSourceRange();
2359 }
2360
2361 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
2362 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
2363 : diag::warn_ret_stack_addr)
2364 << DR->getDecl()->getDeclName() << diagRange;
2365 } else if (isa<BlockExpr>(stackE)) { // local block.
2366 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
2367 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
2368 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
2369 } else { // local temporary.
2370 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
2371 : diag::warn_ret_local_temp_addr)
2372 << diagRange;
2373 }
2374
2375 // Display the "trail" of reference variables that we followed until we
2376 // found the problematic expression using notes.
2377 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
2378 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
2379 // If this var binds to another reference var, show the range of the next
2380 // var, otherwise the var binds to the problematic expression, in which case
2381 // show the range of the expression.
2382 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
2383 : stackE->getSourceRange();
2384 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
2385 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00002386 }
2387}
2388
2389/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
2390/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002391/// to a location on the stack, a local block, an address of a label, or a
2392/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00002393/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002394/// encounter a subexpression that (1) clearly does not lead to one of the
2395/// above problematic expressions (2) is something we cannot determine leads to
2396/// a problematic expression based on such local checking.
2397///
2398/// Both EvalAddr and EvalVal follow through reference variables to evaluate
2399/// the expression that they point to. Such variables are added to the
2400/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00002401///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002402/// EvalAddr processes expressions that are pointers that are used as
2403/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002404/// At the base case of the recursion is a check for the above problematic
2405/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00002406///
2407/// This implementation handles:
2408///
2409/// * pointer-to-pointer casts
2410/// * implicit conversions from array references to pointers
2411/// * taking the address of fields
2412/// * arbitrary interplay between "&" and "*" operators
2413/// * pointer arithmetic from an address of a stack variable
2414/// * taking the address of an array element where the array is on the stack
Chris Lattner5f9e2722011-07-23 10:55:15 +00002415static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002416 if (E->isTypeDependent())
2417 return NULL;
2418
Ted Kremenek06de2762007-08-17 16:46:58 +00002419 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00002420 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00002421 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002422 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002423 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00002424
Peter Collingbournef111d932011-04-15 00:35:48 +00002425 E = E->IgnoreParens();
2426
Ted Kremenek06de2762007-08-17 16:46:58 +00002427 // Our "symbolic interpreter" is just a dispatch off the currently
2428 // viewed AST node. We then recursively traverse the AST by calling
2429 // EvalAddr and EvalVal appropriately.
2430 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002431 case Stmt::DeclRefExprClass: {
2432 DeclRefExpr *DR = cast<DeclRefExpr>(E);
2433
2434 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
2435 // If this is a reference variable, follow through to the expression that
2436 // it points to.
2437 if (V->hasLocalStorage() &&
2438 V->getType()->isReferenceType() && V->hasInit()) {
2439 // Add the reference variable to the "trail".
2440 refVars.push_back(DR);
2441 return EvalAddr(V->getInit(), refVars);
2442 }
2443
2444 return NULL;
2445 }
Ted Kremenek06de2762007-08-17 16:46:58 +00002446
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002447 case Stmt::UnaryOperatorClass: {
2448 // The only unary operator that make sense to handle here
2449 // is AddrOf. All others don't make sense as pointers.
2450 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002451
John McCall2de56d12010-08-25 11:45:40 +00002452 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002453 return EvalVal(U->getSubExpr(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002454 else
Ted Kremenek06de2762007-08-17 16:46:58 +00002455 return NULL;
2456 }
Mike Stump1eb44332009-09-09 15:08:12 +00002457
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002458 case Stmt::BinaryOperatorClass: {
2459 // Handle pointer arithmetic. All other binary operators are not valid
2460 // in this context.
2461 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00002462 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00002463
John McCall2de56d12010-08-25 11:45:40 +00002464 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002465 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00002466
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002467 Expr *Base = B->getLHS();
2468
2469 // Determine which argument is the real pointer base. It could be
2470 // the RHS argument instead of the LHS.
2471 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00002472
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002473 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002474 return EvalAddr(Base, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002475 }
Steve Naroff61f40a22008-09-10 19:17:48 +00002476
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002477 // For conditional operators we need to see if either the LHS or RHS are
2478 // valid DeclRefExpr*s. If one of them is valid, we return it.
2479 case Stmt::ConditionalOperatorClass: {
2480 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002481
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002482 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002483 if (Expr *lhsExpr = C->getLHS()) {
2484 // In C++, we can have a throw-expression, which has 'void' type.
2485 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002486 if (Expr* LHS = EvalAddr(lhsExpr, refVars))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002487 return LHS;
2488 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002489
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002490 // In C++, we can have a throw-expression, which has 'void' type.
2491 if (C->getRHS()->getType()->isVoidType())
2492 return NULL;
2493
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002494 return EvalAddr(C->getRHS(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002495 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002496
2497 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00002498 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002499 return E; // local block.
2500 return NULL;
2501
2502 case Stmt::AddrLabelExprClass:
2503 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00002504
Ted Kremenek54b52742008-08-07 00:49:01 +00002505 // For casts, we need to handle conversions from arrays to
2506 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00002507 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002508 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00002509 case Stmt::CXXFunctionalCastExprClass:
2510 case Stmt::ObjCBridgedCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002511 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00002512 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002513
Steve Naroffdd972f22008-09-05 22:11:13 +00002514 if (SubExpr->getType()->isPointerType() ||
2515 SubExpr->getType()->isBlockPointerType() ||
2516 SubExpr->getType()->isObjCQualifiedIdType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002517 return EvalAddr(SubExpr, refVars);
Ted Kremenek54b52742008-08-07 00:49:01 +00002518 else if (T->isArrayType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002519 return EvalVal(SubExpr, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002520 else
Ted Kremenek54b52742008-08-07 00:49:01 +00002521 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002522 }
Mike Stump1eb44332009-09-09 15:08:12 +00002523
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002524 // C++ casts. For dynamic casts, static casts, and const casts, we
2525 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00002526 // through the cast. In the case the dynamic cast doesn't fail (and
2527 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002528 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00002529 // FIXME: The comment about is wrong; we're not always converting
2530 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00002531 // handle references to objects.
2532 case Stmt::CXXStaticCastExprClass:
2533 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00002534 case Stmt::CXXConstCastExprClass:
2535 case Stmt::CXXReinterpretCastExprClass: {
2536 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00002537 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002538 return EvalAddr(S, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002539 else
2540 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002541 }
Mike Stump1eb44332009-09-09 15:08:12 +00002542
Douglas Gregor03e80032011-06-21 17:03:29 +00002543 case Stmt::MaterializeTemporaryExprClass:
2544 if (Expr *Result = EvalAddr(
2545 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
2546 refVars))
2547 return Result;
2548
2549 return E;
2550
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002551 // Everything else: we simply don't reason about them.
2552 default:
2553 return NULL;
2554 }
Ted Kremenek06de2762007-08-17 16:46:58 +00002555}
Mike Stump1eb44332009-09-09 15:08:12 +00002556
Ted Kremenek06de2762007-08-17 16:46:58 +00002557
2558/// EvalVal - This function is complements EvalAddr in the mutual recursion.
2559/// See the comments for EvalAddr for more details.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002560static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002561do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002562 // We should only be called for evaluating non-pointer expressions, or
2563 // expressions with a pointer type that are not used as references but instead
2564 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00002565
Ted Kremenek06de2762007-08-17 16:46:58 +00002566 // Our "symbolic interpreter" is just a dispatch off the currently
2567 // viewed AST node. We then recursively traverse the AST by calling
2568 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00002569
2570 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00002571 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002572 case Stmt::ImplicitCastExprClass: {
2573 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00002574 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002575 E = IE->getSubExpr();
2576 continue;
2577 }
2578 return NULL;
2579 }
2580
Douglas Gregora2813ce2009-10-23 18:54:35 +00002581 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002582 // When we hit a DeclRefExpr we are looking at code that refers to a
2583 // variable's name. If it's not a reference variable we check if it has
2584 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00002585 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002586
Ted Kremenek06de2762007-08-17 16:46:58 +00002587 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002588 if (V->hasLocalStorage()) {
2589 if (!V->getType()->isReferenceType())
2590 return DR;
2591
2592 // Reference variable, follow through to the expression that
2593 // it points to.
2594 if (V->hasInit()) {
2595 // Add the reference variable to the "trail".
2596 refVars.push_back(DR);
2597 return EvalVal(V->getInit(), refVars);
2598 }
2599 }
Mike Stump1eb44332009-09-09 15:08:12 +00002600
Ted Kremenek06de2762007-08-17 16:46:58 +00002601 return NULL;
2602 }
Mike Stump1eb44332009-09-09 15:08:12 +00002603
Ted Kremenek06de2762007-08-17 16:46:58 +00002604 case Stmt::UnaryOperatorClass: {
2605 // The only unary operator that make sense to handle here
2606 // is Deref. All others don't resolve to a "name." This includes
2607 // handling all sorts of rvalues passed to a unary operator.
2608 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002609
John McCall2de56d12010-08-25 11:45:40 +00002610 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002611 return EvalAddr(U->getSubExpr(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002612
2613 return NULL;
2614 }
Mike Stump1eb44332009-09-09 15:08:12 +00002615
Ted Kremenek06de2762007-08-17 16:46:58 +00002616 case Stmt::ArraySubscriptExprClass: {
2617 // Array subscripts are potential references to data on the stack. We
2618 // retrieve the DeclRefExpr* for the array variable if it indeed
2619 // has local storage.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002620 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002621 }
Mike Stump1eb44332009-09-09 15:08:12 +00002622
Ted Kremenek06de2762007-08-17 16:46:58 +00002623 case Stmt::ConditionalOperatorClass: {
2624 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002625 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00002626 ConditionalOperator *C = cast<ConditionalOperator>(E);
2627
Anders Carlsson39073232007-11-30 19:04:31 +00002628 // Handle the GNU extension for missing LHS.
2629 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002630 if (Expr *LHS = EvalVal(lhsExpr, refVars))
Anders Carlsson39073232007-11-30 19:04:31 +00002631 return LHS;
2632
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002633 return EvalVal(C->getRHS(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002634 }
Mike Stump1eb44332009-09-09 15:08:12 +00002635
Ted Kremenek06de2762007-08-17 16:46:58 +00002636 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00002637 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00002638 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002639
Ted Kremenek06de2762007-08-17 16:46:58 +00002640 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00002641 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00002642 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00002643
2644 // Check whether the member type is itself a reference, in which case
2645 // we're not going to refer to the member, but to what the member refers to.
2646 if (M->getMemberDecl()->getType()->isReferenceType())
2647 return NULL;
2648
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002649 return EvalVal(M->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002650 }
Mike Stump1eb44332009-09-09 15:08:12 +00002651
Douglas Gregor03e80032011-06-21 17:03:29 +00002652 case Stmt::MaterializeTemporaryExprClass:
2653 if (Expr *Result = EvalVal(
2654 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
2655 refVars))
2656 return Result;
2657
2658 return E;
2659
Ted Kremenek06de2762007-08-17 16:46:58 +00002660 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002661 // Check that we don't return or take the address of a reference to a
2662 // temporary. This is only useful in C++.
2663 if (!E->isTypeDependent() && E->isRValue())
2664 return E;
2665
2666 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00002667 return NULL;
2668 }
Ted Kremenek68957a92010-08-04 20:01:07 +00002669} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00002670}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002671
2672//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
2673
2674/// Check for comparisons of floating point operands using != and ==.
2675/// Issue a warning if these are no self-comparisons, as they are not likely
2676/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00002677void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002678 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002679
Richard Trieudd225092011-09-15 21:56:47 +00002680 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
2681 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002682
2683 // Special case: check for x == x (which is OK).
2684 // Do not emit warnings for such cases.
2685 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
2686 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
2687 if (DRL->getDecl() == DRR->getDecl())
2688 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002689
2690
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002691 // Special case: check for comparisons against literals that can be exactly
2692 // represented by APFloat. In such cases, do not emit a warning. This
2693 // is a heuristic: often comparison against such literals are used to
2694 // detect if a value in a variable has not changed. This clearly can
2695 // lead to false negatives.
2696 if (EmitWarning) {
2697 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
2698 if (FLL->isExact())
2699 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002700 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002701 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
2702 if (FLR->isExact())
2703 EmitWarning = false;
2704 }
2705 }
Mike Stump1eb44332009-09-09 15:08:12 +00002706
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002707 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002708 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002709 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002710 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002711 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002712
Sebastian Redl0eb23302009-01-19 00:08:26 +00002713 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002714 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002715 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002716 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002717
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002718 // Emit the diagnostic.
2719 if (EmitWarning)
Richard Trieudd225092011-09-15 21:56:47 +00002720 Diag(Loc, diag::warn_floatingpoint_eq)
2721 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002722}
John McCallba26e582010-01-04 23:21:16 +00002723
John McCallf2370c92010-01-06 05:24:50 +00002724//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
2725//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00002726
John McCallf2370c92010-01-06 05:24:50 +00002727namespace {
John McCallba26e582010-01-04 23:21:16 +00002728
John McCallf2370c92010-01-06 05:24:50 +00002729/// Structure recording the 'active' range of an integer-valued
2730/// expression.
2731struct IntRange {
2732 /// The number of bits active in the int.
2733 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00002734
John McCallf2370c92010-01-06 05:24:50 +00002735 /// True if the int is known not to have negative values.
2736 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00002737
John McCallf2370c92010-01-06 05:24:50 +00002738 IntRange(unsigned Width, bool NonNegative)
2739 : Width(Width), NonNegative(NonNegative)
2740 {}
John McCallba26e582010-01-04 23:21:16 +00002741
John McCall1844a6e2010-11-10 23:38:19 +00002742 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00002743 static IntRange forBoolType() {
2744 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00002745 }
2746
John McCall1844a6e2010-11-10 23:38:19 +00002747 /// Returns the range of an opaque value of the given integral type.
2748 static IntRange forValueOfType(ASTContext &C, QualType T) {
2749 return forValueOfCanonicalType(C,
2750 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00002751 }
2752
John McCall1844a6e2010-11-10 23:38:19 +00002753 /// Returns the range of an opaque value of a canonical integral type.
2754 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00002755 assert(T->isCanonicalUnqualified());
2756
2757 if (const VectorType *VT = dyn_cast<VectorType>(T))
2758 T = VT->getElementType().getTypePtr();
2759 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2760 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00002761
John McCall091f23f2010-11-09 22:22:12 +00002762 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00002763 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
2764 EnumDecl *Enum = ET->getDecl();
John McCall5e1cdac2011-10-07 06:10:15 +00002765 if (!Enum->isCompleteDefinition())
John McCall091f23f2010-11-09 22:22:12 +00002766 return IntRange(C.getIntWidth(QualType(T, 0)), false);
2767
John McCall323ed742010-05-06 08:58:33 +00002768 unsigned NumPositive = Enum->getNumPositiveBits();
2769 unsigned NumNegative = Enum->getNumNegativeBits();
2770
2771 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
2772 }
John McCallf2370c92010-01-06 05:24:50 +00002773
2774 const BuiltinType *BT = cast<BuiltinType>(T);
2775 assert(BT->isInteger());
2776
2777 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2778 }
2779
John McCall1844a6e2010-11-10 23:38:19 +00002780 /// Returns the "target" range of a canonical integral type, i.e.
2781 /// the range of values expressible in the type.
2782 ///
2783 /// This matches forValueOfCanonicalType except that enums have the
2784 /// full range of their type, not the range of their enumerators.
2785 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
2786 assert(T->isCanonicalUnqualified());
2787
2788 if (const VectorType *VT = dyn_cast<VectorType>(T))
2789 T = VT->getElementType().getTypePtr();
2790 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2791 T = CT->getElementType().getTypePtr();
2792 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00002793 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00002794
2795 const BuiltinType *BT = cast<BuiltinType>(T);
2796 assert(BT->isInteger());
2797
2798 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2799 }
2800
2801 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002802 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00002803 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00002804 L.NonNegative && R.NonNegative);
2805 }
2806
John McCall1844a6e2010-11-10 23:38:19 +00002807 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002808 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00002809 return IntRange(std::min(L.Width, R.Width),
2810 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00002811 }
2812};
2813
2814IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
2815 if (value.isSigned() && value.isNegative())
2816 return IntRange(value.getMinSignedBits(), false);
2817
2818 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002819 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00002820
2821 // isNonNegative() just checks the sign bit without considering
2822 // signedness.
2823 return IntRange(value.getActiveBits(), true);
2824}
2825
John McCall0acc3112010-01-06 22:57:21 +00002826IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCallf2370c92010-01-06 05:24:50 +00002827 unsigned MaxWidth) {
2828 if (result.isInt())
2829 return GetValueRange(C, result.getInt(), MaxWidth);
2830
2831 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00002832 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
2833 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
2834 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
2835 R = IntRange::join(R, El);
2836 }
John McCallf2370c92010-01-06 05:24:50 +00002837 return R;
2838 }
2839
2840 if (result.isComplexInt()) {
2841 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
2842 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
2843 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00002844 }
2845
2846 // This can happen with lossless casts to intptr_t of "based" lvalues.
2847 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00002848 // FIXME: The only reason we need to pass the type in here is to get
2849 // the sign right on this one case. It would be nice if APValue
2850 // preserved this.
John McCallf2370c92010-01-06 05:24:50 +00002851 assert(result.isLValue());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00002852 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00002853}
John McCallf2370c92010-01-06 05:24:50 +00002854
2855/// Pseudo-evaluate the given integer expression, estimating the
2856/// range of values it might take.
2857///
2858/// \param MaxWidth - the width to which the value will be truncated
2859IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
2860 E = E->IgnoreParens();
2861
2862 // Try a full evaluation first.
2863 Expr::EvalResult result;
2864 if (E->Evaluate(result, C))
John McCall0acc3112010-01-06 22:57:21 +00002865 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00002866
2867 // I think we only want to look through implicit casts here; if the
2868 // user has an explicit widening cast, we should treat the value as
2869 // being of the new, wider type.
2870 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00002871 if (CE->getCastKind() == CK_NoOp)
John McCallf2370c92010-01-06 05:24:50 +00002872 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
2873
John McCall1844a6e2010-11-10 23:38:19 +00002874 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00002875
John McCall2de56d12010-08-25 11:45:40 +00002876 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00002877
John McCallf2370c92010-01-06 05:24:50 +00002878 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00002879 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00002880 return OutputTypeRange;
2881
2882 IntRange SubRange
2883 = GetExprRange(C, CE->getSubExpr(),
2884 std::min(MaxWidth, OutputTypeRange.Width));
2885
2886 // Bail out if the subexpr's range is as wide as the cast type.
2887 if (SubRange.Width >= OutputTypeRange.Width)
2888 return OutputTypeRange;
2889
2890 // Otherwise, we take the smaller width, and we're non-negative if
2891 // either the output type or the subexpr is.
2892 return IntRange(SubRange.Width,
2893 SubRange.NonNegative || OutputTypeRange.NonNegative);
2894 }
2895
2896 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2897 // If we can fold the condition, just take that operand.
2898 bool CondResult;
2899 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
2900 return GetExprRange(C, CondResult ? CO->getTrueExpr()
2901 : CO->getFalseExpr(),
2902 MaxWidth);
2903
2904 // Otherwise, conservatively merge.
2905 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
2906 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
2907 return IntRange::join(L, R);
2908 }
2909
2910 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2911 switch (BO->getOpcode()) {
2912
2913 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00002914 case BO_LAnd:
2915 case BO_LOr:
2916 case BO_LT:
2917 case BO_GT:
2918 case BO_LE:
2919 case BO_GE:
2920 case BO_EQ:
2921 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00002922 return IntRange::forBoolType();
2923
John McCall862ff872011-07-13 06:35:24 +00002924 // The type of the assignments is the type of the LHS, so the RHS
2925 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00002926 case BO_MulAssign:
2927 case BO_DivAssign:
2928 case BO_RemAssign:
2929 case BO_AddAssign:
2930 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00002931 case BO_XorAssign:
2932 case BO_OrAssign:
2933 // TODO: bitfields?
John McCall1844a6e2010-11-10 23:38:19 +00002934 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00002935
John McCall862ff872011-07-13 06:35:24 +00002936 // Simple assignments just pass through the RHS, which will have
2937 // been coerced to the LHS type.
2938 case BO_Assign:
2939 // TODO: bitfields?
2940 return GetExprRange(C, BO->getRHS(), MaxWidth);
2941
John McCallf2370c92010-01-06 05:24:50 +00002942 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00002943 case BO_PtrMemD:
2944 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00002945 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002946
John McCall60fad452010-01-06 22:07:33 +00002947 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00002948 case BO_And:
2949 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00002950 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
2951 GetExprRange(C, BO->getRHS(), MaxWidth));
2952
John McCallf2370c92010-01-06 05:24:50 +00002953 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00002954 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00002955 // ...except that we want to treat '1 << (blah)' as logically
2956 // positive. It's an important idiom.
2957 if (IntegerLiteral *I
2958 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
2959 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00002960 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00002961 return IntRange(R.Width, /*NonNegative*/ true);
2962 }
2963 }
2964 // fallthrough
2965
John McCall2de56d12010-08-25 11:45:40 +00002966 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00002967 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002968
John McCall60fad452010-01-06 22:07:33 +00002969 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00002970 case BO_Shr:
2971 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00002972 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2973
2974 // If the shift amount is a positive constant, drop the width by
2975 // that much.
2976 llvm::APSInt shift;
2977 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
2978 shift.isNonNegative()) {
2979 unsigned zext = shift.getZExtValue();
2980 if (zext >= L.Width)
2981 L.Width = (L.NonNegative ? 0 : 1);
2982 else
2983 L.Width -= zext;
2984 }
2985
2986 return L;
2987 }
2988
2989 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00002990 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00002991 return GetExprRange(C, BO->getRHS(), MaxWidth);
2992
John McCall60fad452010-01-06 22:07:33 +00002993 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00002994 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00002995 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00002996 return IntRange::forValueOfType(C, E->getType());
John McCall00fe7612011-07-14 22:39:48 +00002997 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002998
John McCall00fe7612011-07-14 22:39:48 +00002999 // The width of a division result is mostly determined by the size
3000 // of the LHS.
3001 case BO_Div: {
3002 // Don't 'pre-truncate' the operands.
3003 unsigned opWidth = C.getIntWidth(E->getType());
3004 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3005
3006 // If the divisor is constant, use that.
3007 llvm::APSInt divisor;
3008 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
3009 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
3010 if (log2 >= L.Width)
3011 L.Width = (L.NonNegative ? 0 : 1);
3012 else
3013 L.Width = std::min(L.Width - log2, MaxWidth);
3014 return L;
3015 }
3016
3017 // Otherwise, just use the LHS's width.
3018 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3019 return IntRange(L.Width, L.NonNegative && R.NonNegative);
3020 }
3021
3022 // The result of a remainder can't be larger than the result of
3023 // either side.
3024 case BO_Rem: {
3025 // Don't 'pre-truncate' the operands.
3026 unsigned opWidth = C.getIntWidth(E->getType());
3027 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3028 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3029
3030 IntRange meet = IntRange::meet(L, R);
3031 meet.Width = std::min(meet.Width, MaxWidth);
3032 return meet;
3033 }
3034
3035 // The default behavior is okay for these.
3036 case BO_Mul:
3037 case BO_Add:
3038 case BO_Xor:
3039 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00003040 break;
3041 }
3042
John McCall00fe7612011-07-14 22:39:48 +00003043 // The default case is to treat the operation as if it were closed
3044 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00003045 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3046 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
3047 return IntRange::join(L, R);
3048 }
3049
3050 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
3051 switch (UO->getOpcode()) {
3052 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00003053 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00003054 return IntRange::forBoolType();
3055
3056 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00003057 case UO_Deref:
3058 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00003059 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003060
3061 default:
3062 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
3063 }
3064 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003065
3066 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00003067 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003068 }
John McCallf2370c92010-01-06 05:24:50 +00003069
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003070 if (FieldDecl *BitField = E->getBitField())
3071 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00003072 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00003073
John McCall1844a6e2010-11-10 23:38:19 +00003074 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003075}
John McCall51313c32010-01-04 23:31:57 +00003076
John McCall323ed742010-05-06 08:58:33 +00003077IntRange GetExprRange(ASTContext &C, Expr *E) {
3078 return GetExprRange(C, E, C.getIntWidth(E->getType()));
3079}
3080
John McCall51313c32010-01-04 23:31:57 +00003081/// Checks whether the given value, which currently has the given
3082/// source semantics, has the same value when coerced through the
3083/// target semantics.
John McCallf2370c92010-01-06 05:24:50 +00003084bool IsSameFloatAfterCast(const llvm::APFloat &value,
3085 const llvm::fltSemantics &Src,
3086 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00003087 llvm::APFloat truncated = value;
3088
3089 bool ignored;
3090 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
3091 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
3092
3093 return truncated.bitwiseIsEqual(value);
3094}
3095
3096/// Checks whether the given value, which currently has the given
3097/// source semantics, has the same value when coerced through the
3098/// target semantics.
3099///
3100/// The value might be a vector of floats (or a complex number).
John McCallf2370c92010-01-06 05:24:50 +00003101bool IsSameFloatAfterCast(const APValue &value,
3102 const llvm::fltSemantics &Src,
3103 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00003104 if (value.isFloat())
3105 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
3106
3107 if (value.isVector()) {
3108 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
3109 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
3110 return false;
3111 return true;
3112 }
3113
3114 assert(value.isComplexFloat());
3115 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
3116 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
3117}
3118
John McCallb4eb64d2010-10-08 02:01:28 +00003119void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00003120
Ted Kremeneke3b159c2010-09-23 21:43:44 +00003121static bool IsZero(Sema &S, Expr *E) {
3122 // Suppress cases where we are comparing against an enum constant.
3123 if (const DeclRefExpr *DR =
3124 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
3125 if (isa<EnumConstantDecl>(DR->getDecl()))
3126 return false;
3127
3128 // Suppress cases where the '0' value is expanded from a macro.
3129 if (E->getLocStart().isMacroID())
3130 return false;
3131
John McCall323ed742010-05-06 08:58:33 +00003132 llvm::APSInt Value;
3133 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
3134}
3135
John McCall372e1032010-10-06 00:25:24 +00003136static bool HasEnumType(Expr *E) {
3137 // Strip off implicit integral promotions.
3138 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00003139 if (ICE->getCastKind() != CK_IntegralCast &&
3140 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00003141 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00003142 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00003143 }
3144
3145 return E->getType()->isEnumeralType();
3146}
3147
John McCall323ed742010-05-06 08:58:33 +00003148void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003149 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00003150 if (E->isValueDependent())
3151 return;
3152
John McCall2de56d12010-08-25 11:45:40 +00003153 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00003154 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003155 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00003156 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003157 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00003158 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003159 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00003160 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003161 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00003162 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003163 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00003164 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003165 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00003166 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003167 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00003168 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3169 }
3170}
3171
3172/// Analyze the operands of the given comparison. Implements the
3173/// fallback case from AnalyzeComparison.
3174void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00003175 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3176 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00003177}
John McCall51313c32010-01-04 23:31:57 +00003178
John McCallba26e582010-01-04 23:21:16 +00003179/// \brief Implements -Wsign-compare.
3180///
Richard Trieudd225092011-09-15 21:56:47 +00003181/// \param E the binary operator to check for warnings
John McCall323ed742010-05-06 08:58:33 +00003182void AnalyzeComparison(Sema &S, BinaryOperator *E) {
3183 // The type the comparison is being performed in.
3184 QualType T = E->getLHS()->getType();
3185 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
3186 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00003187
John McCall323ed742010-05-06 08:58:33 +00003188 // We don't do anything special if this isn't an unsigned integral
3189 // comparison: we're only interested in integral comparisons, and
3190 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00003191 //
3192 // We also don't care about value-dependent expressions or expressions
3193 // whose result is a constant.
3194 if (!T->hasUnsignedIntegerRepresentation()
3195 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCall323ed742010-05-06 08:58:33 +00003196 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00003197
Richard Trieudd225092011-09-15 21:56:47 +00003198 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
3199 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00003200
John McCall323ed742010-05-06 08:58:33 +00003201 // Check to see if one of the (unmodified) operands is of different
3202 // signedness.
3203 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00003204 if (LHS->getType()->hasSignedIntegerRepresentation()) {
3205 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00003206 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00003207 signedOperand = LHS;
3208 unsignedOperand = RHS;
3209 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
3210 signedOperand = RHS;
3211 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00003212 } else {
John McCall323ed742010-05-06 08:58:33 +00003213 CheckTrivialUnsignedComparison(S, E);
3214 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00003215 }
3216
John McCall323ed742010-05-06 08:58:33 +00003217 // Otherwise, calculate the effective range of the signed operand.
3218 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00003219
John McCall323ed742010-05-06 08:58:33 +00003220 // Go ahead and analyze implicit conversions in the operands. Note
3221 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00003222 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
3223 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00003224
John McCall323ed742010-05-06 08:58:33 +00003225 // If the signed range is non-negative, -Wsign-compare won't fire,
3226 // but we should still check for comparisons which are always true
3227 // or false.
3228 if (signedRange.NonNegative)
3229 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00003230
3231 // For (in)equality comparisons, if the unsigned operand is a
3232 // constant which cannot collide with a overflowed signed operand,
3233 // then reinterpreting the signed operand as unsigned will not
3234 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00003235 if (E->isEqualityOp()) {
3236 unsigned comparisonWidth = S.Context.getIntWidth(T);
3237 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00003238
John McCall323ed742010-05-06 08:58:33 +00003239 // We should never be unable to prove that the unsigned operand is
3240 // non-negative.
3241 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
3242
3243 if (unsignedRange.Width < comparisonWidth)
3244 return;
3245 }
3246
3247 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
Richard Trieudd225092011-09-15 21:56:47 +00003248 << LHS->getType() << RHS->getType()
3249 << LHS->getSourceRange() << RHS->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00003250}
3251
John McCall15d7d122010-11-11 03:21:53 +00003252/// Analyzes an attempt to assign the given value to a bitfield.
3253///
3254/// Returns true if there was something fishy about the attempt.
3255bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
3256 SourceLocation InitLoc) {
3257 assert(Bitfield->isBitField());
3258 if (Bitfield->isInvalidDecl())
3259 return false;
3260
John McCall91b60142010-11-11 05:33:51 +00003261 // White-list bool bitfields.
3262 if (Bitfield->getType()->isBooleanType())
3263 return false;
3264
Douglas Gregor46ff3032011-02-04 13:09:01 +00003265 // Ignore value- or type-dependent expressions.
3266 if (Bitfield->getBitWidth()->isValueDependent() ||
3267 Bitfield->getBitWidth()->isTypeDependent() ||
3268 Init->isValueDependent() ||
3269 Init->isTypeDependent())
3270 return false;
3271
John McCall15d7d122010-11-11 03:21:53 +00003272 Expr *OriginalInit = Init->IgnoreParenImpCasts();
3273
John McCall15d7d122010-11-11 03:21:53 +00003274 Expr::EvalResult InitValue;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003275 if (!OriginalInit->Evaluate(InitValue, S.Context) ||
John McCall15d7d122010-11-11 03:21:53 +00003276 !InitValue.Val.isInt())
3277 return false;
3278
3279 const llvm::APSInt &Value = InitValue.Val.getInt();
3280 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003281 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00003282
3283 if (OriginalWidth <= FieldWidth)
3284 return false;
3285
Jay Foad9f71a8f2010-12-07 08:25:34 +00003286 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
John McCall15d7d122010-11-11 03:21:53 +00003287
3288 // It's fairly common to write values into signed bitfields
3289 // that, if sign-extended, would end up becoming a different
3290 // value. We don't want to warn about that.
3291 if (Value.isSigned() && Value.isNegative())
Jay Foad9f71a8f2010-12-07 08:25:34 +00003292 TruncatedValue = TruncatedValue.sext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00003293 else
Jay Foad9f71a8f2010-12-07 08:25:34 +00003294 TruncatedValue = TruncatedValue.zext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00003295
3296 if (Value == TruncatedValue)
3297 return false;
3298
3299 std::string PrettyValue = Value.toString(10);
3300 std::string PrettyTrunc = TruncatedValue.toString(10);
3301
3302 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
3303 << PrettyValue << PrettyTrunc << OriginalInit->getType()
3304 << Init->getSourceRange();
3305
3306 return true;
3307}
3308
John McCallbeb22aa2010-11-09 23:24:47 +00003309/// Analyze the given simple or compound assignment for warning-worthy
3310/// operations.
3311void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
3312 // Just recurse on the LHS.
3313 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3314
3315 // We want to recurse on the RHS as normal unless we're assigning to
3316 // a bitfield.
3317 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00003318 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
3319 E->getOperatorLoc())) {
3320 // Recurse, ignoring any implicit conversions on the RHS.
3321 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
3322 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00003323 }
3324 }
3325
3326 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
3327}
3328
John McCall51313c32010-01-04 23:31:57 +00003329/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003330void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
3331 SourceLocation CContext, unsigned diag) {
3332 S.Diag(E->getExprLoc(), diag)
3333 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
3334}
3335
Chandler Carruthe1b02e02011-04-05 06:47:57 +00003336/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
3337void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
3338 unsigned diag) {
3339 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag);
3340}
3341
Chandler Carruthf65076e2011-04-10 08:36:24 +00003342/// Diagnose an implicit cast from a literal expression. Also attemps to supply
3343/// fixit hints when the cast wouldn't lose information to simply write the
3344/// expression with the expected type.
3345void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
3346 SourceLocation CContext) {
3347 // Emit the primary warning first, then try to emit a fixit hint note if
3348 // reasonable.
3349 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
3350 << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext);
3351
3352 const llvm::APFloat &Value = FL->getValue();
3353
3354 // Don't attempt to fix PPC double double literals.
3355 if (&Value.getSemantics() == &llvm::APFloat::PPCDoubleDouble)
3356 return;
3357
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00003358 // Try to convert this exactly to an integer.
Chandler Carruthf65076e2011-04-10 08:36:24 +00003359 bool isExact = false;
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00003360 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
3361 T->hasUnsignedIntegerRepresentation());
3362 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00003363 llvm::APFloat::rmTowardZero, &isExact)
3364 != llvm::APFloat::opOK || !isExact)
3365 return;
3366
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00003367 std::string LiteralValue = IntegerValue.toString(10);
Chandler Carruthf65076e2011-04-10 08:36:24 +00003368 S.Diag(FL->getExprLoc(), diag::note_fix_integral_float_as_integer)
3369 << FixItHint::CreateReplacement(FL->getSourceRange(), LiteralValue);
3370}
3371
John McCall091f23f2010-11-09 22:22:12 +00003372std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
3373 if (!Range.Width) return "0";
3374
3375 llvm::APSInt ValueInRange = Value;
3376 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00003377 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00003378 return ValueInRange.toString(10);
3379}
3380
Ted Kremenekef9ff882011-03-10 20:03:42 +00003381static bool isFromSystemMacro(Sema &S, SourceLocation loc) {
3382 SourceManager &smgr = S.Context.getSourceManager();
3383 return loc.isMacroID() && smgr.isInSystemHeader(smgr.getSpellingLoc(loc));
3384}
Chandler Carruthf65076e2011-04-10 08:36:24 +00003385
John McCall323ed742010-05-06 08:58:33 +00003386void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00003387 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00003388 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00003389
John McCall323ed742010-05-06 08:58:33 +00003390 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
3391 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
3392 if (Source == Target) return;
3393 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00003394
Chandler Carruth108f7562011-07-26 05:40:03 +00003395 // If the conversion context location is invalid don't complain. We also
3396 // don't want to emit a warning if the issue occurs from the expansion of
3397 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
3398 // delay this check as long as possible. Once we detect we are in that
3399 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00003400 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00003401 return;
3402
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00003403 // Diagnose implicit casts to bool.
3404 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
3405 if (isa<StringLiteral>(E))
3406 // Warn on string literal to bool. Checks for string literals in logical
3407 // expressions, for instances, assert(0 && "error here"), is prevented
3408 // by a check in AnalyzeImplicitConversions().
3409 return DiagnoseImpCast(S, E, T, CC,
3410 diag::warn_impcast_string_literal_to_bool);
David Blaikiee37cdc42011-09-29 04:06:47 +00003411 return; // Other casts to bool are not checked.
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00003412 }
John McCall51313c32010-01-04 23:31:57 +00003413
3414 // Strip vector types.
3415 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003416 if (!isa<VectorType>(Target)) {
3417 if (isFromSystemMacro(S, CC))
3418 return;
John McCallb4eb64d2010-10-08 02:01:28 +00003419 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003420 }
Chris Lattnerb792b302011-06-14 04:51:15 +00003421
3422 // If the vector cast is cast between two vectors of the same size, it is
3423 // a bitcast, not a conversion.
3424 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
3425 return;
John McCall51313c32010-01-04 23:31:57 +00003426
3427 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
3428 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
3429 }
3430
3431 // Strip complex types.
3432 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003433 if (!isa<ComplexType>(Target)) {
3434 if (isFromSystemMacro(S, CC))
3435 return;
3436
John McCallb4eb64d2010-10-08 02:01:28 +00003437 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003438 }
John McCall51313c32010-01-04 23:31:57 +00003439
3440 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
3441 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
3442 }
3443
3444 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
3445 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
3446
3447 // If the source is floating point...
3448 if (SourceBT && SourceBT->isFloatingPoint()) {
3449 // ...and the target is floating point...
3450 if (TargetBT && TargetBT->isFloatingPoint()) {
3451 // ...then warn if we're dropping FP rank.
3452
3453 // Builtin FP kinds are ordered by increasing FP rank.
3454 if (SourceBT->getKind() > TargetBT->getKind()) {
3455 // Don't warn about float constants that are precisely
3456 // representable in the target type.
3457 Expr::EvalResult result;
John McCall323ed742010-05-06 08:58:33 +00003458 if (E->Evaluate(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00003459 // Value might be a float, a float vector, or a float complex.
3460 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00003461 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
3462 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00003463 return;
3464 }
3465
Ted Kremenekef9ff882011-03-10 20:03:42 +00003466 if (isFromSystemMacro(S, CC))
3467 return;
3468
John McCallb4eb64d2010-10-08 02:01:28 +00003469 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00003470 }
3471 return;
3472 }
3473
Ted Kremenekef9ff882011-03-10 20:03:42 +00003474 // If the target is integral, always warn.
Chandler Carrutha5b93322011-02-17 11:05:49 +00003475 if ((TargetBT && TargetBT->isInteger())) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003476 if (isFromSystemMacro(S, CC))
3477 return;
3478
Chandler Carrutha5b93322011-02-17 11:05:49 +00003479 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00003480 // We also want to warn on, e.g., "int i = -1.234"
3481 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
3482 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
3483 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
3484
Chandler Carruthf65076e2011-04-10 08:36:24 +00003485 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
3486 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00003487 } else {
3488 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
3489 }
3490 }
John McCall51313c32010-01-04 23:31:57 +00003491
3492 return;
3493 }
3494
John McCallf2370c92010-01-06 05:24:50 +00003495 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00003496 return;
3497
Richard Trieu1838ca52011-05-29 19:59:02 +00003498 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
3499 == Expr::NPCK_GNUNull) && Target->isIntegerType()) {
3500 S.Diag(E->getExprLoc(), diag::warn_impcast_null_pointer_to_integer)
3501 << E->getSourceRange() << clang::SourceRange(CC);
3502 return;
3503 }
3504
John McCall323ed742010-05-06 08:58:33 +00003505 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00003506 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00003507
3508 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00003509 // If the source is a constant, use a default-on diagnostic.
3510 // TODO: this should happen for bitfield stores, too.
3511 llvm::APSInt Value(32);
3512 if (E->isIntegerConstantExpr(Value, S.Context)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003513 if (isFromSystemMacro(S, CC))
3514 return;
3515
John McCall091f23f2010-11-09 22:22:12 +00003516 std::string PrettySourceValue = Value.toString(10);
3517 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
3518
3519 S.Diag(E->getExprLoc(), diag::warn_impcast_integer_precision_constant)
3520 << PrettySourceValue << PrettyTargetValue
3521 << E->getType() << T << E->getSourceRange() << clang::SourceRange(CC);
3522 return;
3523 }
3524
Chris Lattnerb792b302011-06-14 04:51:15 +00003525 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
Ted Kremenekef9ff882011-03-10 20:03:42 +00003526 if (isFromSystemMacro(S, CC))
3527 return;
3528
John McCallf2370c92010-01-06 05:24:50 +00003529 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCallb4eb64d2010-10-08 02:01:28 +00003530 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32);
3531 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00003532 }
3533
3534 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
3535 (!TargetRange.NonNegative && SourceRange.NonNegative &&
3536 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003537
3538 if (isFromSystemMacro(S, CC))
3539 return;
3540
John McCall323ed742010-05-06 08:58:33 +00003541 unsigned DiagID = diag::warn_impcast_integer_sign;
3542
3543 // Traditionally, gcc has warned about this under -Wsign-compare.
3544 // We also want to warn about it in -Wconversion.
3545 // So if -Wconversion is off, use a completely identical diagnostic
3546 // in the sign-compare group.
3547 // The conditional-checking code will
3548 if (ICContext) {
3549 DiagID = diag::warn_impcast_integer_sign_conditional;
3550 *ICContext = true;
3551 }
3552
John McCallb4eb64d2010-10-08 02:01:28 +00003553 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00003554 }
3555
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003556 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003557 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
3558 // type, to give us better diagnostics.
3559 QualType SourceType = E->getType();
3560 if (!S.getLangOptions().CPlusPlus) {
3561 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3562 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3563 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
3564 SourceType = S.Context.getTypeDeclType(Enum);
3565 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
3566 }
3567 }
3568
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003569 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
3570 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
3571 if ((SourceEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00003572 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003573 (TargetEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00003574 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00003575 SourceEnum != TargetEnum) {
3576 if (isFromSystemMacro(S, CC))
3577 return;
3578
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003579 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003580 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003581 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003582
John McCall51313c32010-01-04 23:31:57 +00003583 return;
3584}
3585
John McCall323ed742010-05-06 08:58:33 +00003586void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
3587
3588void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00003589 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00003590 E = E->IgnoreParenImpCasts();
3591
3592 if (isa<ConditionalOperator>(E))
3593 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
3594
John McCallb4eb64d2010-10-08 02:01:28 +00003595 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003596 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00003597 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00003598 return;
3599}
3600
3601void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00003602 SourceLocation CC = E->getQuestionLoc();
3603
3604 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00003605
3606 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00003607 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
3608 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003609
3610 // If -Wconversion would have warned about either of the candidates
3611 // for a signedness conversion to the context type...
3612 if (!Suspicious) return;
3613
3614 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003615 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
3616 CC))
John McCall323ed742010-05-06 08:58:33 +00003617 return;
3618
John McCall323ed742010-05-06 08:58:33 +00003619 // ...then check whether it would have warned about either of the
3620 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00003621 if (E->getType() == T) return;
3622
3623 Suspicious = false;
3624 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
3625 E->getType(), CC, &Suspicious);
3626 if (!Suspicious)
3627 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00003628 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003629}
3630
3631/// AnalyzeImplicitConversions - Find and report any interesting
3632/// implicit conversions in the given expression. There are a couple
3633/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00003634void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00003635 QualType T = OrigE->getType();
3636 Expr *E = OrigE->IgnoreParenImpCasts();
3637
Douglas Gregorf8b6e152011-10-10 17:38:18 +00003638 if (E->isTypeDependent() || E->isValueDependent())
3639 return;
3640
John McCall323ed742010-05-06 08:58:33 +00003641 // For conditional operators, we analyze the arguments as if they
3642 // were being fed directly into the output.
3643 if (isa<ConditionalOperator>(E)) {
3644 ConditionalOperator *CO = cast<ConditionalOperator>(E);
3645 CheckConditionalOperator(S, CO, T);
3646 return;
3647 }
3648
3649 // Go ahead and check any implicit conversions we might have skipped.
3650 // The non-canonical typecheck is just an optimization;
3651 // CheckImplicitConversion will filter out dead implicit conversions.
3652 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00003653 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00003654
3655 // Now continue drilling into this expression.
3656
3657 // Skip past explicit casts.
3658 if (isa<ExplicitCastExpr>(E)) {
3659 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00003660 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003661 }
3662
John McCallbeb22aa2010-11-09 23:24:47 +00003663 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3664 // Do a somewhat different check with comparison operators.
3665 if (BO->isComparisonOp())
3666 return AnalyzeComparison(S, BO);
3667
3668 // And with assignments and compound assignments.
3669 if (BO->isAssignmentOp())
3670 return AnalyzeAssignment(S, BO);
3671 }
John McCall323ed742010-05-06 08:58:33 +00003672
3673 // These break the otherwise-useful invariant below. Fortunately,
3674 // we don't really need to recurse into them, because any internal
3675 // expressions should have been analyzed already when they were
3676 // built into statements.
3677 if (isa<StmtExpr>(E)) return;
3678
3679 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003680 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00003681
3682 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00003683 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00003684 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
3685 bool IsLogicalOperator = BO && BO->isLogicalOp();
3686 for (Stmt::child_range I = E->children(); I; ++I) {
3687 Expr *ChildExpr = cast<Expr>(*I);
3688 if (IsLogicalOperator &&
3689 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
3690 // Ignore checking string literals that are in logical operators.
3691 continue;
3692 AnalyzeImplicitConversions(S, ChildExpr, CC);
3693 }
John McCall323ed742010-05-06 08:58:33 +00003694}
3695
3696} // end anonymous namespace
3697
3698/// Diagnoses "dangerous" implicit conversions within the given
3699/// expression (which is a full expression). Implements -Wconversion
3700/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00003701///
3702/// \param CC the "context" location of the implicit conversion, i.e.
3703/// the most location of the syntactic entity requiring the implicit
3704/// conversion
3705void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00003706 // Don't diagnose in unevaluated contexts.
3707 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
3708 return;
3709
3710 // Don't diagnose for value- or type-dependent expressions.
3711 if (E->isTypeDependent() || E->isValueDependent())
3712 return;
3713
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003714 // Check for array bounds violations in cases where the check isn't triggered
3715 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
3716 // ArraySubscriptExpr is on the RHS of a variable initialization.
3717 CheckArrayAccess(E);
3718
John McCallb4eb64d2010-10-08 02:01:28 +00003719 // This is not the right CC for (e.g.) a variable initialization.
3720 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003721}
3722
John McCall15d7d122010-11-11 03:21:53 +00003723void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
3724 FieldDecl *BitField,
3725 Expr *Init) {
3726 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
3727}
3728
Mike Stumpf8c49212010-01-21 03:59:47 +00003729/// CheckParmsForFunctionDef - Check that the parameters of the given
3730/// function are appropriate for the definition of a function. This
3731/// takes care of any checks that cannot be performed on the
3732/// declaration itself, e.g., that the types of each of the function
3733/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00003734bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
3735 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00003736 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00003737 for (; P != PEnd; ++P) {
3738 ParmVarDecl *Param = *P;
3739
Mike Stumpf8c49212010-01-21 03:59:47 +00003740 // C99 6.7.5.3p4: the parameters in a parameter type list in a
3741 // function declarator that is part of a function definition of
3742 // that function shall not have incomplete type.
3743 //
3744 // This is also C++ [dcl.fct]p6.
3745 if (!Param->isInvalidDecl() &&
3746 RequireCompleteType(Param->getLocation(), Param->getType(),
3747 diag::err_typecheck_decl_incomplete_type)) {
3748 Param->setInvalidDecl();
3749 HasInvalidParm = true;
3750 }
3751
3752 // C99 6.9.1p5: If the declarator includes a parameter type list, the
3753 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00003754 if (CheckParameterNames &&
3755 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00003756 !Param->isImplicit() &&
3757 !getLangOptions().CPlusPlus)
3758 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00003759
3760 // C99 6.7.5.3p12:
3761 // If the function declarator is not part of a definition of that
3762 // function, parameters may have incomplete type and may use the [*]
3763 // notation in their sequences of declarator specifiers to specify
3764 // variable length array types.
3765 QualType PType = Param->getOriginalType();
3766 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
3767 if (AT->getSizeModifier() == ArrayType::Star) {
3768 // FIXME: This diagnosic should point the the '[*]' if source-location
3769 // information is added for it.
3770 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
3771 }
3772 }
Mike Stumpf8c49212010-01-21 03:59:47 +00003773 }
3774
3775 return HasInvalidParm;
3776}
John McCallb7f4ffe2010-08-12 21:44:57 +00003777
3778/// CheckCastAlign - Implements -Wcast-align, which warns when a
3779/// pointer cast increases the alignment requirements.
3780void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
3781 // This is actually a lot of work to potentially be doing on every
3782 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003783 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
3784 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00003785 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00003786 return;
3787
3788 // Ignore dependent types.
3789 if (T->isDependentType() || Op->getType()->isDependentType())
3790 return;
3791
3792 // Require that the destination be a pointer type.
3793 const PointerType *DestPtr = T->getAs<PointerType>();
3794 if (!DestPtr) return;
3795
3796 // If the destination has alignment 1, we're done.
3797 QualType DestPointee = DestPtr->getPointeeType();
3798 if (DestPointee->isIncompleteType()) return;
3799 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
3800 if (DestAlign.isOne()) return;
3801
3802 // Require that the source be a pointer type.
3803 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
3804 if (!SrcPtr) return;
3805 QualType SrcPointee = SrcPtr->getPointeeType();
3806
3807 // Whitelist casts from cv void*. We already implicitly
3808 // whitelisted casts to cv void*, since they have alignment 1.
3809 // Also whitelist casts involving incomplete types, which implicitly
3810 // includes 'void'.
3811 if (SrcPointee->isIncompleteType()) return;
3812
3813 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
3814 if (SrcAlign >= DestAlign) return;
3815
3816 Diag(TRange.getBegin(), diag::warn_cast_align)
3817 << Op->getType() << T
3818 << static_cast<unsigned>(SrcAlign.getQuantity())
3819 << static_cast<unsigned>(DestAlign.getQuantity())
3820 << TRange << Op->getSourceRange();
3821}
3822
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003823static const Type* getElementType(const Expr *BaseExpr) {
3824 const Type* EltType = BaseExpr->getType().getTypePtr();
3825 if (EltType->isAnyPointerType())
3826 return EltType->getPointeeType().getTypePtr();
3827 else if (EltType->isArrayType())
3828 return EltType->getBaseElementTypeUnsafe();
3829 return EltType;
3830}
3831
Chandler Carruthc2684342011-08-05 09:10:50 +00003832/// \brief Check whether this array fits the idiom of a size-one tail padded
3833/// array member of a struct.
3834///
3835/// We avoid emitting out-of-bounds access warnings for such arrays as they are
3836/// commonly used to emulate flexible arrays in C89 code.
3837static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
3838 const NamedDecl *ND) {
3839 if (Size != 1 || !ND) return false;
3840
3841 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
3842 if (!FD) return false;
3843
3844 // Don't consider sizes resulting from macro expansions or template argument
3845 // substitution to form C89 tail-padded arrays.
3846 ConstantArrayTypeLoc TL =
3847 cast<ConstantArrayTypeLoc>(FD->getTypeSourceInfo()->getTypeLoc());
3848 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(TL.getSizeExpr());
3849 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
3850 return false;
3851
3852 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
3853 if (!RD || !RD->isStruct())
3854 return false;
3855
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00003856 // See if this is the last field decl in the record.
3857 const Decl *D = FD;
3858 while ((D = D->getNextDeclInContext()))
3859 if (isa<FieldDecl>(D))
3860 return false;
3861 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00003862}
3863
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003864void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
3865 bool isSubscript, bool AllowOnePastEnd) {
3866 const Type* EffectiveType = getElementType(BaseExpr);
3867 BaseExpr = BaseExpr->IgnoreParenCasts();
3868 IndexExpr = IndexExpr->IgnoreParenCasts();
3869
Chandler Carruth34064582011-02-17 20:55:08 +00003870 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003871 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00003872 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00003873 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00003874
Chandler Carruth34064582011-02-17 20:55:08 +00003875 if (IndexExpr->isValueDependent())
Ted Kremeneka0125d82011-02-16 01:57:07 +00003876 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003877 llvm::APSInt index;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003878 if (!IndexExpr->isIntegerConstantExpr(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00003879 return;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00003880
Chandler Carruthba447122011-08-05 08:07:29 +00003881 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00003882 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
3883 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00003884 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00003885 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00003886
Ted Kremenek9e060ca2011-02-23 23:06:04 +00003887 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00003888 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00003889 if (!size.isStrictlyPositive())
3890 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003891
3892 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00003893 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003894 // Make sure we're comparing apples to apples when comparing index to size
3895 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
3896 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00003897 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00003898 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003899 if (ptrarith_typesize != array_typesize) {
3900 // There's a cast to a different size type involved
3901 uint64_t ratio = array_typesize / ptrarith_typesize;
3902 // TODO: Be smarter about handling cases where array_typesize is not a
3903 // multiple of ptrarith_typesize
3904 if (ptrarith_typesize * ratio == array_typesize)
3905 size *= llvm::APInt(size.getBitWidth(), ratio);
3906 }
3907 }
3908
Chandler Carruth34064582011-02-17 20:55:08 +00003909 if (size.getBitWidth() > index.getBitWidth())
3910 index = index.sext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00003911 else if (size.getBitWidth() < index.getBitWidth())
3912 size = size.sext(index.getBitWidth());
3913
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003914 // For array subscripting the index must be less than size, but for pointer
3915 // arithmetic also allow the index (offset) to be equal to size since
3916 // computing the next address after the end of the array is legal and
3917 // commonly done e.g. in C++ iterators and range-based for loops.
3918 if (AllowOnePastEnd ? index.sle(size) : index.slt(size))
Chandler Carruthba447122011-08-05 08:07:29 +00003919 return;
3920
3921 // Also don't warn for arrays of size 1 which are members of some
3922 // structure. These are often used to approximate flexible arrays in C89
3923 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003924 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00003925 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003926
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003927 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
3928 if (isSubscript)
3929 DiagID = diag::warn_array_index_exceeds_bounds;
3930
3931 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
3932 PDiag(DiagID) << index.toString(10, true)
3933 << size.toString(10, true)
3934 << (unsigned)size.getLimitedValue(~0U)
3935 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00003936 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003937 unsigned DiagID = diag::warn_array_index_precedes_bounds;
3938 if (!isSubscript) {
3939 DiagID = diag::warn_ptr_arith_precedes_bounds;
3940 if (index.isNegative()) index = -index;
3941 }
3942
3943 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
3944 PDiag(DiagID) << index.toString(10, true)
3945 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00003946 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00003947
Chandler Carruth35001ca2011-02-17 21:10:52 +00003948 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003949 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
3950 PDiag(diag::note_array_index_out_of_bounds)
3951 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00003952}
3953
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003954void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003955 int AllowOnePastEnd = 0;
3956 while (expr) {
3957 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003958 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003959 case Stmt::ArraySubscriptExprClass: {
3960 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
3961 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), true,
3962 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003963 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003964 }
3965 case Stmt::UnaryOperatorClass: {
3966 // Only unwrap the * and & unary operators
3967 const UnaryOperator *UO = cast<UnaryOperator>(expr);
3968 expr = UO->getSubExpr();
3969 switch (UO->getOpcode()) {
3970 case UO_AddrOf:
3971 AllowOnePastEnd++;
3972 break;
3973 case UO_Deref:
3974 AllowOnePastEnd--;
3975 break;
3976 default:
3977 return;
3978 }
3979 break;
3980 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003981 case Stmt::ConditionalOperatorClass: {
3982 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
3983 if (const Expr *lhs = cond->getLHS())
3984 CheckArrayAccess(lhs);
3985 if (const Expr *rhs = cond->getRHS())
3986 CheckArrayAccess(rhs);
3987 return;
3988 }
3989 default:
3990 return;
3991 }
Peter Collingbournef111d932011-04-15 00:35:48 +00003992 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003993}
John McCallf85e1932011-06-15 23:02:42 +00003994
3995//===--- CHECK: Objective-C retain cycles ----------------------------------//
3996
3997namespace {
3998 struct RetainCycleOwner {
3999 RetainCycleOwner() : Variable(0), Indirect(false) {}
4000 VarDecl *Variable;
4001 SourceRange Range;
4002 SourceLocation Loc;
4003 bool Indirect;
4004
4005 void setLocsFrom(Expr *e) {
4006 Loc = e->getExprLoc();
4007 Range = e->getSourceRange();
4008 }
4009 };
4010}
4011
4012/// Consider whether capturing the given variable can possibly lead to
4013/// a retain cycle.
4014static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
4015 // In ARC, it's captured strongly iff the variable has __strong
4016 // lifetime. In MRR, it's captured strongly if the variable is
4017 // __block and has an appropriate type.
4018 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4019 return false;
4020
4021 owner.Variable = var;
4022 owner.setLocsFrom(ref);
4023 return true;
4024}
4025
4026static bool findRetainCycleOwner(Expr *e, RetainCycleOwner &owner) {
4027 while (true) {
4028 e = e->IgnoreParens();
4029 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
4030 switch (cast->getCastKind()) {
4031 case CK_BitCast:
4032 case CK_LValueBitCast:
4033 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00004034 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00004035 e = cast->getSubExpr();
4036 continue;
4037
4038 case CK_GetObjCProperty: {
4039 // Bail out if this isn't a strong explicit property.
4040 const ObjCPropertyRefExpr *pre = cast->getSubExpr()->getObjCProperty();
4041 if (pre->isImplicitProperty()) return false;
4042 ObjCPropertyDecl *property = pre->getExplicitProperty();
John McCall265941b2011-09-13 18:31:23 +00004043 if (!property->isRetaining() &&
John McCallf85e1932011-06-15 23:02:42 +00004044 !(property->getPropertyIvarDecl() &&
4045 property->getPropertyIvarDecl()->getType()
4046 .getObjCLifetime() == Qualifiers::OCL_Strong))
4047 return false;
4048
4049 owner.Indirect = true;
4050 e = const_cast<Expr*>(pre->getBase());
4051 continue;
4052 }
4053
4054 default:
4055 return false;
4056 }
4057 }
4058
4059 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
4060 ObjCIvarDecl *ivar = ref->getDecl();
4061 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4062 return false;
4063
4064 // Try to find a retain cycle in the base.
4065 if (!findRetainCycleOwner(ref->getBase(), owner))
4066 return false;
4067
4068 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
4069 owner.Indirect = true;
4070 return true;
4071 }
4072
4073 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
4074 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
4075 if (!var) return false;
4076 return considerVariable(var, ref, owner);
4077 }
4078
4079 if (BlockDeclRefExpr *ref = dyn_cast<BlockDeclRefExpr>(e)) {
4080 owner.Variable = ref->getDecl();
4081 owner.setLocsFrom(ref);
4082 return true;
4083 }
4084
4085 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
4086 if (member->isArrow()) return false;
4087
4088 // Don't count this as an indirect ownership.
4089 e = member->getBase();
4090 continue;
4091 }
4092
4093 // Array ivars?
4094
4095 return false;
4096 }
4097}
4098
4099namespace {
4100 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
4101 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
4102 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
4103 Variable(variable), Capturer(0) {}
4104
4105 VarDecl *Variable;
4106 Expr *Capturer;
4107
4108 void VisitDeclRefExpr(DeclRefExpr *ref) {
4109 if (ref->getDecl() == Variable && !Capturer)
4110 Capturer = ref;
4111 }
4112
4113 void VisitBlockDeclRefExpr(BlockDeclRefExpr *ref) {
4114 if (ref->getDecl() == Variable && !Capturer)
4115 Capturer = ref;
4116 }
4117
4118 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
4119 if (Capturer) return;
4120 Visit(ref->getBase());
4121 if (Capturer && ref->isFreeIvar())
4122 Capturer = ref;
4123 }
4124
4125 void VisitBlockExpr(BlockExpr *block) {
4126 // Look inside nested blocks
4127 if (block->getBlockDecl()->capturesVariable(Variable))
4128 Visit(block->getBlockDecl()->getBody());
4129 }
4130 };
4131}
4132
4133/// Check whether the given argument is a block which captures a
4134/// variable.
4135static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
4136 assert(owner.Variable && owner.Loc.isValid());
4137
4138 e = e->IgnoreParenCasts();
4139 BlockExpr *block = dyn_cast<BlockExpr>(e);
4140 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
4141 return 0;
4142
4143 FindCaptureVisitor visitor(S.Context, owner.Variable);
4144 visitor.Visit(block->getBlockDecl()->getBody());
4145 return visitor.Capturer;
4146}
4147
4148static void diagnoseRetainCycle(Sema &S, Expr *capturer,
4149 RetainCycleOwner &owner) {
4150 assert(capturer);
4151 assert(owner.Variable && owner.Loc.isValid());
4152
4153 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
4154 << owner.Variable << capturer->getSourceRange();
4155 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
4156 << owner.Indirect << owner.Range;
4157}
4158
4159/// Check for a keyword selector that starts with the word 'add' or
4160/// 'set'.
4161static bool isSetterLikeSelector(Selector sel) {
4162 if (sel.isUnarySelector()) return false;
4163
Chris Lattner5f9e2722011-07-23 10:55:15 +00004164 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00004165 while (!str.empty() && str.front() == '_') str = str.substr(1);
4166 if (str.startswith("set") || str.startswith("add"))
4167 str = str.substr(3);
4168 else
4169 return false;
4170
4171 if (str.empty()) return true;
4172 return !islower(str.front());
4173}
4174
4175/// Check a message send to see if it's likely to cause a retain cycle.
4176void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
4177 // Only check instance methods whose selector looks like a setter.
4178 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
4179 return;
4180
4181 // Try to find a variable that the receiver is strongly owned by.
4182 RetainCycleOwner owner;
4183 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
4184 if (!findRetainCycleOwner(msg->getInstanceReceiver(), owner))
4185 return;
4186 } else {
4187 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
4188 owner.Variable = getCurMethodDecl()->getSelfDecl();
4189 owner.Loc = msg->getSuperLoc();
4190 owner.Range = msg->getSuperLoc();
4191 }
4192
4193 // Check whether the receiver is captured by any of the arguments.
4194 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
4195 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
4196 return diagnoseRetainCycle(*this, capturer, owner);
4197}
4198
4199/// Check a property assign to see if it's likely to cause a retain cycle.
4200void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
4201 RetainCycleOwner owner;
4202 if (!findRetainCycleOwner(receiver, owner))
4203 return;
4204
4205 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
4206 diagnoseRetainCycle(*this, capturer, owner);
4207}
4208
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004209bool Sema::checkUnsafeAssigns(SourceLocation Loc,
John McCallf85e1932011-06-15 23:02:42 +00004210 QualType LHS, Expr *RHS) {
4211 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
4212 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004213 return false;
4214 // strip off any implicit cast added to get to the one arc-specific
4215 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00004216 if (cast->getCastKind() == CK_ARCConsumeObject) {
John McCallf85e1932011-06-15 23:02:42 +00004217 Diag(Loc, diag::warn_arc_retained_assign)
4218 << (LT == Qualifiers::OCL_ExplicitNone)
4219 << RHS->getSourceRange();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004220 return true;
4221 }
4222 RHS = cast->getSubExpr();
4223 }
4224 return false;
John McCallf85e1932011-06-15 23:02:42 +00004225}
4226
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004227void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
4228 Expr *LHS, Expr *RHS) {
4229 QualType LHSType = LHS->getType();
4230 if (checkUnsafeAssigns(Loc, LHSType, RHS))
4231 return;
4232 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
4233 // FIXME. Check for other life times.
4234 if (LT != Qualifiers::OCL_None)
4235 return;
4236
4237 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(LHS)) {
4238 if (PRE->isImplicitProperty())
4239 return;
4240 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
4241 if (!PD)
4242 return;
4243
4244 unsigned Attributes = PD->getPropertyAttributes();
4245 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign)
4246 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00004247 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004248 Diag(Loc, diag::warn_arc_retained_property_assign)
4249 << RHS->getSourceRange();
4250 return;
4251 }
4252 RHS = cast->getSubExpr();
4253 }
4254 }
4255}