blob: daab1cd487769054560af573a0676355d5a85cd6 [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
Nico Webercda57822011-10-13 22:30:23 +0000393 case Builtin::BI__builtin_strncpy:
394 case Builtin::BI__builtin___strncpy_chk:
395 case Builtin::BIstrncpy:
396 CMF = CMF_Strncpy;
397 break;
398
399 case Builtin::BI__builtin_strncmp:
400 CMF = CMF_Strncmp;
401 break;
402
403 case Builtin::BI__builtin_strncasecmp:
404 CMF = CMF_Strncasecmp;
405 break;
406
407 case Builtin::BI__builtin_strncat:
408 case Builtin::BIstrncat:
409 CMF = CMF_Strncat;
410 break;
411
412 case Builtin::BI__builtin_strndup:
413 case Builtin::BIstrndup:
414 CMF = CMF_Strndup;
415 break;
416
Douglas Gregor707a23e2011-06-16 17:56:04 +0000417 default:
418 if (FDecl->getLinkage() == ExternalLinkage &&
419 (!getLangOptions().CPlusPlus || FDecl->isExternC())) {
420 if (FnInfo->isStr("memset"))
421 CMF = CMF_Memset;
422 else if (FnInfo->isStr("memcpy"))
423 CMF = CMF_Memcpy;
424 else if (FnInfo->isStr("memmove"))
425 CMF = CMF_Memmove;
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +0000426 else if (FnInfo->isStr("memcmp"))
427 CMF = CMF_Memcmp;
Nico Webercda57822011-10-13 22:30:23 +0000428 else if (FnInfo->isStr("strncpy"))
429 CMF = CMF_Strncpy;
430 else if (FnInfo->isStr("strncmp"))
431 CMF = CMF_Strncmp;
432 else if (FnInfo->isStr("strncasecmp"))
433 CMF = CMF_Strncasecmp;
434 else if (FnInfo->isStr("strncat"))
435 CMF = CMF_Strncat;
436 else if (FnInfo->isStr("strndup"))
437 CMF = CMF_Strndup;
Douglas Gregor707a23e2011-06-16 17:56:04 +0000438 }
439 break;
Douglas Gregor06bc9eb2011-05-03 20:37:33 +0000440 }
Douglas Gregor707a23e2011-06-16 17:56:04 +0000441
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000442 // Memset/memcpy/memmove handling
Douglas Gregor707a23e2011-06-16 17:56:04 +0000443 if (CMF != -1)
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +0000444 CheckMemaccessArguments(TheCall, CheckedMemoryFunction(CMF), FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000445
Anders Carlssond406bf02009-08-16 01:56:34 +0000446 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000447}
448
Anders Carlssond406bf02009-08-16 01:56:34 +0000449bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000450 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000451 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000452 if (!Format)
Anders Carlssond406bf02009-08-16 01:56:34 +0000453 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000454
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000455 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
456 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000457 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000458
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000459 QualType Ty = V->getType();
460 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000461 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000462
Ted Kremenek826a3452010-07-16 02:11:22 +0000463 const bool b = Format->getType() == "scanf";
464 if (!b && !CheckablePrintfAttr(Format, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +0000465 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000466
Anders Carlssond406bf02009-08-16 01:56:34 +0000467 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek826a3452010-07-16 02:11:22 +0000468 CheckPrintfScanfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
469 HasVAListArg ? 0 : Format->getFirstArg() - 1, !b);
Anders Carlssond406bf02009-08-16 01:56:34 +0000470
471 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000472}
473
Eli Friedman276b0612011-10-11 02:20:01 +0000474ExprResult
475Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::AtomicOp Op) {
476 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
477 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000478
479 // All these operations take one of the following four forms:
480 // T __atomic_load(_Atomic(T)*, int) (loads)
481 // T* __atomic_add(_Atomic(T*)*, ptrdiff_t, int) (pointer add/sub)
482 // int __atomic_compare_exchange_strong(_Atomic(T)*, T*, T, int, int)
483 // (cmpxchg)
484 // T __atomic_exchange(_Atomic(T)*, T, int) (everything else)
485 // where T is an appropriate type, and the int paremeterss are for orderings.
486 unsigned NumVals = 1;
487 unsigned NumOrders = 1;
488 if (Op == AtomicExpr::Load) {
489 NumVals = 0;
490 } else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong) {
491 NumVals = 2;
492 NumOrders = 2;
493 }
494
495 if (TheCall->getNumArgs() < NumVals+NumOrders+1) {
496 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
497 << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
498 << TheCall->getCallee()->getSourceRange();
499 return ExprError();
500 } else if (TheCall->getNumArgs() > NumVals+NumOrders+1) {
501 Diag(TheCall->getArg(NumVals+NumOrders+1)->getLocStart(),
502 diag::err_typecheck_call_too_many_args)
503 << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
504 << TheCall->getCallee()->getSourceRange();
505 return ExprError();
506 }
507
508 // Inspect the first argument of the atomic operation. This should always be
509 // a pointer to an _Atomic type.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000510 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +0000511 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
512 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
513 if (!pointerType) {
514 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
515 << Ptr->getType() << Ptr->getSourceRange();
516 return ExprError();
517 }
518
519 QualType AtomTy = pointerType->getPointeeType();
520 if (!AtomTy->isAtomicType()) {
521 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
522 << Ptr->getType() << Ptr->getSourceRange();
523 return ExprError();
524 }
525 QualType ValType = AtomTy->getAs<AtomicType>()->getValueType();
526
527 if ((Op == AtomicExpr::Add || Op == AtomicExpr::Sub) &&
528 !ValType->isIntegerType() && !ValType->isPointerType()) {
529 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
530 << Ptr->getType() << Ptr->getSourceRange();
531 return ExprError();
532 }
533
534 if (!ValType->isIntegerType() &&
535 (Op == AtomicExpr::And || Op == AtomicExpr::Or || Op == AtomicExpr::Xor)){
536 Diag(DRE->getLocStart(), diag::err_atomic_op_logical_needs_atomic_int)
537 << Ptr->getType() << Ptr->getSourceRange();
538 return ExprError();
539 }
540
541 switch (ValType.getObjCLifetime()) {
542 case Qualifiers::OCL_None:
543 case Qualifiers::OCL_ExplicitNone:
544 // okay
545 break;
546
547 case Qualifiers::OCL_Weak:
548 case Qualifiers::OCL_Strong:
549 case Qualifiers::OCL_Autoreleasing:
550 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
551 << ValType << Ptr->getSourceRange();
552 return ExprError();
553 }
554
555 QualType ResultType = ValType;
556 if (Op == AtomicExpr::Store)
557 ResultType = Context.VoidTy;
558 else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong)
559 ResultType = Context.BoolTy;
560
561 // The first argument --- the pointer --- has a fixed type; we
562 // deduce the types of the rest of the arguments accordingly. Walk
563 // the remaining arguments, converting them to the deduced value type.
564 for (unsigned i = 1; i != NumVals+NumOrders+1; ++i) {
565 ExprResult Arg = TheCall->getArg(i);
566 QualType Ty;
567 if (i < NumVals+1) {
568 // The second argument to a cmpxchg is a pointer to the data which will
569 // be exchanged. The second argument to a pointer add/subtract is the
570 // amount to add/subtract, which must be a ptrdiff_t. The third
571 // argument to a cmpxchg and the second argument in all other cases
572 // is the type of the value.
573 if (i == 1 && (Op == AtomicExpr::CmpXchgWeak ||
574 Op == AtomicExpr::CmpXchgStrong))
575 Ty = Context.getPointerType(ValType.getUnqualifiedType());
576 else if (!ValType->isIntegerType() &&
577 (Op == AtomicExpr::Add || Op == AtomicExpr::Sub))
578 Ty = Context.getPointerDiffType();
579 else
580 Ty = ValType;
581 } else {
582 // The order(s) are always converted to int.
583 Ty = Context.IntTy;
584 }
585 InitializedEntity Entity =
586 InitializedEntity::InitializeParameter(Context, Ty, false);
587 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
588 if (Arg.isInvalid())
589 return true;
590 TheCall->setArg(i, Arg.get());
591 }
592
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000593 SmallVector<Expr*, 5> SubExprs;
594 SubExprs.push_back(Ptr);
Eli Friedman276b0612011-10-11 02:20:01 +0000595 if (Op == AtomicExpr::Load) {
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000596 SubExprs.push_back(TheCall->getArg(1)); // Order
Eli Friedman276b0612011-10-11 02:20:01 +0000597 } else if (Op != AtomicExpr::CmpXchgWeak && Op != AtomicExpr::CmpXchgStrong) {
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000598 SubExprs.push_back(TheCall->getArg(2)); // Order
599 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman276b0612011-10-11 02:20:01 +0000600 } else {
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000601 SubExprs.push_back(TheCall->getArg(3)); // Order
602 SubExprs.push_back(TheCall->getArg(1)); // Val1
603 SubExprs.push_back(TheCall->getArg(2)); // Val2
604 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
Eli Friedman276b0612011-10-11 02:20:01 +0000605 }
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000606
607 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
608 SubExprs.data(), SubExprs.size(),
609 ResultType, Op,
610 TheCall->getRParenLoc()));
Eli Friedman276b0612011-10-11 02:20:01 +0000611}
612
613
John McCall5f8d6042011-08-27 01:09:30 +0000614/// checkBuiltinArgument - Given a call to a builtin function, perform
615/// normal type-checking on the given argument, updating the call in
616/// place. This is useful when a builtin function requires custom
617/// type-checking for some of its arguments but not necessarily all of
618/// them.
619///
620/// Returns true on error.
621static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
622 FunctionDecl *Fn = E->getDirectCallee();
623 assert(Fn && "builtin call without direct callee!");
624
625 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
626 InitializedEntity Entity =
627 InitializedEntity::InitializeParameter(S.Context, Param);
628
629 ExprResult Arg = E->getArg(0);
630 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
631 if (Arg.isInvalid())
632 return true;
633
634 E->setArg(ArgIndex, Arg.take());
635 return false;
636}
637
Chris Lattner5caa3702009-05-08 06:58:22 +0000638/// SemaBuiltinAtomicOverloaded - We have a call to a function like
639/// __sync_fetch_and_add, which is an overloaded function based on the pointer
640/// type of its first argument. The main ActOnCallExpr routines have already
641/// promoted the types of arguments because all of these calls are prototyped as
642/// void(...).
643///
644/// This function goes through and does final semantic checking for these
645/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000646ExprResult
647Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000648 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000649 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
650 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
651
652 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000653 if (TheCall->getNumArgs() < 1) {
654 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
655 << 0 << 1 << TheCall->getNumArgs()
656 << TheCall->getCallee()->getSourceRange();
657 return ExprError();
658 }
Mike Stump1eb44332009-09-09 15:08:12 +0000659
Chris Lattner5caa3702009-05-08 06:58:22 +0000660 // Inspect the first argument of the atomic builtin. This should always be
661 // a pointer type, whose element is an integral scalar or pointer type.
662 // Because it is a pointer type, we don't have to worry about any implicit
663 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000664 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000665 Expr *FirstArg = TheCall->getArg(0);
John McCallf85e1932011-06-15 23:02:42 +0000666 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
667 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000668 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
669 << FirstArg->getType() << FirstArg->getSourceRange();
670 return ExprError();
671 }
Mike Stump1eb44332009-09-09 15:08:12 +0000672
John McCallf85e1932011-06-15 23:02:42 +0000673 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000674 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000675 !ValType->isBlockPointerType()) {
676 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
677 << FirstArg->getType() << FirstArg->getSourceRange();
678 return ExprError();
679 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000680
John McCallf85e1932011-06-15 23:02:42 +0000681 switch (ValType.getObjCLifetime()) {
682 case Qualifiers::OCL_None:
683 case Qualifiers::OCL_ExplicitNone:
684 // okay
685 break;
686
687 case Qualifiers::OCL_Weak:
688 case Qualifiers::OCL_Strong:
689 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +0000690 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +0000691 << ValType << FirstArg->getSourceRange();
692 return ExprError();
693 }
694
John McCallb45ae252011-10-05 07:41:44 +0000695 // Strip any qualifiers off ValType.
696 ValType = ValType.getUnqualifiedType();
697
Chandler Carruth8d13d222010-07-18 20:54:12 +0000698 // The majority of builtins return a value, but a few have special return
699 // types, so allow them to override appropriately below.
700 QualType ResultType = ValType;
701
Chris Lattner5caa3702009-05-08 06:58:22 +0000702 // We need to figure out which concrete builtin this maps onto. For example,
703 // __sync_fetch_and_add with a 2 byte object turns into
704 // __sync_fetch_and_add_2.
705#define BUILTIN_ROW(x) \
706 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
707 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000708
Chris Lattner5caa3702009-05-08 06:58:22 +0000709 static const unsigned BuiltinIndices[][5] = {
710 BUILTIN_ROW(__sync_fetch_and_add),
711 BUILTIN_ROW(__sync_fetch_and_sub),
712 BUILTIN_ROW(__sync_fetch_and_or),
713 BUILTIN_ROW(__sync_fetch_and_and),
714 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +0000715
Chris Lattner5caa3702009-05-08 06:58:22 +0000716 BUILTIN_ROW(__sync_add_and_fetch),
717 BUILTIN_ROW(__sync_sub_and_fetch),
718 BUILTIN_ROW(__sync_and_and_fetch),
719 BUILTIN_ROW(__sync_or_and_fetch),
720 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000721
Chris Lattner5caa3702009-05-08 06:58:22 +0000722 BUILTIN_ROW(__sync_val_compare_and_swap),
723 BUILTIN_ROW(__sync_bool_compare_and_swap),
724 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +0000725 BUILTIN_ROW(__sync_lock_release),
726 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +0000727 };
Mike Stump1eb44332009-09-09 15:08:12 +0000728#undef BUILTIN_ROW
729
Chris Lattner5caa3702009-05-08 06:58:22 +0000730 // Determine the index of the size.
731 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000732 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000733 case 1: SizeIndex = 0; break;
734 case 2: SizeIndex = 1; break;
735 case 4: SizeIndex = 2; break;
736 case 8: SizeIndex = 3; break;
737 case 16: SizeIndex = 4; break;
738 default:
Chandler Carruthd2014572010-07-09 18:59:35 +0000739 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
740 << FirstArg->getType() << FirstArg->getSourceRange();
741 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +0000742 }
Mike Stump1eb44332009-09-09 15:08:12 +0000743
Chris Lattner5caa3702009-05-08 06:58:22 +0000744 // Each of these builtins has one pointer argument, followed by some number of
745 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
746 // that we ignore. Find out which row of BuiltinIndices to read from as well
747 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000748 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000749 unsigned BuiltinIndex, NumFixed = 1;
750 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000751 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Chris Lattner5caa3702009-05-08 06:58:22 +0000752 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
753 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
754 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
755 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
756 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000757
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000758 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
759 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
760 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
761 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 8; break;
762 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000763
Chris Lattner5caa3702009-05-08 06:58:22 +0000764 case Builtin::BI__sync_val_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000765 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +0000766 NumFixed = 2;
767 break;
768 case Builtin::BI__sync_bool_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000769 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +0000770 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000771 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000772 break;
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000773 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000774 case Builtin::BI__sync_lock_release:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000775 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000776 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000777 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000778 break;
Chris Lattner23aa9c82011-04-09 03:57:26 +0000779 case Builtin::BI__sync_swap: BuiltinIndex = 14; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000780 }
Mike Stump1eb44332009-09-09 15:08:12 +0000781
Chris Lattner5caa3702009-05-08 06:58:22 +0000782 // Now that we know how many fixed arguments we expect, first check that we
783 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +0000784 if (TheCall->getNumArgs() < 1+NumFixed) {
785 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
786 << 0 << 1+NumFixed << TheCall->getNumArgs()
787 << TheCall->getCallee()->getSourceRange();
788 return ExprError();
789 }
Mike Stump1eb44332009-09-09 15:08:12 +0000790
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000791 // Get the decl for the concrete builtin from this, we can tell what the
792 // concrete integer type we should convert to is.
793 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
794 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
795 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +0000796 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000797 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
798 TUScope, false, DRE->getLocStart()));
Chandler Carruthd2014572010-07-09 18:59:35 +0000799
John McCallf871d0c2010-08-07 06:22:56 +0000800 // The first argument --- the pointer --- has a fixed type; we
801 // deduce the types of the rest of the arguments accordingly. Walk
802 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +0000803 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +0000804 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +0000805
Chris Lattner5caa3702009-05-08 06:58:22 +0000806 // If the argument is an implicit cast, then there was a promotion due to
807 // "...", just remove it now.
John Wiegley429bb272011-04-08 18:41:53 +0000808 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg.get())) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000809 Arg = ICE->getSubExpr();
810 ICE->setSubExpr(0);
John Wiegley429bb272011-04-08 18:41:53 +0000811 TheCall->setArg(i+1, Arg.get());
Chris Lattner5caa3702009-05-08 06:58:22 +0000812 }
Mike Stump1eb44332009-09-09 15:08:12 +0000813
Chris Lattner5caa3702009-05-08 06:58:22 +0000814 // GCC does an implicit conversion to the pointer or integer ValType. This
815 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +0000816 // Initialize the argument.
817 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
818 ValType, /*consume*/ false);
819 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +0000820 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +0000821 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000822
Chris Lattner5caa3702009-05-08 06:58:22 +0000823 // Okay, we have something that *can* be converted to the right type. Check
824 // to see if there is a potentially weird extension going on here. This can
825 // happen when you do an atomic operation on something like an char* and
826 // pass in 42. The 42 gets converted to char. This is even more strange
827 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +0000828 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +0000829 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +0000830 }
Mike Stump1eb44332009-09-09 15:08:12 +0000831
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +0000832 ASTContext& Context = this->getASTContext();
833
834 // Create a new DeclRefExpr to refer to the new decl.
835 DeclRefExpr* NewDRE = DeclRefExpr::Create(
836 Context,
837 DRE->getQualifierLoc(),
838 NewBuiltinDecl,
839 DRE->getLocation(),
840 NewBuiltinDecl->getType(),
841 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +0000842
Chris Lattner5caa3702009-05-08 06:58:22 +0000843 // Set the callee in the CallExpr.
844 // FIXME: This leaks the original parens and implicit casts.
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +0000845 ExprResult PromotedCall = UsualUnaryConversions(NewDRE);
John Wiegley429bb272011-04-08 18:41:53 +0000846 if (PromotedCall.isInvalid())
847 return ExprError();
848 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +0000849
Chandler Carruthdb4325b2010-07-18 07:23:17 +0000850 // Change the result type of the call to match the original value type. This
851 // is arbitrary, but the codegen for these builtins ins design to handle it
852 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +0000853 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +0000854
855 return move(TheCallResult);
Chris Lattner5caa3702009-05-08 06:58:22 +0000856}
857
Chris Lattner69039812009-02-18 06:01:06 +0000858/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000859/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +0000860/// Note: It might also make sense to do the UTF-16 conversion here (would
861/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +0000862bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000863 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000864 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
865
Douglas Gregor5cee1192011-07-27 05:40:30 +0000866 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000867 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
868 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000869 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000870 }
Mike Stump1eb44332009-09-09 15:08:12 +0000871
Fariborz Jahanian7da71022010-09-07 19:38:13 +0000872 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000873 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +0000874 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000875 SmallVector<UTF16, 128> ToBuf(NumBytes);
Fariborz Jahanian7da71022010-09-07 19:38:13 +0000876 const UTF8 *FromPtr = (UTF8 *)String.data();
877 UTF16 *ToPtr = &ToBuf[0];
878
879 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
880 &ToPtr, ToPtr + NumBytes,
881 strictConversion);
882 // Check for conversion failure.
883 if (Result != conversionOK)
884 Diag(Arg->getLocStart(),
885 diag::warn_cfstring_truncated) << Arg->getSourceRange();
886 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000887 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000888}
889
Chris Lattnerc27c6652007-12-20 00:05:45 +0000890/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
891/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000892bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
893 Expr *Fn = TheCall->getCallee();
894 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000895 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000896 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000897 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
898 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +0000899 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000900 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000901 return true;
902 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000903
904 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +0000905 return Diag(TheCall->getLocEnd(),
906 diag::err_typecheck_call_too_few_args_at_least)
907 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000908 }
909
John McCall5f8d6042011-08-27 01:09:30 +0000910 // Type-check the first argument normally.
911 if (checkBuiltinArgument(*this, TheCall, 0))
912 return true;
913
Chris Lattnerc27c6652007-12-20 00:05:45 +0000914 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000915 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +0000916 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000917 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +0000918 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +0000919 else if (FunctionDecl *FD = getCurFunctionDecl())
920 isVariadic = FD->isVariadic();
921 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000922 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +0000923
Chris Lattnerc27c6652007-12-20 00:05:45 +0000924 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000925 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
926 return true;
927 }
Mike Stump1eb44332009-09-09 15:08:12 +0000928
Chris Lattner30ce3442007-12-19 23:59:04 +0000929 // Verify that the second argument to the builtin is the last argument of the
930 // current function or method.
931 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000932 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +0000933
Anders Carlsson88cf2262008-02-11 04:20:54 +0000934 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
935 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000936 // FIXME: This isn't correct for methods (results in bogus warning).
937 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000938 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000939 if (CurBlock)
940 LastArg = *(CurBlock->TheDecl->param_end()-1);
941 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +0000942 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000943 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000944 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000945 SecondArgIsLastNamedArgument = PV == LastArg;
946 }
947 }
Mike Stump1eb44332009-09-09 15:08:12 +0000948
Chris Lattner30ce3442007-12-19 23:59:04 +0000949 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +0000950 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000951 diag::warn_second_parameter_of_va_start_not_last_named_argument);
952 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000953}
Chris Lattner30ce3442007-12-19 23:59:04 +0000954
Chris Lattner1b9a0792007-12-20 00:26:33 +0000955/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
956/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000957bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
958 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000959 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000960 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000961 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +0000962 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000963 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000964 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000965 << SourceRange(TheCall->getArg(2)->getLocStart(),
966 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000967
John Wiegley429bb272011-04-08 18:41:53 +0000968 ExprResult OrigArg0 = TheCall->getArg(0);
969 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000970
Chris Lattner1b9a0792007-12-20 00:26:33 +0000971 // Do standard promotions between the two arguments, returning their common
972 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000973 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +0000974 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
975 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +0000976
977 // Make sure any conversions are pushed back into the call; this is
978 // type safe since unordered compare builtins are declared as "_Bool
979 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +0000980 TheCall->setArg(0, OrigArg0.get());
981 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +0000982
John Wiegley429bb272011-04-08 18:41:53 +0000983 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +0000984 return false;
985
Chris Lattner1b9a0792007-12-20 00:26:33 +0000986 // If the common type isn't a real floating type, then the arguments were
987 // invalid for this operation.
988 if (!Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +0000989 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000990 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +0000991 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
992 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000993
Chris Lattner1b9a0792007-12-20 00:26:33 +0000994 return false;
995}
996
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000997/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
998/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000999/// to check everything. We expect the last argument to be a floating point
1000/// value.
1001bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1002 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001003 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001004 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001005 if (TheCall->getNumArgs() > NumArgs)
1006 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001007 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001008 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001009 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001010 (*(TheCall->arg_end()-1))->getLocEnd());
1011
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001012 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001013
Eli Friedman9ac6f622009-08-31 20:06:00 +00001014 if (OrigArg->isTypeDependent())
1015 return false;
1016
Chris Lattner81368fb2010-05-06 05:50:07 +00001017 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001018 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001019 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001020 diag::err_typecheck_call_invalid_unary_fp)
1021 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001022
Chris Lattner81368fb2010-05-06 05:50:07 +00001023 // If this is an implicit conversion from float -> double, remove it.
1024 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1025 Expr *CastArg = Cast->getSubExpr();
1026 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1027 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1028 "promotion from float to double is the only expected cast here");
1029 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001030 TheCall->setArg(NumArgs-1, CastArg);
1031 OrigArg = CastArg;
1032 }
1033 }
1034
Eli Friedman9ac6f622009-08-31 20:06:00 +00001035 return false;
1036}
1037
Eli Friedmand38617c2008-05-14 19:38:39 +00001038/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1039// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001040ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001041 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001042 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001043 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +00001044 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +00001045 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001046
Nate Begeman37b6a572010-06-08 00:16:34 +00001047 // Determine which of the following types of shufflevector we're checking:
1048 // 1) unary, vector mask: (lhs, mask)
1049 // 2) binary, vector mask: (lhs, rhs, mask)
1050 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1051 QualType resType = TheCall->getArg(0)->getType();
1052 unsigned numElements = 0;
1053
Douglas Gregorcde01732009-05-19 22:10:17 +00001054 if (!TheCall->getArg(0)->isTypeDependent() &&
1055 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001056 QualType LHSType = TheCall->getArg(0)->getType();
1057 QualType RHSType = TheCall->getArg(1)->getType();
1058
1059 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001060 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001061 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001062 TheCall->getArg(1)->getLocEnd());
1063 return ExprError();
1064 }
Nate Begeman37b6a572010-06-08 00:16:34 +00001065
1066 numElements = LHSType->getAs<VectorType>()->getNumElements();
1067 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001068
Nate Begeman37b6a572010-06-08 00:16:34 +00001069 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1070 // with mask. If so, verify that RHS is an integer vector type with the
1071 // same number of elts as lhs.
1072 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001073 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001074 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1075 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1076 << SourceRange(TheCall->getArg(1)->getLocStart(),
1077 TheCall->getArg(1)->getLocEnd());
1078 numResElements = numElements;
1079 }
1080 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001081 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001082 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001083 TheCall->getArg(1)->getLocEnd());
1084 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +00001085 } else if (numElements != numResElements) {
1086 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001087 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001088 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001089 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001090 }
1091
1092 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001093 if (TheCall->getArg(i)->isTypeDependent() ||
1094 TheCall->getArg(i)->isValueDependent())
1095 continue;
1096
Nate Begeman37b6a572010-06-08 00:16:34 +00001097 llvm::APSInt Result(32);
1098 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1099 return ExprError(Diag(TheCall->getLocStart(),
1100 diag::err_shufflevector_nonconstant_argument)
1101 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001102
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001103 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001104 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001105 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001106 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001107 }
1108
Chris Lattner5f9e2722011-07-23 10:55:15 +00001109 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001110
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001111 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001112 exprs.push_back(TheCall->getArg(i));
1113 TheCall->setArg(i, 0);
1114 }
1115
Nate Begemana88dc302009-08-12 02:10:25 +00001116 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begeman37b6a572010-06-08 00:16:34 +00001117 exprs.size(), resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001118 TheCall->getCallee()->getLocStart(),
1119 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001120}
Chris Lattner30ce3442007-12-19 23:59:04 +00001121
Daniel Dunbar4493f792008-07-21 22:59:13 +00001122/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1123// This is declared to take (const void*, ...) and can take two
1124// optional constant int args.
1125bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001126 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001127
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001128 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001129 return Diag(TheCall->getLocEnd(),
1130 diag::err_typecheck_call_too_many_args_at_most)
1131 << 0 /*function call*/ << 3 << NumArgs
1132 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001133
1134 // Argument 0 is checked for us and the remaining arguments must be
1135 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001136 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001137 Expr *Arg = TheCall->getArg(i);
Eric Christopher691ebc32010-04-17 02:26:23 +00001138
Eli Friedman9aef7262009-12-04 00:30:06 +00001139 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001140 if (SemaBuiltinConstantArg(TheCall, i, Result))
1141 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001142
Daniel Dunbar4493f792008-07-21 22:59:13 +00001143 // FIXME: gcc issues a warning and rewrites these to 0. These
1144 // seems especially odd for the third argument since the default
1145 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001146 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001147 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001148 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001149 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001150 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001151 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001152 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001153 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001154 }
1155 }
1156
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001157 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001158}
1159
Eric Christopher691ebc32010-04-17 02:26:23 +00001160/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1161/// TheCall is a constant expression.
1162bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1163 llvm::APSInt &Result) {
1164 Expr *Arg = TheCall->getArg(ArgNum);
1165 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1166 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1167
1168 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1169
1170 if (!Arg->isIntegerConstantExpr(Result, Context))
1171 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001172 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001173
Chris Lattner21fb98e2009-09-23 06:06:36 +00001174 return false;
1175}
1176
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001177/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1178/// int type). This simply type checks that type is one of the defined
1179/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001180// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001181bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001182 llvm::APSInt Result;
1183
1184 // Check constant-ness first.
1185 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1186 return true;
1187
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001188 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001189 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001190 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1191 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001192 }
1193
1194 return false;
1195}
1196
Eli Friedman586d6a82009-05-03 06:04:26 +00001197/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001198/// This checks that val is a constant 1.
1199bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1200 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001201 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001202
Eric Christopher691ebc32010-04-17 02:26:23 +00001203 // TODO: This is less than ideal. Overload this to take a value.
1204 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1205 return true;
1206
1207 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001208 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1209 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1210
1211 return false;
1212}
1213
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001214// Handle i > 1 ? "x" : "y", recursively.
Ted Kremenek082d9362009-03-20 21:35:28 +00001215bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
1216 bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001217 unsigned format_idx, unsigned firstDataArg,
1218 bool isPrintf) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001219 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001220 if (E->isTypeDependent() || E->isValueDependent())
1221 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001222
Peter Collingbournef111d932011-04-15 00:35:48 +00001223 E = E->IgnoreParens();
1224
Ted Kremenekd30ef872009-01-12 23:09:09 +00001225 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001226 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001227 case Stmt::ConditionalOperatorClass: {
John McCall56ca35d2011-02-17 10:25:35 +00001228 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
Ted Kremenek826a3452010-07-16 02:11:22 +00001229 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg,
1230 format_idx, firstDataArg, isPrintf)
John McCall56ca35d2011-02-17 10:25:35 +00001231 && SemaCheckStringLiteral(C->getFalseExpr(), TheCall, HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001232 format_idx, firstDataArg, isPrintf);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001233 }
1234
Ted Kremenek95355bb2010-09-09 03:51:42 +00001235 case Stmt::IntegerLiteralClass:
1236 // Technically -Wformat-nonliteral does not warn about this case.
1237 // The behavior of printf and friends in this case is implementation
1238 // dependent. Ideally if the format string cannot be null then
1239 // it should have a 'nonnull' attribute in the function prototype.
1240 return true;
1241
Ted Kremenekd30ef872009-01-12 23:09:09 +00001242 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001243 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1244 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001245 }
1246
John McCall56ca35d2011-02-17 10:25:35 +00001247 case Stmt::OpaqueValueExprClass:
1248 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1249 E = src;
1250 goto tryAgain;
1251 }
1252 return false;
1253
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001254 case Stmt::PredefinedExprClass:
1255 // While __func__, etc., are technically not string literals, they
1256 // cannot contain format specifiers and thus are not a security
1257 // liability.
1258 return true;
1259
Ted Kremenek082d9362009-03-20 21:35:28 +00001260 case Stmt::DeclRefExprClass: {
1261 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001262
Ted Kremenek082d9362009-03-20 21:35:28 +00001263 // As an exception, do not flag errors for variables binding to
1264 // const string literals.
1265 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1266 bool isConstant = false;
1267 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001268
Ted Kremenek082d9362009-03-20 21:35:28 +00001269 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1270 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001271 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001272 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001273 PT->getPointeeType().isConstant(Context);
1274 }
Mike Stump1eb44332009-09-09 15:08:12 +00001275
Ted Kremenek082d9362009-03-20 21:35:28 +00001276 if (isConstant) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001277 if (const Expr *Init = VD->getAnyInitializer())
Ted Kremenek082d9362009-03-20 21:35:28 +00001278 return SemaCheckStringLiteral(Init, TheCall,
Ted Kremenek826a3452010-07-16 02:11:22 +00001279 HasVAListArg, format_idx, firstDataArg,
1280 isPrintf);
Ted Kremenek082d9362009-03-20 21:35:28 +00001281 }
Mike Stump1eb44332009-09-09 15:08:12 +00001282
Anders Carlssond966a552009-06-28 19:55:58 +00001283 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1284 // special check to see if the format string is a function parameter
1285 // of the function calling the printf function. If the function
1286 // has an attribute indicating it is a printf-like function, then we
1287 // should suppress warnings concerning non-literals being used in a call
1288 // to a vprintf function. For example:
1289 //
1290 // void
1291 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1292 // va_list ap;
1293 // va_start(ap, fmt);
1294 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1295 // ...
1296 //
1297 //
1298 // FIXME: We don't have full attribute support yet, so just check to see
1299 // if the argument is a DeclRefExpr that references a parameter. We'll
1300 // add proper support for checking the attribute later.
1301 if (HasVAListArg)
1302 if (isa<ParmVarDecl>(VD))
1303 return true;
Ted Kremenek082d9362009-03-20 21:35:28 +00001304 }
Mike Stump1eb44332009-09-09 15:08:12 +00001305
Ted Kremenek082d9362009-03-20 21:35:28 +00001306 return false;
1307 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001308
Anders Carlsson8f031b32009-06-27 04:05:33 +00001309 case Stmt::CallExprClass: {
1310 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001311 if (const ImplicitCastExpr *ICE
Anders Carlsson8f031b32009-06-27 04:05:33 +00001312 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
1313 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
1314 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001315 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001316 unsigned ArgIndex = FA->getFormatIdx();
1317 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001318
1319 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001320 format_idx, firstDataArg, isPrintf);
Anders Carlsson8f031b32009-06-27 04:05:33 +00001321 }
1322 }
1323 }
1324 }
Mike Stump1eb44332009-09-09 15:08:12 +00001325
Anders Carlsson8f031b32009-06-27 04:05:33 +00001326 return false;
1327 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001328 case Stmt::ObjCStringLiteralClass:
1329 case Stmt::StringLiteralClass: {
1330 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001331
Ted Kremenek082d9362009-03-20 21:35:28 +00001332 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001333 StrE = ObjCFExpr->getString();
1334 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001335 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001336
Ted Kremenekd30ef872009-01-12 23:09:09 +00001337 if (StrE) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001338 CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx,
1339 firstDataArg, isPrintf);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001340 return true;
1341 }
Mike Stump1eb44332009-09-09 15:08:12 +00001342
Ted Kremenekd30ef872009-01-12 23:09:09 +00001343 return false;
1344 }
Mike Stump1eb44332009-09-09 15:08:12 +00001345
Ted Kremenek082d9362009-03-20 21:35:28 +00001346 default:
1347 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001348 }
1349}
1350
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001351void
Mike Stump1eb44332009-09-09 15:08:12 +00001352Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001353 const Expr * const *ExprArgs,
1354 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001355 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1356 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001357 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001358 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001359 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001360 Expr::NPC_ValueDependentIsNotNull))
Nick Lewycky909a70d2011-03-25 01:44:32 +00001361 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001362 }
1363}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001364
Ted Kremenek826a3452010-07-16 02:11:22 +00001365/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1366/// functions) for correct use of format strings.
Chris Lattner59907c42007-08-10 20:18:51 +00001367void
Ted Kremenek826a3452010-07-16 02:11:22 +00001368Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
1369 unsigned format_idx, unsigned firstDataArg,
1370 bool isPrintf) {
1371
Ted Kremenek082d9362009-03-20 21:35:28 +00001372 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +00001373
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001374 // The way the format attribute works in GCC, the implicit this argument
1375 // of member functions is counted. However, it doesn't appear in our own
1376 // lists, so decrement format_idx in that case.
1377 if (isa<CXXMemberCallExpr>(TheCall)) {
Chandler Carruth9263a302010-11-16 08:49:43 +00001378 const CXXMethodDecl *method_decl =
1379 dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl());
1380 if (method_decl && method_decl->isInstance()) {
1381 // Catch a format attribute mistakenly referring to the object argument.
1382 if (format_idx == 0)
1383 return;
1384 --format_idx;
1385 if(firstDataArg != 0)
1386 --firstDataArg;
1387 }
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001388 }
1389
Ted Kremenek826a3452010-07-16 02:11:22 +00001390 // CHECK: printf/scanf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +00001391 if (format_idx >= TheCall->getNumArgs()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001392 Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001393 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001394 return;
1395 }
Mike Stump1eb44332009-09-09 15:08:12 +00001396
Ted Kremenek082d9362009-03-20 21:35:28 +00001397 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001398
Chris Lattner59907c42007-08-10 20:18:51 +00001399 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001400 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001401 // Dynamically generated format strings are difficult to
1402 // automatically vet at compile time. Requiring that format strings
1403 // are string literals: (1) permits the checking of format strings by
1404 // the compiler and thereby (2) can practically remove the source of
1405 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001406
Mike Stump1eb44332009-09-09 15:08:12 +00001407 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001408 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001409 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001410 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001411 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
Ted Kremenek826a3452010-07-16 02:11:22 +00001412 firstDataArg, isPrintf))
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001413 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001414
Chris Lattner655f1412009-04-29 04:59:47 +00001415 // If there are no arguments specified, warn with -Wformat-security, otherwise
1416 // warn only with -Wformat-nonliteral.
1417 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump1eb44332009-09-09 15:08:12 +00001418 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001419 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001420 << OrigFormatExpr->getSourceRange();
1421 else
Mike Stump1eb44332009-09-09 15:08:12 +00001422 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001423 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001424 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001425}
Ted Kremenek71895b92007-08-14 17:39:48 +00001426
Ted Kremeneke0e53132010-01-28 23:39:18 +00001427namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001428class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1429protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001430 Sema &S;
1431 const StringLiteral *FExpr;
1432 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001433 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001434 const unsigned NumDataArgs;
1435 const bool IsObjCLiteral;
1436 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001437 const bool HasVAListArg;
1438 const CallExpr *TheCall;
1439 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001440 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001441 bool usesPositionalArgs;
1442 bool atFirstArg;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001443public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001444 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001445 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001446 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001447 const char *beg, bool hasVAListArg,
1448 const CallExpr *theCall, unsigned formatIdx)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001449 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek6ee76532010-03-25 03:59:12 +00001450 FirstDataArg(firstDataArg),
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001451 NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001452 IsObjCLiteral(isObjCLiteral), Beg(beg),
1453 HasVAListArg(hasVAListArg),
Ted Kremenekefaff192010-02-27 01:41:03 +00001454 TheCall(theCall), FormatIdx(formatIdx),
1455 usesPositionalArgs(false), atFirstArg(true) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001456 CoveredArgs.resize(numDataArgs);
1457 CoveredArgs.reset();
1458 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001459
Ted Kremenek07d161f2010-01-29 01:50:07 +00001460 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001461
Ted Kremenek826a3452010-07-16 02:11:22 +00001462 void HandleIncompleteSpecifier(const char *startSpecifier,
1463 unsigned specifierLen);
1464
Ted Kremenekefaff192010-02-27 01:41:03 +00001465 virtual void HandleInvalidPosition(const char *startSpecifier,
1466 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001467 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001468
1469 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1470
Ted Kremeneke0e53132010-01-28 23:39:18 +00001471 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001472
Ted Kremenek826a3452010-07-16 02:11:22 +00001473protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001474 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1475 const char *startSpec,
1476 unsigned specifierLen,
1477 const char *csStart, unsigned csLen);
1478
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001479 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00001480 CharSourceRange getSpecifierRange(const char *startSpecifier,
1481 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001482 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001483
Ted Kremenek0d277352010-01-29 01:06:55 +00001484 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00001485
1486 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1487 const analyze_format_string::ConversionSpecifier &CS,
1488 const char *startSpecifier, unsigned specifierLen,
1489 unsigned argIndex);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001490};
1491}
1492
Ted Kremenek826a3452010-07-16 02:11:22 +00001493SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001494 return OrigFormatExpr->getSourceRange();
1495}
1496
Ted Kremenek826a3452010-07-16 02:11:22 +00001497CharSourceRange CheckFormatHandler::
1498getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001499 SourceLocation Start = getLocationOfByte(startSpecifier);
1500 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1501
1502 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001503 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00001504
1505 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001506}
1507
Ted Kremenek826a3452010-07-16 02:11:22 +00001508SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001509 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001510}
1511
Ted Kremenek826a3452010-07-16 02:11:22 +00001512void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1513 unsigned specifierLen){
Ted Kremenek808015a2010-01-29 03:16:21 +00001514 SourceLocation Loc = getLocationOfByte(startSpecifier);
1515 S.Diag(Loc, diag::warn_printf_incomplete_specifier)
Ted Kremenek826a3452010-07-16 02:11:22 +00001516 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek808015a2010-01-29 03:16:21 +00001517}
1518
Ted Kremenekefaff192010-02-27 01:41:03 +00001519void
Ted Kremenek826a3452010-07-16 02:11:22 +00001520CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1521 analyze_format_string::PositionContext p) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001522 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek826a3452010-07-16 02:11:22 +00001523 S.Diag(Loc, diag::warn_format_invalid_positional_specifier)
1524 << (unsigned) p << getSpecifierRange(startPos, posLen);
Ted Kremenekefaff192010-02-27 01:41:03 +00001525}
1526
Ted Kremenek826a3452010-07-16 02:11:22 +00001527void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00001528 unsigned posLen) {
1529 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek826a3452010-07-16 02:11:22 +00001530 S.Diag(Loc, diag::warn_format_zero_positional_specifier)
1531 << getSpecifierRange(startPos, posLen);
Ted Kremenekefaff192010-02-27 01:41:03 +00001532}
1533
Ted Kremenek826a3452010-07-16 02:11:22 +00001534void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Ted Kremenek0c069442011-03-15 21:18:48 +00001535 if (!IsObjCLiteral) {
1536 // The presence of a null character is likely an error.
1537 S.Diag(getLocationOfByte(nullCharacter),
1538 diag::warn_printf_format_string_contains_null_char)
1539 << getFormatStringRange();
1540 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001541}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001542
Ted Kremenek826a3452010-07-16 02:11:22 +00001543const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
1544 return TheCall->getArg(FirstDataArg + i);
1545}
1546
1547void CheckFormatHandler::DoneProcessing() {
1548 // Does the number of data arguments exceed the number of
1549 // format conversions in the format string?
1550 if (!HasVAListArg) {
1551 // Find any arguments that weren't covered.
1552 CoveredArgs.flip();
1553 signed notCoveredArg = CoveredArgs.find_first();
1554 if (notCoveredArg >= 0) {
1555 assert((unsigned)notCoveredArg < NumDataArgs);
1556 S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(),
1557 diag::warn_printf_data_arg_not_used)
1558 << getFormatStringRange();
1559 }
1560 }
1561}
1562
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001563bool
1564CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1565 SourceLocation Loc,
1566 const char *startSpec,
1567 unsigned specifierLen,
1568 const char *csStart,
1569 unsigned csLen) {
1570
1571 bool keepGoing = true;
1572 if (argIndex < NumDataArgs) {
1573 // Consider the argument coverered, even though the specifier doesn't
1574 // make sense.
1575 CoveredArgs.set(argIndex);
1576 }
1577 else {
1578 // If argIndex exceeds the number of data arguments we
1579 // don't issue a warning because that is just a cascade of warnings (and
1580 // they may have intended '%%' anyway). We don't want to continue processing
1581 // the format string after this point, however, as we will like just get
1582 // gibberish when trying to match arguments.
1583 keepGoing = false;
1584 }
1585
1586 S.Diag(Loc, diag::warn_format_invalid_conversion)
Chris Lattner5f9e2722011-07-23 10:55:15 +00001587 << StringRef(csStart, csLen)
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001588 << getSpecifierRange(startSpec, specifierLen);
1589
1590 return keepGoing;
1591}
1592
Ted Kremenek666a1972010-07-26 19:45:42 +00001593bool
1594CheckFormatHandler::CheckNumArgs(
1595 const analyze_format_string::FormatSpecifier &FS,
1596 const analyze_format_string::ConversionSpecifier &CS,
1597 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1598
1599 if (argIndex >= NumDataArgs) {
1600 if (FS.usesPositionalArg()) {
1601 S.Diag(getLocationOfByte(CS.getStart()),
1602 diag::warn_printf_positional_arg_exceeds_data_args)
1603 << (argIndex+1) << NumDataArgs
1604 << getSpecifierRange(startSpecifier, specifierLen);
1605 }
1606 else {
1607 S.Diag(getLocationOfByte(CS.getStart()),
1608 diag::warn_printf_insufficient_data_args)
1609 << getSpecifierRange(startSpecifier, specifierLen);
1610 }
1611
1612 return false;
1613 }
1614 return true;
1615}
1616
Ted Kremenek826a3452010-07-16 02:11:22 +00001617//===--- CHECK: Printf format string checking ------------------------------===//
1618
1619namespace {
1620class CheckPrintfHandler : public CheckFormatHandler {
1621public:
1622 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1623 const Expr *origFormatExpr, unsigned firstDataArg,
1624 unsigned numDataArgs, bool isObjCLiteral,
1625 const char *beg, bool hasVAListArg,
1626 const CallExpr *theCall, unsigned formatIdx)
1627 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1628 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1629 theCall, formatIdx) {}
1630
1631
1632 bool HandleInvalidPrintfConversionSpecifier(
1633 const analyze_printf::PrintfSpecifier &FS,
1634 const char *startSpecifier,
1635 unsigned specifierLen);
1636
1637 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1638 const char *startSpecifier,
1639 unsigned specifierLen);
1640
1641 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1642 const char *startSpecifier, unsigned specifierLen);
1643 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1644 const analyze_printf::OptionalAmount &Amt,
1645 unsigned type,
1646 const char *startSpecifier, unsigned specifierLen);
1647 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1648 const analyze_printf::OptionalFlag &flag,
1649 const char *startSpecifier, unsigned specifierLen);
1650 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1651 const analyze_printf::OptionalFlag &ignoredFlag,
1652 const analyze_printf::OptionalFlag &flag,
1653 const char *startSpecifier, unsigned specifierLen);
1654};
1655}
1656
1657bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1658 const analyze_printf::PrintfSpecifier &FS,
1659 const char *startSpecifier,
1660 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001661 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001662 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001663
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001664 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1665 getLocationOfByte(CS.getStart()),
1666 startSpecifier, specifierLen,
1667 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001668}
1669
Ted Kremenek826a3452010-07-16 02:11:22 +00001670bool CheckPrintfHandler::HandleAmount(
1671 const analyze_format_string::OptionalAmount &Amt,
1672 unsigned k, const char *startSpecifier,
1673 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001674
1675 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001676 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001677 unsigned argIndex = Amt.getArgIndex();
1678 if (argIndex >= NumDataArgs) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001679 S.Diag(getLocationOfByte(Amt.getStart()),
1680 diag::warn_printf_asterisk_missing_arg)
Ted Kremenek826a3452010-07-16 02:11:22 +00001681 << k << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek0d277352010-01-29 01:06:55 +00001682 // Don't do any more checking. We will just emit
1683 // spurious errors.
1684 return false;
1685 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001686
Ted Kremenek0d277352010-01-29 01:06:55 +00001687 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00001688 // Although not in conformance with C99, we also allow the argument to be
1689 // an 'unsigned int' as that is a reasonably safe case. GCC also
1690 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001691 CoveredArgs.set(argIndex);
1692 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00001693 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001694
1695 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1696 assert(ATR.isValid());
1697
1698 if (!ATR.matchesType(S.Context, T)) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001699 S.Diag(getLocationOfByte(Amt.getStart()),
1700 diag::warn_printf_asterisk_wrong_type)
1701 << k
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001702 << ATR.getRepresentativeType(S.Context) << T
Ted Kremenek826a3452010-07-16 02:11:22 +00001703 << getSpecifierRange(startSpecifier, specifierLen)
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001704 << Arg->getSourceRange();
Ted Kremenek0d277352010-01-29 01:06:55 +00001705 // Don't do any more checking. We will just emit
1706 // spurious errors.
1707 return false;
1708 }
1709 }
1710 }
1711 return true;
1712}
Ted Kremenek0d277352010-01-29 01:06:55 +00001713
Tom Caree4ee9662010-06-17 19:00:27 +00001714void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00001715 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001716 const analyze_printf::OptionalAmount &Amt,
1717 unsigned type,
1718 const char *startSpecifier,
1719 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001720 const analyze_printf::PrintfConversionSpecifier &CS =
1721 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001722 switch (Amt.getHowSpecified()) {
1723 case analyze_printf::OptionalAmount::Constant:
1724 S.Diag(getLocationOfByte(Amt.getStart()),
1725 diag::warn_printf_nonsensical_optional_amount)
1726 << type
1727 << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001728 << getSpecifierRange(startSpecifier, specifierLen)
1729 << FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
Tom Caree4ee9662010-06-17 19:00:27 +00001730 Amt.getConstantLength()));
1731 break;
1732
1733 default:
1734 S.Diag(getLocationOfByte(Amt.getStart()),
1735 diag::warn_printf_nonsensical_optional_amount)
1736 << type
1737 << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001738 << getSpecifierRange(startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001739 break;
1740 }
1741}
1742
Ted Kremenek826a3452010-07-16 02:11:22 +00001743void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001744 const analyze_printf::OptionalFlag &flag,
1745 const char *startSpecifier,
1746 unsigned specifierLen) {
1747 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001748 const analyze_printf::PrintfConversionSpecifier &CS =
1749 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001750 S.Diag(getLocationOfByte(flag.getPosition()),
1751 diag::warn_printf_nonsensical_flag)
1752 << flag.toString() << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001753 << getSpecifierRange(startSpecifier, specifierLen)
1754 << FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1));
Tom Caree4ee9662010-06-17 19:00:27 +00001755}
1756
1757void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00001758 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001759 const analyze_printf::OptionalFlag &ignoredFlag,
1760 const analyze_printf::OptionalFlag &flag,
1761 const char *startSpecifier,
1762 unsigned specifierLen) {
1763 // Warn about ignored flag with a fixit removal.
1764 S.Diag(getLocationOfByte(ignoredFlag.getPosition()),
1765 diag::warn_printf_ignored_flag)
1766 << ignoredFlag.toString() << flag.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001767 << getSpecifierRange(startSpecifier, specifierLen)
1768 << FixItHint::CreateRemoval(getSpecifierRange(
Tom Caree4ee9662010-06-17 19:00:27 +00001769 ignoredFlag.getPosition(), 1));
1770}
1771
Ted Kremeneke0e53132010-01-28 23:39:18 +00001772bool
Ted Kremenek826a3452010-07-16 02:11:22 +00001773CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001774 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001775 const char *startSpecifier,
1776 unsigned specifierLen) {
1777
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001778 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00001779 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001780 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00001781
Ted Kremenekbaa40062010-07-19 22:01:06 +00001782 if (FS.consumesDataArgument()) {
1783 if (atFirstArg) {
1784 atFirstArg = false;
1785 usesPositionalArgs = FS.usesPositionalArg();
1786 }
1787 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1788 // Cannot mix-and-match positional and non-positional arguments.
1789 S.Diag(getLocationOfByte(CS.getStart()),
1790 diag::warn_format_mix_positional_nonpositional_args)
1791 << getSpecifierRange(startSpecifier, specifierLen);
1792 return false;
1793 }
Ted Kremenek0d277352010-01-29 01:06:55 +00001794 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001795
Ted Kremenekefaff192010-02-27 01:41:03 +00001796 // First check if the field width, precision, and conversion specifier
1797 // have matching data arguments.
1798 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1799 startSpecifier, specifierLen)) {
1800 return false;
1801 }
1802
1803 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1804 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001805 return false;
1806 }
1807
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001808 if (!CS.consumesDataArgument()) {
1809 // FIXME: Technically specifying a precision or field width here
1810 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001811 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001812 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001813
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001814 // Consume the argument.
1815 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00001816 if (argIndex < NumDataArgs) {
1817 // The check to see if the argIndex is valid will come later.
1818 // We set the bit here because we may exit early from this
1819 // function if we encounter some other error.
1820 CoveredArgs.set(argIndex);
1821 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001822
1823 // Check for using an Objective-C specific conversion specifier
1824 // in a non-ObjC literal.
1825 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001826 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
1827 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001828 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001829
Tom Caree4ee9662010-06-17 19:00:27 +00001830 // Check for invalid use of field width
1831 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001832 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00001833 startSpecifier, specifierLen);
1834 }
1835
1836 // Check for invalid use of precision
1837 if (!FS.hasValidPrecision()) {
1838 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
1839 startSpecifier, specifierLen);
1840 }
1841
1842 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00001843 if (!FS.hasValidThousandsGroupingPrefix())
1844 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001845 if (!FS.hasValidLeadingZeros())
1846 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
1847 if (!FS.hasValidPlusPrefix())
1848 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00001849 if (!FS.hasValidSpacePrefix())
1850 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001851 if (!FS.hasValidAlternativeForm())
1852 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
1853 if (!FS.hasValidLeftJustified())
1854 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
1855
1856 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00001857 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
1858 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
1859 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001860 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
1861 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
1862 startSpecifier, specifierLen);
1863
1864 // Check the length modifier is valid with the given conversion specifier.
1865 const LengthModifier &LM = FS.getLengthModifier();
1866 if (!FS.hasValidLengthModifier())
1867 S.Diag(getLocationOfByte(LM.getStart()),
Ted Kremenek649aecf2010-07-20 20:03:43 +00001868 diag::warn_format_nonsensical_length)
Tom Caree4ee9662010-06-17 19:00:27 +00001869 << LM.toString() << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001870 << getSpecifierRange(startSpecifier, specifierLen)
1871 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
Tom Caree4ee9662010-06-17 19:00:27 +00001872 LM.getLength()));
1873
1874 // Are we using '%n'?
Ted Kremenek35d353b2010-07-20 20:04:10 +00001875 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Caree4ee9662010-06-17 19:00:27 +00001876 // Issue a warning about this being a possible security issue.
Ted Kremeneke82d8042010-01-29 01:35:25 +00001877 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
Ted Kremenek826a3452010-07-16 02:11:22 +00001878 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremeneke82d8042010-01-29 01:35:25 +00001879 // Continue checking the other format specifiers.
1880 return true;
1881 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001882
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001883 // The remaining checks depend on the data arguments.
1884 if (HasVAListArg)
1885 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001886
Ted Kremenek666a1972010-07-26 19:45:42 +00001887 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001888 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001889
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001890 // Now type check the data expression that matches the
1891 // format specifier.
1892 const Expr *Ex = getDataArg(argIndex);
1893 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
1894 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
1895 // Check if we didn't match because of an implicit cast from a 'char'
1896 // or 'short' to an 'int'. This is done because printf is a varargs
1897 // function.
1898 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00001899 if (ICE->getType() == S.Context.IntTy) {
1900 // All further checking is done on the subexpression.
1901 Ex = ICE->getSubExpr();
1902 if (ATR.matchesType(S.Context, Ex->getType()))
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001903 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00001904 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001905
1906 // We may be able to offer a FixItHint if it is a supported type.
1907 PrintfSpecifier fixedFS = FS;
Hans Wennborga7da2152011-10-18 08:10:06 +00001908 bool success = fixedFS.fixType(Ex->getType(), S.getLangOptions());
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001909
1910 if (success) {
1911 // Get the fix string from the fixed format specifier
1912 llvm::SmallString<128> buf;
1913 llvm::raw_svector_ostream os(buf);
1914 fixedFS.toString(os);
1915
Ted Kremenek9325eaf2010-08-24 22:24:51 +00001916 // FIXME: getRepresentativeType() perhaps should return a string
1917 // instead of a QualType to better handle when the representative
1918 // type is 'wint_t' (which is defined in the system headers).
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001919 S.Diag(getLocationOfByte(CS.getStart()),
1920 diag::warn_printf_conversion_argument_type_mismatch)
1921 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1922 << getSpecifierRange(startSpecifier, specifierLen)
1923 << Ex->getSourceRange()
1924 << FixItHint::CreateReplacement(
1925 getSpecifierRange(startSpecifier, specifierLen),
1926 os.str());
1927 }
1928 else {
1929 S.Diag(getLocationOfByte(CS.getStart()),
1930 diag::warn_printf_conversion_argument_type_mismatch)
1931 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1932 << getSpecifierRange(startSpecifier, specifierLen)
1933 << Ex->getSourceRange();
1934 }
1935 }
1936
Ted Kremeneke0e53132010-01-28 23:39:18 +00001937 return true;
1938}
1939
Ted Kremenek826a3452010-07-16 02:11:22 +00001940//===--- CHECK: Scanf format string checking ------------------------------===//
1941
1942namespace {
1943class CheckScanfHandler : public CheckFormatHandler {
1944public:
1945 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
1946 const Expr *origFormatExpr, unsigned firstDataArg,
1947 unsigned numDataArgs, bool isObjCLiteral,
1948 const char *beg, bool hasVAListArg,
1949 const CallExpr *theCall, unsigned formatIdx)
1950 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1951 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1952 theCall, formatIdx) {}
1953
1954 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
1955 const char *startSpecifier,
1956 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001957
1958 bool HandleInvalidScanfConversionSpecifier(
1959 const analyze_scanf::ScanfSpecifier &FS,
1960 const char *startSpecifier,
1961 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00001962
1963 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00001964};
Ted Kremenek07d161f2010-01-29 01:50:07 +00001965}
Ted Kremeneke0e53132010-01-28 23:39:18 +00001966
Ted Kremenekb7c21012010-07-16 18:28:03 +00001967void CheckScanfHandler::HandleIncompleteScanList(const char *start,
1968 const char *end) {
1969 S.Diag(getLocationOfByte(end), diag::warn_scanf_scanlist_incomplete)
1970 << getSpecifierRange(start, end - start);
1971}
1972
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001973bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
1974 const analyze_scanf::ScanfSpecifier &FS,
1975 const char *startSpecifier,
1976 unsigned specifierLen) {
1977
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001978 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001979 FS.getConversionSpecifier();
1980
1981 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1982 getLocationOfByte(CS.getStart()),
1983 startSpecifier, specifierLen,
1984 CS.getStart(), CS.getLength());
1985}
1986
Ted Kremenek826a3452010-07-16 02:11:22 +00001987bool CheckScanfHandler::HandleScanfSpecifier(
1988 const analyze_scanf::ScanfSpecifier &FS,
1989 const char *startSpecifier,
1990 unsigned specifierLen) {
1991
1992 using namespace analyze_scanf;
1993 using namespace analyze_format_string;
1994
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001995 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001996
Ted Kremenekbaa40062010-07-19 22:01:06 +00001997 // Handle case where '%' and '*' don't consume an argument. These shouldn't
1998 // be used to decide if we are using positional arguments consistently.
1999 if (FS.consumesDataArgument()) {
2000 if (atFirstArg) {
2001 atFirstArg = false;
2002 usesPositionalArgs = FS.usesPositionalArg();
2003 }
2004 else if (usesPositionalArgs != FS.usesPositionalArg()) {
2005 // Cannot mix-and-match positional and non-positional arguments.
2006 S.Diag(getLocationOfByte(CS.getStart()),
2007 diag::warn_format_mix_positional_nonpositional_args)
2008 << getSpecifierRange(startSpecifier, specifierLen);
2009 return false;
2010 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002011 }
2012
2013 // Check if the field with is non-zero.
2014 const OptionalAmount &Amt = FS.getFieldWidth();
2015 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
2016 if (Amt.getConstantAmount() == 0) {
2017 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
2018 Amt.getConstantLength());
2019 S.Diag(getLocationOfByte(Amt.getStart()),
2020 diag::warn_scanf_nonzero_width)
2021 << R << FixItHint::CreateRemoval(R);
2022 }
2023 }
2024
2025 if (!FS.consumesDataArgument()) {
2026 // FIXME: Technically specifying a precision or field width here
2027 // makes no sense. Worth issuing a warning at some point.
2028 return true;
2029 }
2030
2031 // Consume the argument.
2032 unsigned argIndex = FS.getArgIndex();
2033 if (argIndex < NumDataArgs) {
2034 // The check to see if the argIndex is valid will come later.
2035 // We set the bit here because we may exit early from this
2036 // function if we encounter some other error.
2037 CoveredArgs.set(argIndex);
2038 }
2039
Ted Kremenek1e51c202010-07-20 20:04:47 +00002040 // Check the length modifier is valid with the given conversion specifier.
2041 const LengthModifier &LM = FS.getLengthModifier();
2042 if (!FS.hasValidLengthModifier()) {
2043 S.Diag(getLocationOfByte(LM.getStart()),
2044 diag::warn_format_nonsensical_length)
2045 << LM.toString() << CS.toString()
2046 << getSpecifierRange(startSpecifier, specifierLen)
2047 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
2048 LM.getLength()));
2049 }
2050
Ted Kremenek826a3452010-07-16 02:11:22 +00002051 // The remaining checks depend on the data arguments.
2052 if (HasVAListArg)
2053 return true;
2054
Ted Kremenek666a1972010-07-26 19:45:42 +00002055 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00002056 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00002057
2058 // FIXME: Check that the argument type matches the format specifier.
2059
2060 return true;
2061}
2062
2063void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002064 const Expr *OrigFormatExpr,
2065 const CallExpr *TheCall, bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00002066 unsigned format_idx, unsigned firstDataArg,
2067 bool isPrintf) {
2068
Ted Kremeneke0e53132010-01-28 23:39:18 +00002069 // CHECK: is the format string a wide literal?
Douglas Gregor5cee1192011-07-27 05:40:30 +00002070 if (!FExpr->isAscii()) {
Ted Kremeneke0e53132010-01-28 23:39:18 +00002071 Diag(FExpr->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00002072 diag::warn_format_string_is_wide_literal)
Ted Kremeneke0e53132010-01-28 23:39:18 +00002073 << OrigFormatExpr->getSourceRange();
2074 return;
2075 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002076
Ted Kremeneke0e53132010-01-28 23:39:18 +00002077 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00002078 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00002079 const char *Str = StrRef.data();
2080 unsigned StrLen = StrRef.size();
Ted Kremenek4cd57912011-09-29 05:52:16 +00002081 const unsigned numDataArgs = TheCall->getNumArgs() - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00002082
Ted Kremeneke0e53132010-01-28 23:39:18 +00002083 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00002084 if (StrLen == 0 && numDataArgs > 0) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002085 Diag(FExpr->getLocStart(), diag::warn_empty_format_string)
Ted Kremeneke0e53132010-01-28 23:39:18 +00002086 << OrigFormatExpr->getSourceRange();
2087 return;
2088 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002089
2090 if (isPrintf) {
2091 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremenek4cd57912011-09-29 05:52:16 +00002092 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
2093 Str, HasVAListArg, TheCall, format_idx);
Ted Kremenek826a3452010-07-16 02:11:22 +00002094
2095 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen))
2096 H.DoneProcessing();
2097 }
2098 else {
2099 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremenek4cd57912011-09-29 05:52:16 +00002100 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
2101 Str, HasVAListArg, TheCall, format_idx);
Ted Kremenek826a3452010-07-16 02:11:22 +00002102
2103 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen))
2104 H.DoneProcessing();
2105 }
Ted Kremenekce7024e2010-01-28 01:18:22 +00002106}
2107
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002108//===--- CHECK: Standard memory functions ---------------------------------===//
2109
Douglas Gregor2a053a32011-05-03 20:05:22 +00002110/// \brief Determine whether the given type is a dynamic class type (e.g.,
2111/// whether it has a vtable).
2112static bool isDynamicClassType(QualType T) {
2113 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
2114 if (CXXRecordDecl *Definition = Record->getDefinition())
2115 if (Definition->isDynamicClass())
2116 return true;
2117
2118 return false;
2119}
2120
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002121/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00002122/// otherwise returns NULL.
2123static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00002124 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00002125 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2126 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
2127 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002128
Chandler Carruth000d4282011-06-16 09:09:40 +00002129 return 0;
2130}
2131
Chandler Carrutha72a12f2011-06-21 23:04:20 +00002132/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00002133static QualType getSizeOfArgType(const Expr* E) {
2134 if (const UnaryExprOrTypeTraitExpr *SizeOf =
2135 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2136 if (SizeOf->getKind() == clang::UETT_SizeOf)
2137 return SizeOf->getTypeOfArgument();
2138
2139 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00002140}
2141
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002142/// \brief Check for dangerous or invalid arguments to memset().
2143///
Chandler Carruth929f0132011-06-03 06:23:57 +00002144/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002145/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
2146/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002147///
2148/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00002149void Sema::CheckMemaccessArguments(const CallExpr *Call,
2150 CheckedMemoryFunction CMF,
2151 IdentifierInfo *FnName) {
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002152 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00002153 // we have enough arguments, and if not, abort further checking.
Nico Webercda57822011-10-13 22:30:23 +00002154 unsigned ExpectedNumArgs = (CMF == CMF_Strndup ? 2 : 3);
2155 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00002156 return;
2157
Nico Webercda57822011-10-13 22:30:23 +00002158 unsigned LastArg = (CMF == CMF_Memset || CMF == CMF_Strndup ? 1 : 2);
2159 unsigned LenArg = (CMF == CMF_Strndup ? 1 : 2);
2160 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00002161
2162 // We have special checking when the length is a sizeof expression.
2163 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
2164 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
2165 llvm::FoldingSetNodeID SizeOfArgID;
2166
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002167 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
2168 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00002169 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002170
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002171 QualType DestTy = Dest->getType();
2172 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
2173 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00002174
Chandler Carruth000d4282011-06-16 09:09:40 +00002175 // Never warn about void type pointers. This can be used to suppress
2176 // false positives.
2177 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002178 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002179
Chandler Carruth000d4282011-06-16 09:09:40 +00002180 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
2181 // actually comparing the expressions for equality. Because computing the
2182 // expression IDs can be expensive, we only do this if the diagnostic is
2183 // enabled.
2184 if (SizeOfArg &&
2185 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
2186 SizeOfArg->getExprLoc())) {
2187 // We only compute IDs for expressions if the warning is enabled, and
2188 // cache the sizeof arg's ID.
2189 if (SizeOfArgID == llvm::FoldingSetNodeID())
2190 SizeOfArg->Profile(SizeOfArgID, Context, true);
2191 llvm::FoldingSetNodeID DestID;
2192 Dest->Profile(DestID, Context, true);
2193 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00002194 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
2195 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00002196 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
2197 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
2198 if (UnaryOp->getOpcode() == UO_AddrOf)
2199 ActionIdx = 1; // If its an address-of operator, just remove it.
2200 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
2201 ActionIdx = 2; // If the pointee's size is sizeof(char),
2202 // suggest an explicit length.
Nico Webercda57822011-10-13 22:30:23 +00002203 unsigned DestSrcSelect = (CMF == CMF_Strndup ? 1 : ArgIdx);
Chandler Carruth000d4282011-06-16 09:09:40 +00002204 DiagRuntimeBehavior(SizeOfArg->getExprLoc(), Dest,
2205 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Nico Webercda57822011-10-13 22:30:23 +00002206 << FnName << DestSrcSelect << ActionIdx
Chandler Carruth000d4282011-06-16 09:09:40 +00002207 << Dest->getSourceRange()
2208 << SizeOfArg->getSourceRange());
2209 break;
2210 }
2211 }
2212
2213 // Also check for cases where the sizeof argument is the exact same
2214 // type as the memory argument, and where it points to a user-defined
2215 // record type.
2216 if (SizeOfArgTy != QualType()) {
2217 if (PointeeTy->isRecordType() &&
2218 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
2219 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
2220 PDiag(diag::warn_sizeof_pointer_type_memaccess)
2221 << FnName << SizeOfArgTy << ArgIdx
2222 << PointeeTy << Dest->getSourceRange()
2223 << LenExpr->getSourceRange());
2224 break;
2225 }
Nico Webere4a1c642011-06-14 16:14:58 +00002226 }
2227
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002228 // Always complain about dynamic classes.
John McCallf85e1932011-06-15 23:02:42 +00002229 if (isDynamicClassType(PointeeTy))
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002230 DiagRuntimeBehavior(
2231 Dest->getExprLoc(), Dest,
2232 PDiag(diag::warn_dyn_class_memaccess)
2233 << (CMF == CMF_Memcmp ? ArgIdx + 2 : ArgIdx) << FnName << PointeeTy
2234 // "overwritten" if we're warning about the destination for any call
2235 // but memcmp; otherwise a verb appropriate to the call.
2236 << (ArgIdx == 0 && CMF != CMF_Memcmp ? 0 : (unsigned)CMF)
2237 << Call->getCallee()->getSourceRange());
Douglas Gregor707a23e2011-06-16 17:56:04 +00002238 else if (PointeeTy.hasNonTrivialObjCLifetime() && CMF != CMF_Memset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00002239 DiagRuntimeBehavior(
2240 Dest->getExprLoc(), Dest,
2241 PDiag(diag::warn_arc_object_memaccess)
2242 << ArgIdx << FnName << PointeeTy
2243 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00002244 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002245 continue;
John McCallf85e1932011-06-15 23:02:42 +00002246
2247 DiagRuntimeBehavior(
2248 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00002249 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00002250 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
2251 break;
2252 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00002253 }
2254}
2255
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002256// A little helper routine: ignore addition and subtraction of integer literals.
2257// This intentionally does not ignore all integer constant expressions because
2258// we don't want to remove sizeof().
2259static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
2260 Ex = Ex->IgnoreParenCasts();
2261
2262 for (;;) {
2263 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
2264 if (!BO || !BO->isAdditiveOp())
2265 break;
2266
2267 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
2268 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
2269
2270 if (isa<IntegerLiteral>(RHS))
2271 Ex = LHS;
2272 else if (isa<IntegerLiteral>(LHS))
2273 Ex = RHS;
2274 else
2275 break;
2276 }
2277
2278 return Ex;
2279}
2280
2281// Warn if the user has made the 'size' argument to strlcpy or strlcat
2282// be the size of the source, instead of the destination.
2283void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
2284 IdentifierInfo *FnName) {
2285
2286 // Don't crash if the user has the wrong number of arguments
2287 if (Call->getNumArgs() != 3)
2288 return;
2289
2290 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
2291 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
2292 const Expr *CompareWithSrc = NULL;
2293
2294 // Look for 'strlcpy(dst, x, sizeof(x))'
2295 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
2296 CompareWithSrc = Ex;
2297 else {
2298 // Look for 'strlcpy(dst, x, strlen(x))'
2299 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
2300 if (SizeCall->isBuiltinCall(Context) == Builtin::BIstrlen
2301 && SizeCall->getNumArgs() == 1)
2302 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
2303 }
2304 }
2305
2306 if (!CompareWithSrc)
2307 return;
2308
2309 // Determine if the argument to sizeof/strlen is equal to the source
2310 // argument. In principle there's all kinds of things you could do
2311 // here, for instance creating an == expression and evaluating it with
2312 // EvaluateAsBooleanCondition, but this uses a more direct technique:
2313 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
2314 if (!SrcArgDRE)
2315 return;
2316
2317 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
2318 if (!CompareWithSrcDRE ||
2319 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
2320 return;
2321
2322 const Expr *OriginalSizeArg = Call->getArg(2);
2323 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
2324 << OriginalSizeArg->getSourceRange() << FnName;
2325
2326 // Output a FIXIT hint if the destination is an array (rather than a
2327 // pointer to an array). This could be enhanced to handle some
2328 // pointers if we know the actual size, like if DstArg is 'array+2'
2329 // we could say 'sizeof(array)-2'.
2330 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Ted Kremenek8f746222011-08-18 22:48:41 +00002331 QualType DstArgTy = DstArg->getType();
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002332
Ted Kremenek8f746222011-08-18 22:48:41 +00002333 // Only handle constant-sized or VLAs, but not flexible members.
2334 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
2335 // Only issue the FIXIT for arrays of size > 1.
2336 if (CAT->getSize().getSExtValue() <= 1)
2337 return;
2338 } else if (!DstArgTy->isVariableArrayType()) {
2339 return;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002340 }
Ted Kremenek8f746222011-08-18 22:48:41 +00002341
2342 llvm::SmallString<128> sizeString;
2343 llvm::raw_svector_ostream OS(sizeString);
2344 OS << "sizeof(";
Douglas Gregor8987b232011-09-27 23:30:47 +00002345 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00002346 OS << ")";
2347
2348 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
2349 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
2350 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00002351}
2352
Ted Kremenek06de2762007-08-17 16:46:58 +00002353//===--- CHECK: Return Address of Stack Variable --------------------------===//
2354
Chris Lattner5f9e2722011-07-23 10:55:15 +00002355static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars);
2356static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002357
2358/// CheckReturnStackAddr - Check if a return statement returns the address
2359/// of a stack variable.
2360void
2361Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
2362 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00002363
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002364 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002365 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002366
2367 // Perform checking for returned stack addresses, local blocks,
2368 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00002369 if (lhsType->isPointerType() ||
2370 (!getLangOptions().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002371 stackE = EvalAddr(RetValExp, refVars);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002372 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002373 stackE = EvalVal(RetValExp, refVars);
2374 }
2375
2376 if (stackE == 0)
2377 return; // Nothing suspicious was found.
2378
2379 SourceLocation diagLoc;
2380 SourceRange diagRange;
2381 if (refVars.empty()) {
2382 diagLoc = stackE->getLocStart();
2383 diagRange = stackE->getSourceRange();
2384 } else {
2385 // We followed through a reference variable. 'stackE' contains the
2386 // problematic expression but we will warn at the return statement pointing
2387 // at the reference variable. We will later display the "trail" of
2388 // reference variables using notes.
2389 diagLoc = refVars[0]->getLocStart();
2390 diagRange = refVars[0]->getSourceRange();
2391 }
2392
2393 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
2394 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
2395 : diag::warn_ret_stack_addr)
2396 << DR->getDecl()->getDeclName() << diagRange;
2397 } else if (isa<BlockExpr>(stackE)) { // local block.
2398 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
2399 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
2400 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
2401 } else { // local temporary.
2402 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
2403 : diag::warn_ret_local_temp_addr)
2404 << diagRange;
2405 }
2406
2407 // Display the "trail" of reference variables that we followed until we
2408 // found the problematic expression using notes.
2409 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
2410 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
2411 // If this var binds to another reference var, show the range of the next
2412 // var, otherwise the var binds to the problematic expression, in which case
2413 // show the range of the expression.
2414 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
2415 : stackE->getSourceRange();
2416 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
2417 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00002418 }
2419}
2420
2421/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
2422/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002423/// to a location on the stack, a local block, an address of a label, or a
2424/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00002425/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002426/// encounter a subexpression that (1) clearly does not lead to one of the
2427/// above problematic expressions (2) is something we cannot determine leads to
2428/// a problematic expression based on such local checking.
2429///
2430/// Both EvalAddr and EvalVal follow through reference variables to evaluate
2431/// the expression that they point to. Such variables are added to the
2432/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00002433///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002434/// EvalAddr processes expressions that are pointers that are used as
2435/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002436/// At the base case of the recursion is a check for the above problematic
2437/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00002438///
2439/// This implementation handles:
2440///
2441/// * pointer-to-pointer casts
2442/// * implicit conversions from array references to pointers
2443/// * taking the address of fields
2444/// * arbitrary interplay between "&" and "*" operators
2445/// * pointer arithmetic from an address of a stack variable
2446/// * taking the address of an array element where the array is on the stack
Chris Lattner5f9e2722011-07-23 10:55:15 +00002447static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002448 if (E->isTypeDependent())
2449 return NULL;
2450
Ted Kremenek06de2762007-08-17 16:46:58 +00002451 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00002452 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00002453 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002454 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002455 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00002456
Peter Collingbournef111d932011-04-15 00:35:48 +00002457 E = E->IgnoreParens();
2458
Ted Kremenek06de2762007-08-17 16:46:58 +00002459 // Our "symbolic interpreter" is just a dispatch off the currently
2460 // viewed AST node. We then recursively traverse the AST by calling
2461 // EvalAddr and EvalVal appropriately.
2462 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002463 case Stmt::DeclRefExprClass: {
2464 DeclRefExpr *DR = cast<DeclRefExpr>(E);
2465
2466 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
2467 // If this is a reference variable, follow through to the expression that
2468 // it points to.
2469 if (V->hasLocalStorage() &&
2470 V->getType()->isReferenceType() && V->hasInit()) {
2471 // Add the reference variable to the "trail".
2472 refVars.push_back(DR);
2473 return EvalAddr(V->getInit(), refVars);
2474 }
2475
2476 return NULL;
2477 }
Ted Kremenek06de2762007-08-17 16:46:58 +00002478
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002479 case Stmt::UnaryOperatorClass: {
2480 // The only unary operator that make sense to handle here
2481 // is AddrOf. All others don't make sense as pointers.
2482 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002483
John McCall2de56d12010-08-25 11:45:40 +00002484 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002485 return EvalVal(U->getSubExpr(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002486 else
Ted Kremenek06de2762007-08-17 16:46:58 +00002487 return NULL;
2488 }
Mike Stump1eb44332009-09-09 15:08:12 +00002489
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002490 case Stmt::BinaryOperatorClass: {
2491 // Handle pointer arithmetic. All other binary operators are not valid
2492 // in this context.
2493 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00002494 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00002495
John McCall2de56d12010-08-25 11:45:40 +00002496 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002497 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00002498
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002499 Expr *Base = B->getLHS();
2500
2501 // Determine which argument is the real pointer base. It could be
2502 // the RHS argument instead of the LHS.
2503 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00002504
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002505 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002506 return EvalAddr(Base, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002507 }
Steve Naroff61f40a22008-09-10 19:17:48 +00002508
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002509 // For conditional operators we need to see if either the LHS or RHS are
2510 // valid DeclRefExpr*s. If one of them is valid, we return it.
2511 case Stmt::ConditionalOperatorClass: {
2512 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002513
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002514 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002515 if (Expr *lhsExpr = C->getLHS()) {
2516 // In C++, we can have a throw-expression, which has 'void' type.
2517 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002518 if (Expr* LHS = EvalAddr(lhsExpr, refVars))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002519 return LHS;
2520 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002521
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002522 // In C++, we can have a throw-expression, which has 'void' type.
2523 if (C->getRHS()->getType()->isVoidType())
2524 return NULL;
2525
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002526 return EvalAddr(C->getRHS(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002527 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002528
2529 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00002530 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002531 return E; // local block.
2532 return NULL;
2533
2534 case Stmt::AddrLabelExprClass:
2535 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00002536
Ted Kremenek54b52742008-08-07 00:49:01 +00002537 // For casts, we need to handle conversions from arrays to
2538 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00002539 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002540 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00002541 case Stmt::CXXFunctionalCastExprClass:
2542 case Stmt::ObjCBridgedCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002543 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00002544 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002545
Steve Naroffdd972f22008-09-05 22:11:13 +00002546 if (SubExpr->getType()->isPointerType() ||
2547 SubExpr->getType()->isBlockPointerType() ||
2548 SubExpr->getType()->isObjCQualifiedIdType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002549 return EvalAddr(SubExpr, refVars);
Ted Kremenek54b52742008-08-07 00:49:01 +00002550 else if (T->isArrayType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002551 return EvalVal(SubExpr, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002552 else
Ted Kremenek54b52742008-08-07 00:49:01 +00002553 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002554 }
Mike Stump1eb44332009-09-09 15:08:12 +00002555
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002556 // C++ casts. For dynamic casts, static casts, and const casts, we
2557 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00002558 // through the cast. In the case the dynamic cast doesn't fail (and
2559 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002560 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00002561 // FIXME: The comment about is wrong; we're not always converting
2562 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00002563 // handle references to objects.
2564 case Stmt::CXXStaticCastExprClass:
2565 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00002566 case Stmt::CXXConstCastExprClass:
2567 case Stmt::CXXReinterpretCastExprClass: {
2568 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00002569 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002570 return EvalAddr(S, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002571 else
2572 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002573 }
Mike Stump1eb44332009-09-09 15:08:12 +00002574
Douglas Gregor03e80032011-06-21 17:03:29 +00002575 case Stmt::MaterializeTemporaryExprClass:
2576 if (Expr *Result = EvalAddr(
2577 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
2578 refVars))
2579 return Result;
2580
2581 return E;
2582
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002583 // Everything else: we simply don't reason about them.
2584 default:
2585 return NULL;
2586 }
Ted Kremenek06de2762007-08-17 16:46:58 +00002587}
Mike Stump1eb44332009-09-09 15:08:12 +00002588
Ted Kremenek06de2762007-08-17 16:46:58 +00002589
2590/// EvalVal - This function is complements EvalAddr in the mutual recursion.
2591/// See the comments for EvalAddr for more details.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002592static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002593do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002594 // We should only be called for evaluating non-pointer expressions, or
2595 // expressions with a pointer type that are not used as references but instead
2596 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00002597
Ted Kremenek06de2762007-08-17 16:46:58 +00002598 // Our "symbolic interpreter" is just a dispatch off the currently
2599 // viewed AST node. We then recursively traverse the AST by calling
2600 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00002601
2602 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00002603 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002604 case Stmt::ImplicitCastExprClass: {
2605 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00002606 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002607 E = IE->getSubExpr();
2608 continue;
2609 }
2610 return NULL;
2611 }
2612
Douglas Gregora2813ce2009-10-23 18:54:35 +00002613 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002614 // When we hit a DeclRefExpr we are looking at code that refers to a
2615 // variable's name. If it's not a reference variable we check if it has
2616 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00002617 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002618
Ted Kremenek06de2762007-08-17 16:46:58 +00002619 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002620 if (V->hasLocalStorage()) {
2621 if (!V->getType()->isReferenceType())
2622 return DR;
2623
2624 // Reference variable, follow through to the expression that
2625 // it points to.
2626 if (V->hasInit()) {
2627 // Add the reference variable to the "trail".
2628 refVars.push_back(DR);
2629 return EvalVal(V->getInit(), refVars);
2630 }
2631 }
Mike Stump1eb44332009-09-09 15:08:12 +00002632
Ted Kremenek06de2762007-08-17 16:46:58 +00002633 return NULL;
2634 }
Mike Stump1eb44332009-09-09 15:08:12 +00002635
Ted Kremenek06de2762007-08-17 16:46:58 +00002636 case Stmt::UnaryOperatorClass: {
2637 // The only unary operator that make sense to handle here
2638 // is Deref. All others don't resolve to a "name." This includes
2639 // handling all sorts of rvalues passed to a unary operator.
2640 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002641
John McCall2de56d12010-08-25 11:45:40 +00002642 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002643 return EvalAddr(U->getSubExpr(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002644
2645 return NULL;
2646 }
Mike Stump1eb44332009-09-09 15:08:12 +00002647
Ted Kremenek06de2762007-08-17 16:46:58 +00002648 case Stmt::ArraySubscriptExprClass: {
2649 // Array subscripts are potential references to data on the stack. We
2650 // retrieve the DeclRefExpr* for the array variable if it indeed
2651 // has local storage.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002652 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002653 }
Mike Stump1eb44332009-09-09 15:08:12 +00002654
Ted Kremenek06de2762007-08-17 16:46:58 +00002655 case Stmt::ConditionalOperatorClass: {
2656 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002657 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00002658 ConditionalOperator *C = cast<ConditionalOperator>(E);
2659
Anders Carlsson39073232007-11-30 19:04:31 +00002660 // Handle the GNU extension for missing LHS.
2661 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002662 if (Expr *LHS = EvalVal(lhsExpr, refVars))
Anders Carlsson39073232007-11-30 19:04:31 +00002663 return LHS;
2664
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002665 return EvalVal(C->getRHS(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002666 }
Mike Stump1eb44332009-09-09 15:08:12 +00002667
Ted Kremenek06de2762007-08-17 16:46:58 +00002668 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00002669 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00002670 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002671
Ted Kremenek06de2762007-08-17 16:46:58 +00002672 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00002673 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00002674 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00002675
2676 // Check whether the member type is itself a reference, in which case
2677 // we're not going to refer to the member, but to what the member refers to.
2678 if (M->getMemberDecl()->getType()->isReferenceType())
2679 return NULL;
2680
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002681 return EvalVal(M->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002682 }
Mike Stump1eb44332009-09-09 15:08:12 +00002683
Douglas Gregor03e80032011-06-21 17:03:29 +00002684 case Stmt::MaterializeTemporaryExprClass:
2685 if (Expr *Result = EvalVal(
2686 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
2687 refVars))
2688 return Result;
2689
2690 return E;
2691
Ted Kremenek06de2762007-08-17 16:46:58 +00002692 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002693 // Check that we don't return or take the address of a reference to a
2694 // temporary. This is only useful in C++.
2695 if (!E->isTypeDependent() && E->isRValue())
2696 return E;
2697
2698 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00002699 return NULL;
2700 }
Ted Kremenek68957a92010-08-04 20:01:07 +00002701} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00002702}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002703
2704//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
2705
2706/// Check for comparisons of floating point operands using != and ==.
2707/// Issue a warning if these are no self-comparisons, as they are not likely
2708/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00002709void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002710 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002711
Richard Trieudd225092011-09-15 21:56:47 +00002712 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
2713 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002714
2715 // Special case: check for x == x (which is OK).
2716 // Do not emit warnings for such cases.
2717 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
2718 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
2719 if (DRL->getDecl() == DRR->getDecl())
2720 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002721
2722
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002723 // Special case: check for comparisons against literals that can be exactly
2724 // represented by APFloat. In such cases, do not emit a warning. This
2725 // is a heuristic: often comparison against such literals are used to
2726 // detect if a value in a variable has not changed. This clearly can
2727 // lead to false negatives.
2728 if (EmitWarning) {
2729 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
2730 if (FLL->isExact())
2731 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002732 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002733 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
2734 if (FLR->isExact())
2735 EmitWarning = false;
2736 }
2737 }
Mike Stump1eb44332009-09-09 15:08:12 +00002738
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002739 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002740 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002741 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002742 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002743 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002744
Sebastian Redl0eb23302009-01-19 00:08:26 +00002745 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002746 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002747 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002748 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002749
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002750 // Emit the diagnostic.
2751 if (EmitWarning)
Richard Trieudd225092011-09-15 21:56:47 +00002752 Diag(Loc, diag::warn_floatingpoint_eq)
2753 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002754}
John McCallba26e582010-01-04 23:21:16 +00002755
John McCallf2370c92010-01-06 05:24:50 +00002756//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
2757//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00002758
John McCallf2370c92010-01-06 05:24:50 +00002759namespace {
John McCallba26e582010-01-04 23:21:16 +00002760
John McCallf2370c92010-01-06 05:24:50 +00002761/// Structure recording the 'active' range of an integer-valued
2762/// expression.
2763struct IntRange {
2764 /// The number of bits active in the int.
2765 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00002766
John McCallf2370c92010-01-06 05:24:50 +00002767 /// True if the int is known not to have negative values.
2768 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00002769
John McCallf2370c92010-01-06 05:24:50 +00002770 IntRange(unsigned Width, bool NonNegative)
2771 : Width(Width), NonNegative(NonNegative)
2772 {}
John McCallba26e582010-01-04 23:21:16 +00002773
John McCall1844a6e2010-11-10 23:38:19 +00002774 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00002775 static IntRange forBoolType() {
2776 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00002777 }
2778
John McCall1844a6e2010-11-10 23:38:19 +00002779 /// Returns the range of an opaque value of the given integral type.
2780 static IntRange forValueOfType(ASTContext &C, QualType T) {
2781 return forValueOfCanonicalType(C,
2782 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00002783 }
2784
John McCall1844a6e2010-11-10 23:38:19 +00002785 /// Returns the range of an opaque value of a canonical integral type.
2786 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00002787 assert(T->isCanonicalUnqualified());
2788
2789 if (const VectorType *VT = dyn_cast<VectorType>(T))
2790 T = VT->getElementType().getTypePtr();
2791 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2792 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00002793
John McCall091f23f2010-11-09 22:22:12 +00002794 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00002795 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
2796 EnumDecl *Enum = ET->getDecl();
John McCall5e1cdac2011-10-07 06:10:15 +00002797 if (!Enum->isCompleteDefinition())
John McCall091f23f2010-11-09 22:22:12 +00002798 return IntRange(C.getIntWidth(QualType(T, 0)), false);
2799
John McCall323ed742010-05-06 08:58:33 +00002800 unsigned NumPositive = Enum->getNumPositiveBits();
2801 unsigned NumNegative = Enum->getNumNegativeBits();
2802
2803 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
2804 }
John McCallf2370c92010-01-06 05:24:50 +00002805
2806 const BuiltinType *BT = cast<BuiltinType>(T);
2807 assert(BT->isInteger());
2808
2809 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2810 }
2811
John McCall1844a6e2010-11-10 23:38:19 +00002812 /// Returns the "target" range of a canonical integral type, i.e.
2813 /// the range of values expressible in the type.
2814 ///
2815 /// This matches forValueOfCanonicalType except that enums have the
2816 /// full range of their type, not the range of their enumerators.
2817 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
2818 assert(T->isCanonicalUnqualified());
2819
2820 if (const VectorType *VT = dyn_cast<VectorType>(T))
2821 T = VT->getElementType().getTypePtr();
2822 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2823 T = CT->getElementType().getTypePtr();
2824 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00002825 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00002826
2827 const BuiltinType *BT = cast<BuiltinType>(T);
2828 assert(BT->isInteger());
2829
2830 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2831 }
2832
2833 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002834 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00002835 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00002836 L.NonNegative && R.NonNegative);
2837 }
2838
John McCall1844a6e2010-11-10 23:38:19 +00002839 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002840 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00002841 return IntRange(std::min(L.Width, R.Width),
2842 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00002843 }
2844};
2845
2846IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
2847 if (value.isSigned() && value.isNegative())
2848 return IntRange(value.getMinSignedBits(), false);
2849
2850 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002851 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00002852
2853 // isNonNegative() just checks the sign bit without considering
2854 // signedness.
2855 return IntRange(value.getActiveBits(), true);
2856}
2857
John McCall0acc3112010-01-06 22:57:21 +00002858IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCallf2370c92010-01-06 05:24:50 +00002859 unsigned MaxWidth) {
2860 if (result.isInt())
2861 return GetValueRange(C, result.getInt(), MaxWidth);
2862
2863 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00002864 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
2865 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
2866 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
2867 R = IntRange::join(R, El);
2868 }
John McCallf2370c92010-01-06 05:24:50 +00002869 return R;
2870 }
2871
2872 if (result.isComplexInt()) {
2873 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
2874 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
2875 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00002876 }
2877
2878 // This can happen with lossless casts to intptr_t of "based" lvalues.
2879 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00002880 // FIXME: The only reason we need to pass the type in here is to get
2881 // the sign right on this one case. It would be nice if APValue
2882 // preserved this.
John McCallf2370c92010-01-06 05:24:50 +00002883 assert(result.isLValue());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00002884 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00002885}
John McCallf2370c92010-01-06 05:24:50 +00002886
2887/// Pseudo-evaluate the given integer expression, estimating the
2888/// range of values it might take.
2889///
2890/// \param MaxWidth - the width to which the value will be truncated
2891IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
2892 E = E->IgnoreParens();
2893
2894 // Try a full evaluation first.
2895 Expr::EvalResult result;
2896 if (E->Evaluate(result, C))
John McCall0acc3112010-01-06 22:57:21 +00002897 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00002898
2899 // I think we only want to look through implicit casts here; if the
2900 // user has an explicit widening cast, we should treat the value as
2901 // being of the new, wider type.
2902 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00002903 if (CE->getCastKind() == CK_NoOp)
John McCallf2370c92010-01-06 05:24:50 +00002904 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
2905
John McCall1844a6e2010-11-10 23:38:19 +00002906 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00002907
John McCall2de56d12010-08-25 11:45:40 +00002908 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00002909
John McCallf2370c92010-01-06 05:24:50 +00002910 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00002911 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00002912 return OutputTypeRange;
2913
2914 IntRange SubRange
2915 = GetExprRange(C, CE->getSubExpr(),
2916 std::min(MaxWidth, OutputTypeRange.Width));
2917
2918 // Bail out if the subexpr's range is as wide as the cast type.
2919 if (SubRange.Width >= OutputTypeRange.Width)
2920 return OutputTypeRange;
2921
2922 // Otherwise, we take the smaller width, and we're non-negative if
2923 // either the output type or the subexpr is.
2924 return IntRange(SubRange.Width,
2925 SubRange.NonNegative || OutputTypeRange.NonNegative);
2926 }
2927
2928 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2929 // If we can fold the condition, just take that operand.
2930 bool CondResult;
2931 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
2932 return GetExprRange(C, CondResult ? CO->getTrueExpr()
2933 : CO->getFalseExpr(),
2934 MaxWidth);
2935
2936 // Otherwise, conservatively merge.
2937 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
2938 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
2939 return IntRange::join(L, R);
2940 }
2941
2942 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2943 switch (BO->getOpcode()) {
2944
2945 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00002946 case BO_LAnd:
2947 case BO_LOr:
2948 case BO_LT:
2949 case BO_GT:
2950 case BO_LE:
2951 case BO_GE:
2952 case BO_EQ:
2953 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00002954 return IntRange::forBoolType();
2955
John McCall862ff872011-07-13 06:35:24 +00002956 // The type of the assignments is the type of the LHS, so the RHS
2957 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00002958 case BO_MulAssign:
2959 case BO_DivAssign:
2960 case BO_RemAssign:
2961 case BO_AddAssign:
2962 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00002963 case BO_XorAssign:
2964 case BO_OrAssign:
2965 // TODO: bitfields?
John McCall1844a6e2010-11-10 23:38:19 +00002966 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00002967
John McCall862ff872011-07-13 06:35:24 +00002968 // Simple assignments just pass through the RHS, which will have
2969 // been coerced to the LHS type.
2970 case BO_Assign:
2971 // TODO: bitfields?
2972 return GetExprRange(C, BO->getRHS(), MaxWidth);
2973
John McCallf2370c92010-01-06 05:24:50 +00002974 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00002975 case BO_PtrMemD:
2976 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00002977 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002978
John McCall60fad452010-01-06 22:07:33 +00002979 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00002980 case BO_And:
2981 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00002982 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
2983 GetExprRange(C, BO->getRHS(), MaxWidth));
2984
John McCallf2370c92010-01-06 05:24:50 +00002985 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00002986 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00002987 // ...except that we want to treat '1 << (blah)' as logically
2988 // positive. It's an important idiom.
2989 if (IntegerLiteral *I
2990 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
2991 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00002992 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00002993 return IntRange(R.Width, /*NonNegative*/ true);
2994 }
2995 }
2996 // fallthrough
2997
John McCall2de56d12010-08-25 11:45:40 +00002998 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00002999 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003000
John McCall60fad452010-01-06 22:07:33 +00003001 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00003002 case BO_Shr:
3003 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00003004 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3005
3006 // If the shift amount is a positive constant, drop the width by
3007 // that much.
3008 llvm::APSInt shift;
3009 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
3010 shift.isNonNegative()) {
3011 unsigned zext = shift.getZExtValue();
3012 if (zext >= L.Width)
3013 L.Width = (L.NonNegative ? 0 : 1);
3014 else
3015 L.Width -= zext;
3016 }
3017
3018 return L;
3019 }
3020
3021 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00003022 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00003023 return GetExprRange(C, BO->getRHS(), MaxWidth);
3024
John McCall60fad452010-01-06 22:07:33 +00003025 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00003026 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00003027 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00003028 return IntRange::forValueOfType(C, E->getType());
John McCall00fe7612011-07-14 22:39:48 +00003029 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003030
John McCall00fe7612011-07-14 22:39:48 +00003031 // The width of a division result is mostly determined by the size
3032 // of the LHS.
3033 case BO_Div: {
3034 // Don't 'pre-truncate' the operands.
3035 unsigned opWidth = C.getIntWidth(E->getType());
3036 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3037
3038 // If the divisor is constant, use that.
3039 llvm::APSInt divisor;
3040 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
3041 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
3042 if (log2 >= L.Width)
3043 L.Width = (L.NonNegative ? 0 : 1);
3044 else
3045 L.Width = std::min(L.Width - log2, MaxWidth);
3046 return L;
3047 }
3048
3049 // Otherwise, just use the LHS's width.
3050 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3051 return IntRange(L.Width, L.NonNegative && R.NonNegative);
3052 }
3053
3054 // The result of a remainder can't be larger than the result of
3055 // either side.
3056 case BO_Rem: {
3057 // Don't 'pre-truncate' the operands.
3058 unsigned opWidth = C.getIntWidth(E->getType());
3059 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3060 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3061
3062 IntRange meet = IntRange::meet(L, R);
3063 meet.Width = std::min(meet.Width, MaxWidth);
3064 return meet;
3065 }
3066
3067 // The default behavior is okay for these.
3068 case BO_Mul:
3069 case BO_Add:
3070 case BO_Xor:
3071 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00003072 break;
3073 }
3074
John McCall00fe7612011-07-14 22:39:48 +00003075 // The default case is to treat the operation as if it were closed
3076 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00003077 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3078 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
3079 return IntRange::join(L, R);
3080 }
3081
3082 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
3083 switch (UO->getOpcode()) {
3084 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00003085 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00003086 return IntRange::forBoolType();
3087
3088 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00003089 case UO_Deref:
3090 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00003091 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003092
3093 default:
3094 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
3095 }
3096 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003097
3098 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00003099 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003100 }
John McCallf2370c92010-01-06 05:24:50 +00003101
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003102 if (FieldDecl *BitField = E->getBitField())
3103 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00003104 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00003105
John McCall1844a6e2010-11-10 23:38:19 +00003106 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00003107}
John McCall51313c32010-01-04 23:31:57 +00003108
John McCall323ed742010-05-06 08:58:33 +00003109IntRange GetExprRange(ASTContext &C, Expr *E) {
3110 return GetExprRange(C, E, C.getIntWidth(E->getType()));
3111}
3112
John McCall51313c32010-01-04 23:31:57 +00003113/// Checks whether the given value, which currently has the given
3114/// source semantics, has the same value when coerced through the
3115/// target semantics.
John McCallf2370c92010-01-06 05:24:50 +00003116bool IsSameFloatAfterCast(const llvm::APFloat &value,
3117 const llvm::fltSemantics &Src,
3118 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00003119 llvm::APFloat truncated = value;
3120
3121 bool ignored;
3122 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
3123 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
3124
3125 return truncated.bitwiseIsEqual(value);
3126}
3127
3128/// Checks whether the given value, which currently has the given
3129/// source semantics, has the same value when coerced through the
3130/// target semantics.
3131///
3132/// The value might be a vector of floats (or a complex number).
John McCallf2370c92010-01-06 05:24:50 +00003133bool IsSameFloatAfterCast(const APValue &value,
3134 const llvm::fltSemantics &Src,
3135 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00003136 if (value.isFloat())
3137 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
3138
3139 if (value.isVector()) {
3140 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
3141 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
3142 return false;
3143 return true;
3144 }
3145
3146 assert(value.isComplexFloat());
3147 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
3148 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
3149}
3150
John McCallb4eb64d2010-10-08 02:01:28 +00003151void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00003152
Ted Kremeneke3b159c2010-09-23 21:43:44 +00003153static bool IsZero(Sema &S, Expr *E) {
3154 // Suppress cases where we are comparing against an enum constant.
3155 if (const DeclRefExpr *DR =
3156 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
3157 if (isa<EnumConstantDecl>(DR->getDecl()))
3158 return false;
3159
3160 // Suppress cases where the '0' value is expanded from a macro.
3161 if (E->getLocStart().isMacroID())
3162 return false;
3163
John McCall323ed742010-05-06 08:58:33 +00003164 llvm::APSInt Value;
3165 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
3166}
3167
John McCall372e1032010-10-06 00:25:24 +00003168static bool HasEnumType(Expr *E) {
3169 // Strip off implicit integral promotions.
3170 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00003171 if (ICE->getCastKind() != CK_IntegralCast &&
3172 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00003173 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00003174 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00003175 }
3176
3177 return E->getType()->isEnumeralType();
3178}
3179
John McCall323ed742010-05-06 08:58:33 +00003180void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003181 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00003182 if (E->isValueDependent())
3183 return;
3184
John McCall2de56d12010-08-25 11:45:40 +00003185 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00003186 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003187 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00003188 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003189 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00003190 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003191 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00003192 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003193 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00003194 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003195 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00003196 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00003197 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00003198 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00003199 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00003200 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3201 }
3202}
3203
3204/// Analyze the operands of the given comparison. Implements the
3205/// fallback case from AnalyzeComparison.
3206void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00003207 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3208 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00003209}
John McCall51313c32010-01-04 23:31:57 +00003210
John McCallba26e582010-01-04 23:21:16 +00003211/// \brief Implements -Wsign-compare.
3212///
Richard Trieudd225092011-09-15 21:56:47 +00003213/// \param E the binary operator to check for warnings
John McCall323ed742010-05-06 08:58:33 +00003214void AnalyzeComparison(Sema &S, BinaryOperator *E) {
3215 // The type the comparison is being performed in.
3216 QualType T = E->getLHS()->getType();
3217 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
3218 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00003219
John McCall323ed742010-05-06 08:58:33 +00003220 // We don't do anything special if this isn't an unsigned integral
3221 // comparison: we're only interested in integral comparisons, and
3222 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00003223 //
3224 // We also don't care about value-dependent expressions or expressions
3225 // whose result is a constant.
3226 if (!T->hasUnsignedIntegerRepresentation()
3227 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCall323ed742010-05-06 08:58:33 +00003228 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00003229
Richard Trieudd225092011-09-15 21:56:47 +00003230 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
3231 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00003232
John McCall323ed742010-05-06 08:58:33 +00003233 // Check to see if one of the (unmodified) operands is of different
3234 // signedness.
3235 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00003236 if (LHS->getType()->hasSignedIntegerRepresentation()) {
3237 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00003238 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00003239 signedOperand = LHS;
3240 unsignedOperand = RHS;
3241 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
3242 signedOperand = RHS;
3243 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00003244 } else {
John McCall323ed742010-05-06 08:58:33 +00003245 CheckTrivialUnsignedComparison(S, E);
3246 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00003247 }
3248
John McCall323ed742010-05-06 08:58:33 +00003249 // Otherwise, calculate the effective range of the signed operand.
3250 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00003251
John McCall323ed742010-05-06 08:58:33 +00003252 // Go ahead and analyze implicit conversions in the operands. Note
3253 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00003254 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
3255 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00003256
John McCall323ed742010-05-06 08:58:33 +00003257 // If the signed range is non-negative, -Wsign-compare won't fire,
3258 // but we should still check for comparisons which are always true
3259 // or false.
3260 if (signedRange.NonNegative)
3261 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00003262
3263 // For (in)equality comparisons, if the unsigned operand is a
3264 // constant which cannot collide with a overflowed signed operand,
3265 // then reinterpreting the signed operand as unsigned will not
3266 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00003267 if (E->isEqualityOp()) {
3268 unsigned comparisonWidth = S.Context.getIntWidth(T);
3269 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00003270
John McCall323ed742010-05-06 08:58:33 +00003271 // We should never be unable to prove that the unsigned operand is
3272 // non-negative.
3273 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
3274
3275 if (unsignedRange.Width < comparisonWidth)
3276 return;
3277 }
3278
3279 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
Richard Trieudd225092011-09-15 21:56:47 +00003280 << LHS->getType() << RHS->getType()
3281 << LHS->getSourceRange() << RHS->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00003282}
3283
John McCall15d7d122010-11-11 03:21:53 +00003284/// Analyzes an attempt to assign the given value to a bitfield.
3285///
3286/// Returns true if there was something fishy about the attempt.
3287bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
3288 SourceLocation InitLoc) {
3289 assert(Bitfield->isBitField());
3290 if (Bitfield->isInvalidDecl())
3291 return false;
3292
John McCall91b60142010-11-11 05:33:51 +00003293 // White-list bool bitfields.
3294 if (Bitfield->getType()->isBooleanType())
3295 return false;
3296
Douglas Gregor46ff3032011-02-04 13:09:01 +00003297 // Ignore value- or type-dependent expressions.
3298 if (Bitfield->getBitWidth()->isValueDependent() ||
3299 Bitfield->getBitWidth()->isTypeDependent() ||
3300 Init->isValueDependent() ||
3301 Init->isTypeDependent())
3302 return false;
3303
John McCall15d7d122010-11-11 03:21:53 +00003304 Expr *OriginalInit = Init->IgnoreParenImpCasts();
3305
John McCall15d7d122010-11-11 03:21:53 +00003306 Expr::EvalResult InitValue;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003307 if (!OriginalInit->Evaluate(InitValue, S.Context) ||
John McCall15d7d122010-11-11 03:21:53 +00003308 !InitValue.Val.isInt())
3309 return false;
3310
3311 const llvm::APSInt &Value = InitValue.Val.getInt();
3312 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00003313 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00003314
3315 if (OriginalWidth <= FieldWidth)
3316 return false;
3317
Jay Foad9f71a8f2010-12-07 08:25:34 +00003318 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
John McCall15d7d122010-11-11 03:21:53 +00003319
3320 // It's fairly common to write values into signed bitfields
3321 // that, if sign-extended, would end up becoming a different
3322 // value. We don't want to warn about that.
3323 if (Value.isSigned() && Value.isNegative())
Jay Foad9f71a8f2010-12-07 08:25:34 +00003324 TruncatedValue = TruncatedValue.sext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00003325 else
Jay Foad9f71a8f2010-12-07 08:25:34 +00003326 TruncatedValue = TruncatedValue.zext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00003327
3328 if (Value == TruncatedValue)
3329 return false;
3330
3331 std::string PrettyValue = Value.toString(10);
3332 std::string PrettyTrunc = TruncatedValue.toString(10);
3333
3334 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
3335 << PrettyValue << PrettyTrunc << OriginalInit->getType()
3336 << Init->getSourceRange();
3337
3338 return true;
3339}
3340
John McCallbeb22aa2010-11-09 23:24:47 +00003341/// Analyze the given simple or compound assignment for warning-worthy
3342/// operations.
3343void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
3344 // Just recurse on the LHS.
3345 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3346
3347 // We want to recurse on the RHS as normal unless we're assigning to
3348 // a bitfield.
3349 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00003350 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
3351 E->getOperatorLoc())) {
3352 // Recurse, ignoring any implicit conversions on the RHS.
3353 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
3354 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00003355 }
3356 }
3357
3358 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
3359}
3360
John McCall51313c32010-01-04 23:31:57 +00003361/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003362void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
3363 SourceLocation CContext, unsigned diag) {
3364 S.Diag(E->getExprLoc(), diag)
3365 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
3366}
3367
Chandler Carruthe1b02e02011-04-05 06:47:57 +00003368/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
3369void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
3370 unsigned diag) {
3371 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag);
3372}
3373
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003374/// Diagnose an implicit cast from a literal expression. Does not warn when the
3375/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00003376void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
3377 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003378 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00003379 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003380 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00003381 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
3382 T->hasUnsignedIntegerRepresentation());
3383 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00003384 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003385 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00003386 return;
3387
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00003388 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
3389 << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00003390}
3391
John McCall091f23f2010-11-09 22:22:12 +00003392std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
3393 if (!Range.Width) return "0";
3394
3395 llvm::APSInt ValueInRange = Value;
3396 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00003397 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00003398 return ValueInRange.toString(10);
3399}
3400
Ted Kremenekef9ff882011-03-10 20:03:42 +00003401static bool isFromSystemMacro(Sema &S, SourceLocation loc) {
3402 SourceManager &smgr = S.Context.getSourceManager();
3403 return loc.isMacroID() && smgr.isInSystemHeader(smgr.getSpellingLoc(loc));
3404}
Chandler Carruthf65076e2011-04-10 08:36:24 +00003405
John McCall323ed742010-05-06 08:58:33 +00003406void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00003407 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00003408 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00003409
John McCall323ed742010-05-06 08:58:33 +00003410 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
3411 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
3412 if (Source == Target) return;
3413 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00003414
Chandler Carruth108f7562011-07-26 05:40:03 +00003415 // If the conversion context location is invalid don't complain. We also
3416 // don't want to emit a warning if the issue occurs from the expansion of
3417 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
3418 // delay this check as long as possible. Once we detect we are in that
3419 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00003420 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00003421 return;
3422
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00003423 // Diagnose implicit casts to bool.
3424 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
3425 if (isa<StringLiteral>(E))
3426 // Warn on string literal to bool. Checks for string literals in logical
3427 // expressions, for instances, assert(0 && "error here"), is prevented
3428 // by a check in AnalyzeImplicitConversions().
3429 return DiagnoseImpCast(S, E, T, CC,
3430 diag::warn_impcast_string_literal_to_bool);
David Blaikiee37cdc42011-09-29 04:06:47 +00003431 return; // Other casts to bool are not checked.
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00003432 }
John McCall51313c32010-01-04 23:31:57 +00003433
3434 // Strip vector types.
3435 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003436 if (!isa<VectorType>(Target)) {
3437 if (isFromSystemMacro(S, CC))
3438 return;
John McCallb4eb64d2010-10-08 02:01:28 +00003439 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003440 }
Chris Lattnerb792b302011-06-14 04:51:15 +00003441
3442 // If the vector cast is cast between two vectors of the same size, it is
3443 // a bitcast, not a conversion.
3444 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
3445 return;
John McCall51313c32010-01-04 23:31:57 +00003446
3447 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
3448 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
3449 }
3450
3451 // Strip complex types.
3452 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003453 if (!isa<ComplexType>(Target)) {
3454 if (isFromSystemMacro(S, CC))
3455 return;
3456
John McCallb4eb64d2010-10-08 02:01:28 +00003457 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003458 }
John McCall51313c32010-01-04 23:31:57 +00003459
3460 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
3461 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
3462 }
3463
3464 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
3465 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
3466
3467 // If the source is floating point...
3468 if (SourceBT && SourceBT->isFloatingPoint()) {
3469 // ...and the target is floating point...
3470 if (TargetBT && TargetBT->isFloatingPoint()) {
3471 // ...then warn if we're dropping FP rank.
3472
3473 // Builtin FP kinds are ordered by increasing FP rank.
3474 if (SourceBT->getKind() > TargetBT->getKind()) {
3475 // Don't warn about float constants that are precisely
3476 // representable in the target type.
3477 Expr::EvalResult result;
John McCall323ed742010-05-06 08:58:33 +00003478 if (E->Evaluate(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00003479 // Value might be a float, a float vector, or a float complex.
3480 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00003481 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
3482 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00003483 return;
3484 }
3485
Ted Kremenekef9ff882011-03-10 20:03:42 +00003486 if (isFromSystemMacro(S, CC))
3487 return;
3488
John McCallb4eb64d2010-10-08 02:01:28 +00003489 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00003490 }
3491 return;
3492 }
3493
Ted Kremenekef9ff882011-03-10 20:03:42 +00003494 // If the target is integral, always warn.
Chandler Carrutha5b93322011-02-17 11:05:49 +00003495 if ((TargetBT && TargetBT->isInteger())) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003496 if (isFromSystemMacro(S, CC))
3497 return;
3498
Chandler Carrutha5b93322011-02-17 11:05:49 +00003499 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00003500 // We also want to warn on, e.g., "int i = -1.234"
3501 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
3502 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
3503 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
3504
Chandler Carruthf65076e2011-04-10 08:36:24 +00003505 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
3506 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00003507 } else {
3508 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
3509 }
3510 }
John McCall51313c32010-01-04 23:31:57 +00003511
3512 return;
3513 }
3514
John McCallf2370c92010-01-06 05:24:50 +00003515 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00003516 return;
3517
Richard Trieu1838ca52011-05-29 19:59:02 +00003518 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
3519 == Expr::NPCK_GNUNull) && Target->isIntegerType()) {
3520 S.Diag(E->getExprLoc(), diag::warn_impcast_null_pointer_to_integer)
3521 << E->getSourceRange() << clang::SourceRange(CC);
3522 return;
3523 }
3524
John McCall323ed742010-05-06 08:58:33 +00003525 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00003526 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00003527
3528 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00003529 // If the source is a constant, use a default-on diagnostic.
3530 // TODO: this should happen for bitfield stores, too.
3531 llvm::APSInt Value(32);
3532 if (E->isIntegerConstantExpr(Value, S.Context)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003533 if (isFromSystemMacro(S, CC))
3534 return;
3535
John McCall091f23f2010-11-09 22:22:12 +00003536 std::string PrettySourceValue = Value.toString(10);
3537 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
3538
Ted Kremenek5e745da2011-10-22 02:37:33 +00003539 S.DiagRuntimeBehavior(E->getExprLoc(), E,
3540 S.PDiag(diag::warn_impcast_integer_precision_constant)
3541 << PrettySourceValue << PrettyTargetValue
3542 << E->getType() << T << E->getSourceRange()
3543 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00003544 return;
3545 }
3546
Chris Lattnerb792b302011-06-14 04:51:15 +00003547 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
Ted Kremenekef9ff882011-03-10 20:03:42 +00003548 if (isFromSystemMacro(S, CC))
3549 return;
3550
John McCallf2370c92010-01-06 05:24:50 +00003551 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCallb4eb64d2010-10-08 02:01:28 +00003552 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32);
3553 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00003554 }
3555
3556 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
3557 (!TargetRange.NonNegative && SourceRange.NonNegative &&
3558 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00003559
3560 if (isFromSystemMacro(S, CC))
3561 return;
3562
John McCall323ed742010-05-06 08:58:33 +00003563 unsigned DiagID = diag::warn_impcast_integer_sign;
3564
3565 // Traditionally, gcc has warned about this under -Wsign-compare.
3566 // We also want to warn about it in -Wconversion.
3567 // So if -Wconversion is off, use a completely identical diagnostic
3568 // in the sign-compare group.
3569 // The conditional-checking code will
3570 if (ICContext) {
3571 DiagID = diag::warn_impcast_integer_sign_conditional;
3572 *ICContext = true;
3573 }
3574
John McCallb4eb64d2010-10-08 02:01:28 +00003575 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00003576 }
3577
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003578 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003579 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
3580 // type, to give us better diagnostics.
3581 QualType SourceType = E->getType();
3582 if (!S.getLangOptions().CPlusPlus) {
3583 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3584 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3585 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
3586 SourceType = S.Context.getTypeDeclType(Enum);
3587 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
3588 }
3589 }
3590
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003591 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
3592 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
3593 if ((SourceEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00003594 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003595 (TargetEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00003596 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00003597 SourceEnum != TargetEnum) {
3598 if (isFromSystemMacro(S, CC))
3599 return;
3600
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003601 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003602 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003603 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003604
John McCall51313c32010-01-04 23:31:57 +00003605 return;
3606}
3607
John McCall323ed742010-05-06 08:58:33 +00003608void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
3609
3610void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00003611 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00003612 E = E->IgnoreParenImpCasts();
3613
3614 if (isa<ConditionalOperator>(E))
3615 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
3616
John McCallb4eb64d2010-10-08 02:01:28 +00003617 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003618 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00003619 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00003620 return;
3621}
3622
3623void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00003624 SourceLocation CC = E->getQuestionLoc();
3625
3626 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00003627
3628 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00003629 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
3630 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003631
3632 // If -Wconversion would have warned about either of the candidates
3633 // for a signedness conversion to the context type...
3634 if (!Suspicious) return;
3635
3636 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003637 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
3638 CC))
John McCall323ed742010-05-06 08:58:33 +00003639 return;
3640
John McCall323ed742010-05-06 08:58:33 +00003641 // ...then check whether it would have warned about either of the
3642 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00003643 if (E->getType() == T) return;
3644
3645 Suspicious = false;
3646 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
3647 E->getType(), CC, &Suspicious);
3648 if (!Suspicious)
3649 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00003650 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003651}
3652
3653/// AnalyzeImplicitConversions - Find and report any interesting
3654/// implicit conversions in the given expression. There are a couple
3655/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00003656void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00003657 QualType T = OrigE->getType();
3658 Expr *E = OrigE->IgnoreParenImpCasts();
3659
Douglas Gregorf8b6e152011-10-10 17:38:18 +00003660 if (E->isTypeDependent() || E->isValueDependent())
3661 return;
3662
John McCall323ed742010-05-06 08:58:33 +00003663 // For conditional operators, we analyze the arguments as if they
3664 // were being fed directly into the output.
3665 if (isa<ConditionalOperator>(E)) {
3666 ConditionalOperator *CO = cast<ConditionalOperator>(E);
3667 CheckConditionalOperator(S, CO, T);
3668 return;
3669 }
3670
3671 // Go ahead and check any implicit conversions we might have skipped.
3672 // The non-canonical typecheck is just an optimization;
3673 // CheckImplicitConversion will filter out dead implicit conversions.
3674 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00003675 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00003676
3677 // Now continue drilling into this expression.
3678
3679 // Skip past explicit casts.
3680 if (isa<ExplicitCastExpr>(E)) {
3681 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00003682 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003683 }
3684
John McCallbeb22aa2010-11-09 23:24:47 +00003685 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3686 // Do a somewhat different check with comparison operators.
3687 if (BO->isComparisonOp())
3688 return AnalyzeComparison(S, BO);
3689
3690 // And with assignments and compound assignments.
3691 if (BO->isAssignmentOp())
3692 return AnalyzeAssignment(S, BO);
3693 }
John McCall323ed742010-05-06 08:58:33 +00003694
3695 // These break the otherwise-useful invariant below. Fortunately,
3696 // we don't really need to recurse into them, because any internal
3697 // expressions should have been analyzed already when they were
3698 // built into statements.
3699 if (isa<StmtExpr>(E)) return;
3700
3701 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003702 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00003703
3704 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00003705 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00003706 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
3707 bool IsLogicalOperator = BO && BO->isLogicalOp();
3708 for (Stmt::child_range I = E->children(); I; ++I) {
3709 Expr *ChildExpr = cast<Expr>(*I);
3710 if (IsLogicalOperator &&
3711 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
3712 // Ignore checking string literals that are in logical operators.
3713 continue;
3714 AnalyzeImplicitConversions(S, ChildExpr, CC);
3715 }
John McCall323ed742010-05-06 08:58:33 +00003716}
3717
3718} // end anonymous namespace
3719
3720/// Diagnoses "dangerous" implicit conversions within the given
3721/// expression (which is a full expression). Implements -Wconversion
3722/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00003723///
3724/// \param CC the "context" location of the implicit conversion, i.e.
3725/// the most location of the syntactic entity requiring the implicit
3726/// conversion
3727void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00003728 // Don't diagnose in unevaluated contexts.
3729 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
3730 return;
3731
3732 // Don't diagnose for value- or type-dependent expressions.
3733 if (E->isTypeDependent() || E->isValueDependent())
3734 return;
3735
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003736 // Check for array bounds violations in cases where the check isn't triggered
3737 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
3738 // ArraySubscriptExpr is on the RHS of a variable initialization.
3739 CheckArrayAccess(E);
3740
John McCallb4eb64d2010-10-08 02:01:28 +00003741 // This is not the right CC for (e.g.) a variable initialization.
3742 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003743}
3744
John McCall15d7d122010-11-11 03:21:53 +00003745void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
3746 FieldDecl *BitField,
3747 Expr *Init) {
3748 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
3749}
3750
Mike Stumpf8c49212010-01-21 03:59:47 +00003751/// CheckParmsForFunctionDef - Check that the parameters of the given
3752/// function are appropriate for the definition of a function. This
3753/// takes care of any checks that cannot be performed on the
3754/// declaration itself, e.g., that the types of each of the function
3755/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00003756bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
3757 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00003758 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00003759 for (; P != PEnd; ++P) {
3760 ParmVarDecl *Param = *P;
3761
Mike Stumpf8c49212010-01-21 03:59:47 +00003762 // C99 6.7.5.3p4: the parameters in a parameter type list in a
3763 // function declarator that is part of a function definition of
3764 // that function shall not have incomplete type.
3765 //
3766 // This is also C++ [dcl.fct]p6.
3767 if (!Param->isInvalidDecl() &&
3768 RequireCompleteType(Param->getLocation(), Param->getType(),
3769 diag::err_typecheck_decl_incomplete_type)) {
3770 Param->setInvalidDecl();
3771 HasInvalidParm = true;
3772 }
3773
3774 // C99 6.9.1p5: If the declarator includes a parameter type list, the
3775 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00003776 if (CheckParameterNames &&
3777 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00003778 !Param->isImplicit() &&
3779 !getLangOptions().CPlusPlus)
3780 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00003781
3782 // C99 6.7.5.3p12:
3783 // If the function declarator is not part of a definition of that
3784 // function, parameters may have incomplete type and may use the [*]
3785 // notation in their sequences of declarator specifiers to specify
3786 // variable length array types.
3787 QualType PType = Param->getOriginalType();
3788 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
3789 if (AT->getSizeModifier() == ArrayType::Star) {
3790 // FIXME: This diagnosic should point the the '[*]' if source-location
3791 // information is added for it.
3792 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
3793 }
3794 }
Mike Stumpf8c49212010-01-21 03:59:47 +00003795 }
3796
3797 return HasInvalidParm;
3798}
John McCallb7f4ffe2010-08-12 21:44:57 +00003799
3800/// CheckCastAlign - Implements -Wcast-align, which warns when a
3801/// pointer cast increases the alignment requirements.
3802void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
3803 // This is actually a lot of work to potentially be doing on every
3804 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003805 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
3806 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00003807 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00003808 return;
3809
3810 // Ignore dependent types.
3811 if (T->isDependentType() || Op->getType()->isDependentType())
3812 return;
3813
3814 // Require that the destination be a pointer type.
3815 const PointerType *DestPtr = T->getAs<PointerType>();
3816 if (!DestPtr) return;
3817
3818 // If the destination has alignment 1, we're done.
3819 QualType DestPointee = DestPtr->getPointeeType();
3820 if (DestPointee->isIncompleteType()) return;
3821 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
3822 if (DestAlign.isOne()) return;
3823
3824 // Require that the source be a pointer type.
3825 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
3826 if (!SrcPtr) return;
3827 QualType SrcPointee = SrcPtr->getPointeeType();
3828
3829 // Whitelist casts from cv void*. We already implicitly
3830 // whitelisted casts to cv void*, since they have alignment 1.
3831 // Also whitelist casts involving incomplete types, which implicitly
3832 // includes 'void'.
3833 if (SrcPointee->isIncompleteType()) return;
3834
3835 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
3836 if (SrcAlign >= DestAlign) return;
3837
3838 Diag(TRange.getBegin(), diag::warn_cast_align)
3839 << Op->getType() << T
3840 << static_cast<unsigned>(SrcAlign.getQuantity())
3841 << static_cast<unsigned>(DestAlign.getQuantity())
3842 << TRange << Op->getSourceRange();
3843}
3844
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003845static const Type* getElementType(const Expr *BaseExpr) {
3846 const Type* EltType = BaseExpr->getType().getTypePtr();
3847 if (EltType->isAnyPointerType())
3848 return EltType->getPointeeType().getTypePtr();
3849 else if (EltType->isArrayType())
3850 return EltType->getBaseElementTypeUnsafe();
3851 return EltType;
3852}
3853
Chandler Carruthc2684342011-08-05 09:10:50 +00003854/// \brief Check whether this array fits the idiom of a size-one tail padded
3855/// array member of a struct.
3856///
3857/// We avoid emitting out-of-bounds access warnings for such arrays as they are
3858/// commonly used to emulate flexible arrays in C89 code.
3859static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
3860 const NamedDecl *ND) {
3861 if (Size != 1 || !ND) return false;
3862
3863 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
3864 if (!FD) return false;
3865
3866 // Don't consider sizes resulting from macro expansions or template argument
3867 // substitution to form C89 tail-padded arrays.
3868 ConstantArrayTypeLoc TL =
3869 cast<ConstantArrayTypeLoc>(FD->getTypeSourceInfo()->getTypeLoc());
3870 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(TL.getSizeExpr());
3871 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
3872 return false;
3873
3874 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
3875 if (!RD || !RD->isStruct())
3876 return false;
3877
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00003878 // See if this is the last field decl in the record.
3879 const Decl *D = FD;
3880 while ((D = D->getNextDeclInContext()))
3881 if (isa<FieldDecl>(D))
3882 return false;
3883 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00003884}
3885
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003886void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
3887 bool isSubscript, bool AllowOnePastEnd) {
3888 const Type* EffectiveType = getElementType(BaseExpr);
3889 BaseExpr = BaseExpr->IgnoreParenCasts();
3890 IndexExpr = IndexExpr->IgnoreParenCasts();
3891
Chandler Carruth34064582011-02-17 20:55:08 +00003892 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003893 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00003894 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00003895 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00003896
Chandler Carruth34064582011-02-17 20:55:08 +00003897 if (IndexExpr->isValueDependent())
Ted Kremeneka0125d82011-02-16 01:57:07 +00003898 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003899 llvm::APSInt index;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003900 if (!IndexExpr->isIntegerConstantExpr(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00003901 return;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00003902
Chandler Carruthba447122011-08-05 08:07:29 +00003903 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00003904 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
3905 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00003906 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00003907 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00003908
Ted Kremenek9e060ca2011-02-23 23:06:04 +00003909 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00003910 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00003911 if (!size.isStrictlyPositive())
3912 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003913
3914 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00003915 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003916 // Make sure we're comparing apples to apples when comparing index to size
3917 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
3918 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00003919 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00003920 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003921 if (ptrarith_typesize != array_typesize) {
3922 // There's a cast to a different size type involved
3923 uint64_t ratio = array_typesize / ptrarith_typesize;
3924 // TODO: Be smarter about handling cases where array_typesize is not a
3925 // multiple of ptrarith_typesize
3926 if (ptrarith_typesize * ratio == array_typesize)
3927 size *= llvm::APInt(size.getBitWidth(), ratio);
3928 }
3929 }
3930
Chandler Carruth34064582011-02-17 20:55:08 +00003931 if (size.getBitWidth() > index.getBitWidth())
3932 index = index.sext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00003933 else if (size.getBitWidth() < index.getBitWidth())
3934 size = size.sext(index.getBitWidth());
3935
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003936 // For array subscripting the index must be less than size, but for pointer
3937 // arithmetic also allow the index (offset) to be equal to size since
3938 // computing the next address after the end of the array is legal and
3939 // commonly done e.g. in C++ iterators and range-based for loops.
3940 if (AllowOnePastEnd ? index.sle(size) : index.slt(size))
Chandler Carruthba447122011-08-05 08:07:29 +00003941 return;
3942
3943 // Also don't warn for arrays of size 1 which are members of some
3944 // structure. These are often used to approximate flexible arrays in C89
3945 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003946 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00003947 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003948
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003949 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
3950 if (isSubscript)
3951 DiagID = diag::warn_array_index_exceeds_bounds;
3952
3953 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
3954 PDiag(DiagID) << index.toString(10, true)
3955 << size.toString(10, true)
3956 << (unsigned)size.getLimitedValue(~0U)
3957 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00003958 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003959 unsigned DiagID = diag::warn_array_index_precedes_bounds;
3960 if (!isSubscript) {
3961 DiagID = diag::warn_ptr_arith_precedes_bounds;
3962 if (index.isNegative()) index = -index;
3963 }
3964
3965 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
3966 PDiag(DiagID) << index.toString(10, true)
3967 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00003968 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00003969
Chandler Carruth35001ca2011-02-17 21:10:52 +00003970 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003971 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
3972 PDiag(diag::note_array_index_out_of_bounds)
3973 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00003974}
3975
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003976void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003977 int AllowOnePastEnd = 0;
3978 while (expr) {
3979 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003980 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003981 case Stmt::ArraySubscriptExprClass: {
3982 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
3983 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), true,
3984 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003985 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00003986 }
3987 case Stmt::UnaryOperatorClass: {
3988 // Only unwrap the * and & unary operators
3989 const UnaryOperator *UO = cast<UnaryOperator>(expr);
3990 expr = UO->getSubExpr();
3991 switch (UO->getOpcode()) {
3992 case UO_AddrOf:
3993 AllowOnePastEnd++;
3994 break;
3995 case UO_Deref:
3996 AllowOnePastEnd--;
3997 break;
3998 default:
3999 return;
4000 }
4001 break;
4002 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004003 case Stmt::ConditionalOperatorClass: {
4004 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
4005 if (const Expr *lhs = cond->getLHS())
4006 CheckArrayAccess(lhs);
4007 if (const Expr *rhs = cond->getRHS())
4008 CheckArrayAccess(rhs);
4009 return;
4010 }
4011 default:
4012 return;
4013 }
Peter Collingbournef111d932011-04-15 00:35:48 +00004014 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00004015}
John McCallf85e1932011-06-15 23:02:42 +00004016
4017//===--- CHECK: Objective-C retain cycles ----------------------------------//
4018
4019namespace {
4020 struct RetainCycleOwner {
4021 RetainCycleOwner() : Variable(0), Indirect(false) {}
4022 VarDecl *Variable;
4023 SourceRange Range;
4024 SourceLocation Loc;
4025 bool Indirect;
4026
4027 void setLocsFrom(Expr *e) {
4028 Loc = e->getExprLoc();
4029 Range = e->getSourceRange();
4030 }
4031 };
4032}
4033
4034/// Consider whether capturing the given variable can possibly lead to
4035/// a retain cycle.
4036static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
4037 // In ARC, it's captured strongly iff the variable has __strong
4038 // lifetime. In MRR, it's captured strongly if the variable is
4039 // __block and has an appropriate type.
4040 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4041 return false;
4042
4043 owner.Variable = var;
4044 owner.setLocsFrom(ref);
4045 return true;
4046}
4047
4048static bool findRetainCycleOwner(Expr *e, RetainCycleOwner &owner) {
4049 while (true) {
4050 e = e->IgnoreParens();
4051 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
4052 switch (cast->getCastKind()) {
4053 case CK_BitCast:
4054 case CK_LValueBitCast:
4055 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00004056 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00004057 e = cast->getSubExpr();
4058 continue;
4059
4060 case CK_GetObjCProperty: {
4061 // Bail out if this isn't a strong explicit property.
4062 const ObjCPropertyRefExpr *pre = cast->getSubExpr()->getObjCProperty();
4063 if (pre->isImplicitProperty()) return false;
4064 ObjCPropertyDecl *property = pre->getExplicitProperty();
John McCall265941b2011-09-13 18:31:23 +00004065 if (!property->isRetaining() &&
John McCallf85e1932011-06-15 23:02:42 +00004066 !(property->getPropertyIvarDecl() &&
4067 property->getPropertyIvarDecl()->getType()
4068 .getObjCLifetime() == Qualifiers::OCL_Strong))
4069 return false;
4070
4071 owner.Indirect = true;
4072 e = const_cast<Expr*>(pre->getBase());
4073 continue;
4074 }
4075
4076 default:
4077 return false;
4078 }
4079 }
4080
4081 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
4082 ObjCIvarDecl *ivar = ref->getDecl();
4083 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4084 return false;
4085
4086 // Try to find a retain cycle in the base.
4087 if (!findRetainCycleOwner(ref->getBase(), owner))
4088 return false;
4089
4090 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
4091 owner.Indirect = true;
4092 return true;
4093 }
4094
4095 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
4096 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
4097 if (!var) return false;
4098 return considerVariable(var, ref, owner);
4099 }
4100
4101 if (BlockDeclRefExpr *ref = dyn_cast<BlockDeclRefExpr>(e)) {
4102 owner.Variable = ref->getDecl();
4103 owner.setLocsFrom(ref);
4104 return true;
4105 }
4106
4107 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
4108 if (member->isArrow()) return false;
4109
4110 // Don't count this as an indirect ownership.
4111 e = member->getBase();
4112 continue;
4113 }
4114
4115 // Array ivars?
4116
4117 return false;
4118 }
4119}
4120
4121namespace {
4122 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
4123 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
4124 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
4125 Variable(variable), Capturer(0) {}
4126
4127 VarDecl *Variable;
4128 Expr *Capturer;
4129
4130 void VisitDeclRefExpr(DeclRefExpr *ref) {
4131 if (ref->getDecl() == Variable && !Capturer)
4132 Capturer = ref;
4133 }
4134
4135 void VisitBlockDeclRefExpr(BlockDeclRefExpr *ref) {
4136 if (ref->getDecl() == Variable && !Capturer)
4137 Capturer = ref;
4138 }
4139
4140 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
4141 if (Capturer) return;
4142 Visit(ref->getBase());
4143 if (Capturer && ref->isFreeIvar())
4144 Capturer = ref;
4145 }
4146
4147 void VisitBlockExpr(BlockExpr *block) {
4148 // Look inside nested blocks
4149 if (block->getBlockDecl()->capturesVariable(Variable))
4150 Visit(block->getBlockDecl()->getBody());
4151 }
4152 };
4153}
4154
4155/// Check whether the given argument is a block which captures a
4156/// variable.
4157static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
4158 assert(owner.Variable && owner.Loc.isValid());
4159
4160 e = e->IgnoreParenCasts();
4161 BlockExpr *block = dyn_cast<BlockExpr>(e);
4162 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
4163 return 0;
4164
4165 FindCaptureVisitor visitor(S.Context, owner.Variable);
4166 visitor.Visit(block->getBlockDecl()->getBody());
4167 return visitor.Capturer;
4168}
4169
4170static void diagnoseRetainCycle(Sema &S, Expr *capturer,
4171 RetainCycleOwner &owner) {
4172 assert(capturer);
4173 assert(owner.Variable && owner.Loc.isValid());
4174
4175 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
4176 << owner.Variable << capturer->getSourceRange();
4177 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
4178 << owner.Indirect << owner.Range;
4179}
4180
4181/// Check for a keyword selector that starts with the word 'add' or
4182/// 'set'.
4183static bool isSetterLikeSelector(Selector sel) {
4184 if (sel.isUnarySelector()) return false;
4185
Chris Lattner5f9e2722011-07-23 10:55:15 +00004186 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00004187 while (!str.empty() && str.front() == '_') str = str.substr(1);
4188 if (str.startswith("set") || str.startswith("add"))
4189 str = str.substr(3);
4190 else
4191 return false;
4192
4193 if (str.empty()) return true;
4194 return !islower(str.front());
4195}
4196
4197/// Check a message send to see if it's likely to cause a retain cycle.
4198void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
4199 // Only check instance methods whose selector looks like a setter.
4200 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
4201 return;
4202
4203 // Try to find a variable that the receiver is strongly owned by.
4204 RetainCycleOwner owner;
4205 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
4206 if (!findRetainCycleOwner(msg->getInstanceReceiver(), owner))
4207 return;
4208 } else {
4209 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
4210 owner.Variable = getCurMethodDecl()->getSelfDecl();
4211 owner.Loc = msg->getSuperLoc();
4212 owner.Range = msg->getSuperLoc();
4213 }
4214
4215 // Check whether the receiver is captured by any of the arguments.
4216 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
4217 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
4218 return diagnoseRetainCycle(*this, capturer, owner);
4219}
4220
4221/// Check a property assign to see if it's likely to cause a retain cycle.
4222void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
4223 RetainCycleOwner owner;
4224 if (!findRetainCycleOwner(receiver, owner))
4225 return;
4226
4227 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
4228 diagnoseRetainCycle(*this, capturer, owner);
4229}
4230
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004231bool Sema::checkUnsafeAssigns(SourceLocation Loc,
John McCallf85e1932011-06-15 23:02:42 +00004232 QualType LHS, Expr *RHS) {
4233 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
4234 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004235 return false;
4236 // strip off any implicit cast added to get to the one arc-specific
4237 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00004238 if (cast->getCastKind() == CK_ARCConsumeObject) {
John McCallf85e1932011-06-15 23:02:42 +00004239 Diag(Loc, diag::warn_arc_retained_assign)
4240 << (LT == Qualifiers::OCL_ExplicitNone)
4241 << RHS->getSourceRange();
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004242 return true;
4243 }
4244 RHS = cast->getSubExpr();
4245 }
4246 return false;
John McCallf85e1932011-06-15 23:02:42 +00004247}
4248
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004249void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
4250 Expr *LHS, Expr *RHS) {
4251 QualType LHSType = LHS->getType();
4252 if (checkUnsafeAssigns(Loc, LHSType, RHS))
4253 return;
4254 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
4255 // FIXME. Check for other life times.
4256 if (LT != Qualifiers::OCL_None)
4257 return;
4258
4259 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(LHS)) {
4260 if (PRE->isImplicitProperty())
4261 return;
4262 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
4263 if (!PD)
4264 return;
4265
4266 unsigned Attributes = PD->getPropertyAttributes();
4267 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign)
4268 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00004269 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00004270 Diag(Loc, diag::warn_arc_retained_property_assign)
4271 << RHS->getSourceRange();
4272 return;
4273 }
4274 RHS = cast->getSubExpr();
4275 }
4276 }
4277}