blob: b1da24b1f9bced85910be50f1a93385a7cb13954 [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 McCall2d887082010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Chris Lattner59907c42007-08-10 20:18:51 +000016#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000017#include "clang/AST/CharUnits.h"
John McCall384aff82010-08-25 07:42:41 +000018#include "clang/AST/DeclCXX.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikiebe0ee872012-05-15 16:56:36 +000021#include "clang/AST/Expr.h"
Ted Kremenek23245122007-08-20 16:18:38 +000022#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000023#include "clang/AST/ExprObjC.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000024#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtObjC.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000026#include "clang/Analysis/Analyses/FormatString.h"
Jordan Rose3f6f51e2013-02-08 22:30:41 +000027#include "clang/Basic/CharInfo.h"
Eric Christopher691ebc32010-04-17 02:26:23 +000028#include "clang/Basic/TargetBuiltins.h"
Nate Begeman26a31422010-06-08 02:47:44 +000029#include "clang/Basic/TargetInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000030#include "clang/Lex/Preprocessor.h"
31#include "clang/Sema/Initialization.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000032#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/Sema.h"
Richard Smith0e218972013-08-05 18:49:43 +000035#include "llvm/ADT/SmallBitVector.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000036#include "llvm/ADT/SmallString.h"
Richard Smith0e218972013-08-05 18:49:43 +000037#include "llvm/ADT/STLExtras.h"
Dmitri Gribenkocb5620c2013-01-30 12:06:08 +000038#include "llvm/Support/ConvertUTF.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000039#include "llvm/Support/raw_ostream.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000040#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000041using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000042using namespace sema;
Chris Lattner59907c42007-08-10 20:18:51 +000043
Chris Lattner60800082009-02-18 17:49:48 +000044SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
45 unsigned ByteNo) const {
Chris Lattner08f92e32010-11-17 07:37:15 +000046 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +000047 PP.getLangOpts(), PP.getTargetInfo());
Chris Lattner60800082009-02-18 17:49:48 +000048}
49
John McCall8e10f3b2011-02-26 05:39:39 +000050/// Checks that a call expression's argument count is the desired number.
51/// This is useful when doing custom type-checking. Returns true on error.
52static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
53 unsigned argCount = call->getNumArgs();
54 if (argCount == desiredArgCount) return false;
55
56 if (argCount < desiredArgCount)
57 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
58 << 0 /*function call*/ << desiredArgCount << argCount
59 << call->getSourceRange();
60
61 // Highlight all the excess arguments.
62 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
63 call->getArg(argCount - 1)->getLocEnd());
64
65 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
66 << 0 /*function call*/ << desiredArgCount << argCount
67 << call->getArg(1)->getSourceRange();
68}
69
Julien Lerougee5939212012-04-28 17:39:16 +000070/// Check that the first argument to __builtin_annotation is an integer
71/// and the second argument is a non-wide string literal.
72static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
73 if (checkArgCount(S, TheCall, 2))
74 return true;
75
76 // First argument should be an integer.
77 Expr *ValArg = TheCall->getArg(0);
78 QualType Ty = ValArg->getType();
79 if (!Ty->isIntegerType()) {
80 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
81 << ValArg->getSourceRange();
Julien Lerouge77f68bb2011-09-09 22:41:49 +000082 return true;
83 }
Julien Lerougee5939212012-04-28 17:39:16 +000084
85 // Second argument should be a constant string.
86 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
87 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
88 if (!Literal || !Literal->isAscii()) {
89 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
90 << StrArg->getSourceRange();
91 return true;
92 }
93
94 TheCall->setType(Ty);
Julien Lerouge77f68bb2011-09-09 22:41:49 +000095 return false;
96}
97
Richard Smith5154dce2013-07-11 02:27:57 +000098/// Check that the argument to __builtin_addressof is a glvalue, and set the
99/// result type to the corresponding pointer type.
100static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
101 if (checkArgCount(S, TheCall, 1))
102 return true;
103
104 ExprResult Arg(S.Owned(TheCall->getArg(0)));
105 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
106 if (ResultType.isNull())
107 return true;
108
109 TheCall->setArg(0, Arg.take());
110 TheCall->setType(ResultType);
111 return false;
112}
113
John McCall60d7b3a2010-08-24 06:29:42 +0000114ExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +0000115Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCall60d7b3a2010-08-24 06:29:42 +0000116 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +0000117
Chris Lattner946928f2010-10-01 23:23:24 +0000118 // Find out if any arguments are required to be integer constant expressions.
119 unsigned ICEArguments = 0;
120 ASTContext::GetBuiltinTypeError Error;
121 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
122 if (Error != ASTContext::GE_None)
123 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
124
125 // If any arguments are required to be ICE's, check and diagnose.
126 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
127 // Skip arguments not required to be ICE's.
128 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
129
130 llvm::APSInt Result;
131 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
132 return true;
133 ICEArguments &= ~(1 << ArgNo);
134 }
135
Anders Carlssond406bf02009-08-16 01:56:34 +0000136 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000137 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000138 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000139 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000140 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000141 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000142 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000143 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000144 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000145 if (SemaBuiltinVAStart(TheCall))
146 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000147 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000148 case Builtin::BI__builtin_isgreater:
149 case Builtin::BI__builtin_isgreaterequal:
150 case Builtin::BI__builtin_isless:
151 case Builtin::BI__builtin_islessequal:
152 case Builtin::BI__builtin_islessgreater:
153 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000154 if (SemaBuiltinUnorderedCompare(TheCall))
155 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000156 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000157 case Builtin::BI__builtin_fpclassify:
158 if (SemaBuiltinFPClassification(TheCall, 6))
159 return ExprError();
160 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000161 case Builtin::BI__builtin_isfinite:
162 case Builtin::BI__builtin_isinf:
163 case Builtin::BI__builtin_isinf_sign:
164 case Builtin::BI__builtin_isnan:
165 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000166 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000167 return ExprError();
168 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000169 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000170 return SemaBuiltinShuffleVector(TheCall);
171 // TheCall will be freed by the smart pointer here, but that's fine, since
172 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000173 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000174 if (SemaBuiltinPrefetch(TheCall))
175 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000176 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000177 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000178 if (SemaBuiltinObjectSize(TheCall))
179 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000180 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000181 case Builtin::BI__builtin_longjmp:
182 if (SemaBuiltinLongjmp(TheCall))
183 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000184 break;
John McCall8e10f3b2011-02-26 05:39:39 +0000185
186 case Builtin::BI__builtin_classify_type:
187 if (checkArgCount(*this, TheCall, 1)) return true;
188 TheCall->setType(Context.IntTy);
189 break;
Chris Lattner75c29a02010-10-12 17:47:42 +0000190 case Builtin::BI__builtin_constant_p:
John McCall8e10f3b2011-02-26 05:39:39 +0000191 if (checkArgCount(*this, TheCall, 1)) return true;
192 TheCall->setType(Context.IntTy);
Chris Lattner75c29a02010-10-12 17:47:42 +0000193 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000194 case Builtin::BI__sync_fetch_and_add:
Douglas Gregora9766412011-11-28 16:30:08 +0000195 case Builtin::BI__sync_fetch_and_add_1:
196 case Builtin::BI__sync_fetch_and_add_2:
197 case Builtin::BI__sync_fetch_and_add_4:
198 case Builtin::BI__sync_fetch_and_add_8:
199 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000200 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregora9766412011-11-28 16:30:08 +0000201 case Builtin::BI__sync_fetch_and_sub_1:
202 case Builtin::BI__sync_fetch_and_sub_2:
203 case Builtin::BI__sync_fetch_and_sub_4:
204 case Builtin::BI__sync_fetch_and_sub_8:
205 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000206 case Builtin::BI__sync_fetch_and_or:
Douglas Gregora9766412011-11-28 16:30:08 +0000207 case Builtin::BI__sync_fetch_and_or_1:
208 case Builtin::BI__sync_fetch_and_or_2:
209 case Builtin::BI__sync_fetch_and_or_4:
210 case Builtin::BI__sync_fetch_and_or_8:
211 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000212 case Builtin::BI__sync_fetch_and_and:
Douglas Gregora9766412011-11-28 16:30:08 +0000213 case Builtin::BI__sync_fetch_and_and_1:
214 case Builtin::BI__sync_fetch_and_and_2:
215 case Builtin::BI__sync_fetch_and_and_4:
216 case Builtin::BI__sync_fetch_and_and_8:
217 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000218 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregora9766412011-11-28 16:30:08 +0000219 case Builtin::BI__sync_fetch_and_xor_1:
220 case Builtin::BI__sync_fetch_and_xor_2:
221 case Builtin::BI__sync_fetch_and_xor_4:
222 case Builtin::BI__sync_fetch_and_xor_8:
223 case Builtin::BI__sync_fetch_and_xor_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000224 case Builtin::BI__sync_add_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000225 case Builtin::BI__sync_add_and_fetch_1:
226 case Builtin::BI__sync_add_and_fetch_2:
227 case Builtin::BI__sync_add_and_fetch_4:
228 case Builtin::BI__sync_add_and_fetch_8:
229 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000230 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000231 case Builtin::BI__sync_sub_and_fetch_1:
232 case Builtin::BI__sync_sub_and_fetch_2:
233 case Builtin::BI__sync_sub_and_fetch_4:
234 case Builtin::BI__sync_sub_and_fetch_8:
235 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000236 case Builtin::BI__sync_and_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000237 case Builtin::BI__sync_and_and_fetch_1:
238 case Builtin::BI__sync_and_and_fetch_2:
239 case Builtin::BI__sync_and_and_fetch_4:
240 case Builtin::BI__sync_and_and_fetch_8:
241 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000242 case Builtin::BI__sync_or_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000243 case Builtin::BI__sync_or_and_fetch_1:
244 case Builtin::BI__sync_or_and_fetch_2:
245 case Builtin::BI__sync_or_and_fetch_4:
246 case Builtin::BI__sync_or_and_fetch_8:
247 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000248 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000249 case Builtin::BI__sync_xor_and_fetch_1:
250 case Builtin::BI__sync_xor_and_fetch_2:
251 case Builtin::BI__sync_xor_and_fetch_4:
252 case Builtin::BI__sync_xor_and_fetch_8:
253 case Builtin::BI__sync_xor_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000254 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000255 case Builtin::BI__sync_val_compare_and_swap_1:
256 case Builtin::BI__sync_val_compare_and_swap_2:
257 case Builtin::BI__sync_val_compare_and_swap_4:
258 case Builtin::BI__sync_val_compare_and_swap_8:
259 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000260 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000261 case Builtin::BI__sync_bool_compare_and_swap_1:
262 case Builtin::BI__sync_bool_compare_and_swap_2:
263 case Builtin::BI__sync_bool_compare_and_swap_4:
264 case Builtin::BI__sync_bool_compare_and_swap_8:
265 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000266 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregora9766412011-11-28 16:30:08 +0000267 case Builtin::BI__sync_lock_test_and_set_1:
268 case Builtin::BI__sync_lock_test_and_set_2:
269 case Builtin::BI__sync_lock_test_and_set_4:
270 case Builtin::BI__sync_lock_test_and_set_8:
271 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000272 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +0000273 case Builtin::BI__sync_lock_release_1:
274 case Builtin::BI__sync_lock_release_2:
275 case Builtin::BI__sync_lock_release_4:
276 case Builtin::BI__sync_lock_release_8:
277 case Builtin::BI__sync_lock_release_16:
Chris Lattner23aa9c82011-04-09 03:57:26 +0000278 case Builtin::BI__sync_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000279 case Builtin::BI__sync_swap_1:
280 case Builtin::BI__sync_swap_2:
281 case Builtin::BI__sync_swap_4:
282 case Builtin::BI__sync_swap_8:
283 case Builtin::BI__sync_swap_16:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000284 return SemaBuiltinAtomicOverloaded(TheCallResult);
Richard Smithff34d402012-04-12 05:08:17 +0000285#define BUILTIN(ID, TYPE, ATTRS)
286#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
287 case Builtin::BI##ID: \
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000288 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithff34d402012-04-12 05:08:17 +0000289#include "clang/Basic/Builtins.def"
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000290 case Builtin::BI__builtin_annotation:
Julien Lerougee5939212012-04-28 17:39:16 +0000291 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000292 return ExprError();
293 break;
Richard Smith5154dce2013-07-11 02:27:57 +0000294 case Builtin::BI__builtin_addressof:
295 if (SemaBuiltinAddressof(*this, TheCall))
296 return ExprError();
297 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000298 }
299
300 // Since the target specific builtins for each arch overlap, only check those
301 // of the arch we are compiling for.
302 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000303 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman26a31422010-06-08 02:47:44 +0000304 case llvm::Triple::arm:
305 case llvm::Triple::thumb:
306 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
307 return ExprError();
308 break;
Tim Northoverb793f0d2013-08-01 09:23:19 +0000309 case llvm::Triple::aarch64:
310 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
311 return ExprError();
312 break;
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000313 case llvm::Triple::mips:
314 case llvm::Triple::mipsel:
315 case llvm::Triple::mips64:
316 case llvm::Triple::mips64el:
317 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
318 return ExprError();
319 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000320 default:
321 break;
322 }
323 }
324
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000325 return TheCallResult;
Nate Begeman26a31422010-06-08 02:47:44 +0000326}
327
Nate Begeman61eecf52010-06-14 05:21:25 +0000328// Get the valid immediate range for the specified NEON type code.
329static unsigned RFT(unsigned t, bool shift = false) {
Bob Wilsonda95f732011-11-08 01:16:11 +0000330 NeonTypeFlags Type(t);
331 int IsQuad = Type.isQuad();
332 switch (Type.getEltType()) {
333 case NeonTypeFlags::Int8:
334 case NeonTypeFlags::Poly8:
335 return shift ? 7 : (8 << IsQuad) - 1;
336 case NeonTypeFlags::Int16:
337 case NeonTypeFlags::Poly16:
338 return shift ? 15 : (4 << IsQuad) - 1;
339 case NeonTypeFlags::Int32:
340 return shift ? 31 : (2 << IsQuad) - 1;
341 case NeonTypeFlags::Int64:
342 return shift ? 63 : (1 << IsQuad) - 1;
343 case NeonTypeFlags::Float16:
344 assert(!shift && "cannot shift float types!");
345 return (4 << IsQuad) - 1;
346 case NeonTypeFlags::Float32:
347 assert(!shift && "cannot shift float types!");
348 return (2 << IsQuad) - 1;
Tim Northoverb793f0d2013-08-01 09:23:19 +0000349 case NeonTypeFlags::Float64:
350 assert(!shift && "cannot shift float types!");
351 return (1 << IsQuad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000352 }
David Blaikie7530c032012-01-17 06:56:22 +0000353 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman61eecf52010-06-14 05:21:25 +0000354}
355
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000356/// getNeonEltType - Return the QualType corresponding to the elements of
357/// the vector type specified by the NeonTypeFlags. This is used to check
358/// the pointer arguments for Neon load/store intrinsics.
359static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
360 switch (Flags.getEltType()) {
361 case NeonTypeFlags::Int8:
362 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
363 case NeonTypeFlags::Int16:
364 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
365 case NeonTypeFlags::Int32:
366 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
367 case NeonTypeFlags::Int64:
368 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
369 case NeonTypeFlags::Poly8:
370 return Context.SignedCharTy;
371 case NeonTypeFlags::Poly16:
372 return Context.ShortTy;
373 case NeonTypeFlags::Float16:
374 return Context.UnsignedShortTy;
375 case NeonTypeFlags::Float32:
376 return Context.FloatTy;
Tim Northoverb793f0d2013-08-01 09:23:19 +0000377 case NeonTypeFlags::Float64:
378 return Context.DoubleTy;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000379 }
David Blaikie7530c032012-01-17 06:56:22 +0000380 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000381}
382
Tim Northoverb793f0d2013-08-01 09:23:19 +0000383bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
384 CallExpr *TheCall) {
385
386 llvm::APSInt Result;
387
388 uint64_t mask = 0;
389 unsigned TV = 0;
390 int PtrArgNum = -1;
391 bool HasConstPtr = false;
392 switch (BuiltinID) {
393#define GET_NEON_AARCH64_OVERLOAD_CHECK
394#include "clang/Basic/arm_neon.inc"
395#undef GET_NEON_AARCH64_OVERLOAD_CHECK
396 }
397
398 // For NEON intrinsics which are overloaded on vector element type, validate
399 // the immediate which specifies which variant to emit.
400 unsigned ImmArg = TheCall->getNumArgs() - 1;
401 if (mask) {
402 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
403 return true;
404
405 TV = Result.getLimitedValue(64);
406 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
407 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
408 << TheCall->getArg(ImmArg)->getSourceRange();
409 }
410
411 if (PtrArgNum >= 0) {
412 // Check that pointer arguments have the specified type.
413 Expr *Arg = TheCall->getArg(PtrArgNum);
414 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
415 Arg = ICE->getSubExpr();
416 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
417 QualType RHSTy = RHS.get()->getType();
418 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
419 if (HasConstPtr)
420 EltTy = EltTy.withConst();
421 QualType LHSTy = Context.getPointerType(EltTy);
422 AssignConvertType ConvTy;
423 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
424 if (RHS.isInvalid())
425 return true;
426 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
427 RHS.get(), AA_Assigning))
428 return true;
429 }
430
431 // For NEON intrinsics which take an immediate value as part of the
432 // instruction, range check them here.
433 unsigned i = 0, l = 0, u = 0;
434 switch (BuiltinID) {
435 default:
436 return false;
437#define GET_NEON_AARCH64_IMMEDIATE_CHECK
438#include "clang/Basic/arm_neon.inc"
439#undef GET_NEON_AARCH64_IMMEDIATE_CHECK
440 }
441 ;
442
443 // We can't check the value of a dependent argument.
444 if (TheCall->getArg(i)->isTypeDependent() ||
445 TheCall->getArg(i)->isValueDependent())
446 return false;
447
448 // Check that the immediate argument is actually a constant.
449 if (SemaBuiltinConstantArg(TheCall, i, Result))
450 return true;
451
452 // Range check against the upper/lower values for this isntruction.
453 unsigned Val = Result.getZExtValue();
454 if (Val < l || Val > (u + l))
455 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
456 << l << u + l << TheCall->getArg(i)->getSourceRange();
457
458 return false;
459}
460
Tim Northover09df2b02013-07-16 09:47:53 +0000461bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall) {
462 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
463 BuiltinID == ARM::BI__builtin_arm_strex) &&
464 "unexpected ARM builtin");
465 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex;
466
467 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
468
469 // Ensure that we have the proper number of arguments.
470 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
471 return true;
472
473 // Inspect the pointer argument of the atomic builtin. This should always be
474 // a pointer type, whose element is an integral scalar or pointer type.
475 // Because it is a pointer type, we don't have to worry about any implicit
476 // casts here.
477 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
478 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
479 if (PointerArgRes.isInvalid())
480 return true;
481 PointerArg = PointerArgRes.take();
482
483 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
484 if (!pointerType) {
485 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
486 << PointerArg->getType() << PointerArg->getSourceRange();
487 return true;
488 }
489
490 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
491 // task is to insert the appropriate casts into the AST. First work out just
492 // what the appropriate type is.
493 QualType ValType = pointerType->getPointeeType();
494 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
495 if (IsLdrex)
496 AddrType.addConst();
497
498 // Issue a warning if the cast is dodgy.
499 CastKind CastNeeded = CK_NoOp;
500 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
501 CastNeeded = CK_BitCast;
502 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
503 << PointerArg->getType()
504 << Context.getPointerType(AddrType)
505 << AA_Passing << PointerArg->getSourceRange();
506 }
507
508 // Finally, do the cast and replace the argument with the corrected version.
509 AddrType = Context.getPointerType(AddrType);
510 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
511 if (PointerArgRes.isInvalid())
512 return true;
513 PointerArg = PointerArgRes.take();
514
515 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
516
517 // In general, we allow ints, floats and pointers to be loaded and stored.
518 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
519 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
520 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
521 << PointerArg->getType() << PointerArg->getSourceRange();
522 return true;
523 }
524
525 // But ARM doesn't have instructions to deal with 128-bit versions.
526 if (Context.getTypeSize(ValType) > 64) {
527 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
528 << PointerArg->getType() << PointerArg->getSourceRange();
529 return true;
530 }
531
532 switch (ValType.getObjCLifetime()) {
533 case Qualifiers::OCL_None:
534 case Qualifiers::OCL_ExplicitNone:
535 // okay
536 break;
537
538 case Qualifiers::OCL_Weak:
539 case Qualifiers::OCL_Strong:
540 case Qualifiers::OCL_Autoreleasing:
541 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
542 << ValType << PointerArg->getSourceRange();
543 return true;
544 }
545
546
547 if (IsLdrex) {
548 TheCall->setType(ValType);
549 return false;
550 }
551
552 // Initialize the argument to be stored.
553 ExprResult ValArg = TheCall->getArg(0);
554 InitializedEntity Entity = InitializedEntity::InitializeParameter(
555 Context, ValType, /*consume*/ false);
556 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
557 if (ValArg.isInvalid())
558 return true;
Tim Northover09df2b02013-07-16 09:47:53 +0000559 TheCall->setArg(0, ValArg.get());
Tim Northovera6306fc2013-10-29 12:32:58 +0000560
561 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
562 // but the custom checker bypasses all default analysis.
563 TheCall->setType(Context.IntTy);
Tim Northover09df2b02013-07-16 09:47:53 +0000564 return false;
565}
566
Nate Begeman26a31422010-06-08 02:47:44 +0000567bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000568 llvm::APSInt Result;
569
Tim Northover09df2b02013-07-16 09:47:53 +0000570 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
571 BuiltinID == ARM::BI__builtin_arm_strex) {
572 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall);
573 }
574
Richard Smithf8ee6bc2012-08-14 01:28:02 +0000575 uint64_t mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000576 unsigned TV = 0;
Bob Wilson46482552011-11-16 21:32:23 +0000577 int PtrArgNum = -1;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000578 bool HasConstPtr = false;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000579 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000580#define GET_NEON_OVERLOAD_CHECK
581#include "clang/Basic/arm_neon.inc"
582#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000583 }
584
Nate Begeman0d15c532010-06-13 04:47:52 +0000585 // For NEON intrinsics which are overloaded on vector element type, validate
586 // the immediate which specifies which variant to emit.
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000587 unsigned ImmArg = TheCall->getNumArgs()-1;
Nate Begeman0d15c532010-06-13 04:47:52 +0000588 if (mask) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000589 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
Nate Begeman0d15c532010-06-13 04:47:52 +0000590 return true;
591
Bob Wilsonda95f732011-11-08 01:16:11 +0000592 TV = Result.getLimitedValue(64);
Richard Smithf8ee6bc2012-08-14 01:28:02 +0000593 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000594 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000595 << TheCall->getArg(ImmArg)->getSourceRange();
596 }
597
Bob Wilson46482552011-11-16 21:32:23 +0000598 if (PtrArgNum >= 0) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000599 // Check that pointer arguments have the specified type.
Bob Wilson46482552011-11-16 21:32:23 +0000600 Expr *Arg = TheCall->getArg(PtrArgNum);
601 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
602 Arg = ICE->getSubExpr();
603 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
604 QualType RHSTy = RHS.get()->getType();
605 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
606 if (HasConstPtr)
607 EltTy = EltTy.withConst();
608 QualType LHSTy = Context.getPointerType(EltTy);
609 AssignConvertType ConvTy;
610 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
611 if (RHS.isInvalid())
612 return true;
613 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
614 RHS.get(), AA_Assigning))
615 return true;
Nate Begeman0d15c532010-06-13 04:47:52 +0000616 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000617
Nate Begeman0d15c532010-06-13 04:47:52 +0000618 // For NEON intrinsics which take an immediate value as part of the
619 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000620 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000621 switch (BuiltinID) {
622 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000623 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
624 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000625 case ARM::BI__builtin_arm_vcvtr_f:
626 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000627#define GET_NEON_IMMEDIATE_CHECK
628#include "clang/Basic/arm_neon.inc"
629#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000630 };
631
Douglas Gregor592a4232012-06-29 01:05:22 +0000632 // We can't check the value of a dependent argument.
633 if (TheCall->getArg(i)->isTypeDependent() ||
634 TheCall->getArg(i)->isValueDependent())
635 return false;
636
Nate Begeman61eecf52010-06-14 05:21:25 +0000637 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000638 if (SemaBuiltinConstantArg(TheCall, i, Result))
639 return true;
640
Nate Begeman61eecf52010-06-14 05:21:25 +0000641 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000642 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000643 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000644 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000645 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000646
Nate Begeman99c40bb2010-08-03 21:32:34 +0000647 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000648 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000649}
Daniel Dunbarde454282008-10-02 18:44:07 +0000650
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000651bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
652 unsigned i = 0, l = 0, u = 0;
653 switch (BuiltinID) {
654 default: return false;
655 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
656 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyanbe22cb82012-08-27 12:29:20 +0000657 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
658 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
659 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
660 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
661 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000662 };
663
664 // We can't check the value of a dependent argument.
665 if (TheCall->getArg(i)->isTypeDependent() ||
666 TheCall->getArg(i)->isValueDependent())
667 return false;
668
669 // Check that the immediate argument is actually a constant.
670 llvm::APSInt Result;
671 if (SemaBuiltinConstantArg(TheCall, i, Result))
672 return true;
673
674 // Range check against the upper/lower values for this instruction.
675 unsigned Val = Result.getZExtValue();
676 if (Val < l || Val > u)
677 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
678 << l << u << TheCall->getArg(i)->getSourceRange();
679
680 return false;
681}
682
Richard Smith831421f2012-06-25 20:30:08 +0000683/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
684/// parameter with the FormatAttr's correct format_idx and firstDataArg.
685/// Returns true when the format fits the function and the FormatStringInfo has
686/// been populated.
687bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
688 FormatStringInfo *FSI) {
689 FSI->HasVAListArg = Format->getFirstArg() == 0;
690 FSI->FormatIdx = Format->getFormatIdx() - 1;
691 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssond406bf02009-08-16 01:56:34 +0000692
Richard Smith831421f2012-06-25 20:30:08 +0000693 // The way the format attribute works in GCC, the implicit this argument
694 // of member functions is counted. However, it doesn't appear in our own
695 // lists, so decrement format_idx in that case.
696 if (IsCXXMember) {
697 if(FSI->FormatIdx == 0)
698 return false;
699 --FSI->FormatIdx;
700 if (FSI->FirstDataArg != 0)
701 --FSI->FirstDataArg;
702 }
703 return true;
704}
Mike Stump1eb44332009-09-09 15:08:12 +0000705
Richard Smith831421f2012-06-25 20:30:08 +0000706/// Handles the checks for format strings, non-POD arguments to vararg
707/// functions, and NULL arguments passed to non-NULL parameters.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000708void Sema::checkCall(NamedDecl *FDecl,
709 ArrayRef<const Expr *> Args,
Richard Smith831421f2012-06-25 20:30:08 +0000710 unsigned NumProtoArgs,
711 bool IsMemberFunction,
712 SourceLocation Loc,
713 SourceRange Range,
714 VariadicCallType CallType) {
Richard Smith0e218972013-08-05 18:49:43 +0000715 // FIXME: We should check as much as we can in the template definition.
Jordan Rose66360e22012-10-02 01:49:54 +0000716 if (CurContext->isDependentContext())
717 return;
Daniel Dunbarde454282008-10-02 18:44:07 +0000718
Ted Kremenekc82faca2010-09-09 04:33:05 +0000719 // Printf and scanf checking.
Richard Smith0e218972013-08-05 18:49:43 +0000720 llvm::SmallBitVector CheckedVarArgs;
721 if (FDecl) {
Richard Trieu0538f0e2013-06-22 00:20:41 +0000722 for (specific_attr_iterator<FormatAttr>
Benjamin Kramer47abb252013-08-08 11:08:26 +0000723 I = FDecl->specific_attr_begin<FormatAttr>(),
724 E = FDecl->specific_attr_end<FormatAttr>();
Benjamin Kramer541a28f2013-08-09 09:39:17 +0000725 I != E; ++I) {
726 // Only create vector if there are format attributes.
727 CheckedVarArgs.resize(Args.size());
728
Benjamin Kramer47abb252013-08-08 11:08:26 +0000729 CheckFormatArguments(*I, Args, IsMemberFunction, CallType, Loc, Range,
730 CheckedVarArgs);
Benjamin Kramer541a28f2013-08-09 09:39:17 +0000731 }
Richard Smith0e218972013-08-05 18:49:43 +0000732 }
Richard Smith831421f2012-06-25 20:30:08 +0000733
734 // Refuse POD arguments that weren't caught by the format string
735 // checks above.
Richard Smith0e218972013-08-05 18:49:43 +0000736 if (CallType != VariadicDoesNotApply) {
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000737 for (unsigned ArgIdx = NumProtoArgs; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek0234bfa2012-10-11 19:06:43 +0000738 // Args[ArgIdx] can be null in malformed code.
Richard Smith0e218972013-08-05 18:49:43 +0000739 if (const Expr *Arg = Args[ArgIdx]) {
740 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
741 checkVariadicArgument(Arg, CallType);
742 }
Ted Kremenek0234bfa2012-10-11 19:06:43 +0000743 }
Richard Smith0e218972013-08-05 18:49:43 +0000744 }
Mike Stump1eb44332009-09-09 15:08:12 +0000745
Richard Trieu0538f0e2013-06-22 00:20:41 +0000746 if (FDecl) {
747 for (specific_attr_iterator<NonNullAttr>
748 I = FDecl->specific_attr_begin<NonNullAttr>(),
749 E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I)
750 CheckNonNullArguments(*I, Args.data(), Loc);
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +0000751
Richard Trieu0538f0e2013-06-22 00:20:41 +0000752 // Type safety checking.
753 for (specific_attr_iterator<ArgumentWithTypeTagAttr>
754 i = FDecl->specific_attr_begin<ArgumentWithTypeTagAttr>(),
755 e = FDecl->specific_attr_end<ArgumentWithTypeTagAttr>();
756 i != e; ++i) {
757 CheckArgumentWithTypeTag(*i, Args.data());
758 }
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +0000759 }
Richard Smith831421f2012-06-25 20:30:08 +0000760}
761
762/// CheckConstructorCall - Check a constructor call for correctness and safety
763/// properties not enforced by the C type system.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000764void Sema::CheckConstructorCall(FunctionDecl *FDecl,
765 ArrayRef<const Expr *> Args,
Richard Smith831421f2012-06-25 20:30:08 +0000766 const FunctionProtoType *Proto,
767 SourceLocation Loc) {
768 VariadicCallType CallType =
769 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000770 checkCall(FDecl, Args, Proto->getNumArgs(),
Richard Smith831421f2012-06-25 20:30:08 +0000771 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
772}
773
774/// CheckFunctionCall - Check a direct function call for various correctness
775/// and safety properties not strictly enforced by the C type system.
776bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
777 const FunctionProtoType *Proto) {
Eli Friedman2edcde82012-10-11 00:30:58 +0000778 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
779 isa<CXXMethodDecl>(FDecl);
780 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
781 IsMemberOperatorCall;
Richard Smith831421f2012-06-25 20:30:08 +0000782 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
783 TheCall->getCallee());
784 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
Eli Friedman2edcde82012-10-11 00:30:58 +0000785 Expr** Args = TheCall->getArgs();
786 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmandf75b0c2012-10-11 00:34:15 +0000787 if (IsMemberOperatorCall) {
Eli Friedman2edcde82012-10-11 00:30:58 +0000788 // If this is a call to a member operator, hide the first argument
789 // from checkCall.
790 // FIXME: Our choice of AST representation here is less than ideal.
791 ++Args;
792 --NumArgs;
793 }
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000794 checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs),
795 NumProtoArgs,
Richard Smith831421f2012-06-25 20:30:08 +0000796 IsMemberFunction, TheCall->getRParenLoc(),
797 TheCall->getCallee()->getSourceRange(), CallType);
798
799 IdentifierInfo *FnInfo = FDecl->getIdentifier();
800 // None of the checks below are needed for functions that don't have
801 // simple names (e.g., C++ conversion functions).
802 if (!FnInfo)
803 return false;
Sebastian Redl0eb23302009-01-19 00:08:26 +0000804
Anna Zaks0a151a12012-01-17 00:37:07 +0000805 unsigned CMId = FDecl->getMemoryFunctionKind();
806 if (CMId == 0)
Anna Zaksd9b859a2012-01-13 21:52:01 +0000807 return false;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000808
Anna Zaksd9b859a2012-01-13 21:52:01 +0000809 // Handle memory setting and copying functions.
Anna Zaks0a151a12012-01-17 00:37:07 +0000810 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000811 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaksc36bedc2012-02-01 19:08:57 +0000812 else if (CMId == Builtin::BIstrncat)
813 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaksd9b859a2012-01-13 21:52:01 +0000814 else
Anna Zaks0a151a12012-01-17 00:37:07 +0000815 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000816
Anders Carlssond406bf02009-08-16 01:56:34 +0000817 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000818}
819
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000820bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko287f24d2013-05-05 19:42:09 +0000821 ArrayRef<const Expr *> Args) {
Richard Smith831421f2012-06-25 20:30:08 +0000822 VariadicCallType CallType =
823 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000824
Dmitri Gribenko287f24d2013-05-05 19:42:09 +0000825 checkCall(Method, Args, Method->param_size(),
Richard Smith831421f2012-06-25 20:30:08 +0000826 /*IsMemberFunction=*/false,
827 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000828
829 return false;
830}
831
Richard Trieuf462b012013-06-20 21:03:13 +0000832bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
833 const FunctionProtoType *Proto) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000834 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
835 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000836 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000837
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000838 QualType Ty = V->getType();
Richard Trieuf462b012013-06-20 21:03:13 +0000839 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000840 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000841
Richard Trieuf462b012013-06-20 21:03:13 +0000842 VariadicCallType CallType;
Richard Trieua4993772013-06-20 23:21:54 +0000843 if (!Proto || !Proto->isVariadic()) {
Richard Trieuf462b012013-06-20 21:03:13 +0000844 CallType = VariadicDoesNotApply;
845 } else if (Ty->isBlockPointerType()) {
846 CallType = VariadicBlock;
847 } else { // Ty->isFunctionPointerType()
848 CallType = VariadicFunction;
849 }
Richard Smith831421f2012-06-25 20:30:08 +0000850 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
Anders Carlssond406bf02009-08-16 01:56:34 +0000851
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000852 checkCall(NDecl,
853 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
854 TheCall->getNumArgs()),
Richard Smith831421f2012-06-25 20:30:08 +0000855 NumProtoArgs, /*IsMemberFunction=*/false,
856 TheCall->getRParenLoc(),
857 TheCall->getCallee()->getSourceRange(), CallType);
858
Anders Carlssond406bf02009-08-16 01:56:34 +0000859 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000860}
861
Richard Trieu0538f0e2013-06-22 00:20:41 +0000862/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
863/// such as function pointers returned from functions.
864bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
865 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/0, Proto,
866 TheCall->getCallee());
867 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
868
869 checkCall(/*FDecl=*/0,
870 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
871 TheCall->getNumArgs()),
872 NumProtoArgs, /*IsMemberFunction=*/false,
873 TheCall->getRParenLoc(),
874 TheCall->getCallee()->getSourceRange(), CallType);
875
876 return false;
877}
878
Richard Smithff34d402012-04-12 05:08:17 +0000879ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
880 AtomicExpr::AtomicOp Op) {
Eli Friedman276b0612011-10-11 02:20:01 +0000881 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
882 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000883
Richard Smithff34d402012-04-12 05:08:17 +0000884 // All these operations take one of the following forms:
885 enum {
886 // C __c11_atomic_init(A *, C)
887 Init,
888 // C __c11_atomic_load(A *, int)
889 Load,
890 // void __atomic_load(A *, CP, int)
891 Copy,
892 // C __c11_atomic_add(A *, M, int)
893 Arithmetic,
894 // C __atomic_exchange_n(A *, CP, int)
895 Xchg,
896 // void __atomic_exchange(A *, C *, CP, int)
897 GNUXchg,
898 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
899 C11CmpXchg,
900 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
901 GNUCmpXchg
902 } Form = Init;
903 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
904 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
905 // where:
906 // C is an appropriate type,
907 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
908 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
909 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
910 // the int parameters are for orderings.
Eli Friedman276b0612011-10-11 02:20:01 +0000911
Richard Smithff34d402012-04-12 05:08:17 +0000912 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
913 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
914 && "need to update code for modified C11 atomics");
915 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
916 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
917 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
918 Op == AtomicExpr::AO__atomic_store_n ||
919 Op == AtomicExpr::AO__atomic_exchange_n ||
920 Op == AtomicExpr::AO__atomic_compare_exchange_n;
921 bool IsAddSub = false;
922
923 switch (Op) {
924 case AtomicExpr::AO__c11_atomic_init:
925 Form = Init;
926 break;
927
928 case AtomicExpr::AO__c11_atomic_load:
929 case AtomicExpr::AO__atomic_load_n:
930 Form = Load;
931 break;
932
933 case AtomicExpr::AO__c11_atomic_store:
934 case AtomicExpr::AO__atomic_load:
935 case AtomicExpr::AO__atomic_store:
936 case AtomicExpr::AO__atomic_store_n:
937 Form = Copy;
938 break;
939
940 case AtomicExpr::AO__c11_atomic_fetch_add:
941 case AtomicExpr::AO__c11_atomic_fetch_sub:
942 case AtomicExpr::AO__atomic_fetch_add:
943 case AtomicExpr::AO__atomic_fetch_sub:
944 case AtomicExpr::AO__atomic_add_fetch:
945 case AtomicExpr::AO__atomic_sub_fetch:
946 IsAddSub = true;
947 // Fall through.
948 case AtomicExpr::AO__c11_atomic_fetch_and:
949 case AtomicExpr::AO__c11_atomic_fetch_or:
950 case AtomicExpr::AO__c11_atomic_fetch_xor:
951 case AtomicExpr::AO__atomic_fetch_and:
952 case AtomicExpr::AO__atomic_fetch_or:
953 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smith51b92402012-04-13 06:31:38 +0000954 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithff34d402012-04-12 05:08:17 +0000955 case AtomicExpr::AO__atomic_and_fetch:
956 case AtomicExpr::AO__atomic_or_fetch:
957 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smith51b92402012-04-13 06:31:38 +0000958 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithff34d402012-04-12 05:08:17 +0000959 Form = Arithmetic;
960 break;
961
962 case AtomicExpr::AO__c11_atomic_exchange:
963 case AtomicExpr::AO__atomic_exchange_n:
964 Form = Xchg;
965 break;
966
967 case AtomicExpr::AO__atomic_exchange:
968 Form = GNUXchg;
969 break;
970
971 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
972 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
973 Form = C11CmpXchg;
974 break;
975
976 case AtomicExpr::AO__atomic_compare_exchange:
977 case AtomicExpr::AO__atomic_compare_exchange_n:
978 Form = GNUCmpXchg;
979 break;
980 }
981
982 // Check we have the right number of arguments.
983 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedman276b0612011-10-11 02:20:01 +0000984 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithff34d402012-04-12 05:08:17 +0000985 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000986 << TheCall->getCallee()->getSourceRange();
987 return ExprError();
Richard Smithff34d402012-04-12 05:08:17 +0000988 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
989 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedman276b0612011-10-11 02:20:01 +0000990 diag::err_typecheck_call_too_many_args)
Richard Smithff34d402012-04-12 05:08:17 +0000991 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000992 << TheCall->getCallee()->getSourceRange();
993 return ExprError();
994 }
995
Richard Smithff34d402012-04-12 05:08:17 +0000996 // Inspect the first argument of the atomic operation.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000997 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +0000998 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
999 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1000 if (!pointerType) {
Richard Smithff34d402012-04-12 05:08:17 +00001001 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedman276b0612011-10-11 02:20:01 +00001002 << Ptr->getType() << Ptr->getSourceRange();
1003 return ExprError();
1004 }
1005
Richard Smithff34d402012-04-12 05:08:17 +00001006 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1007 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1008 QualType ValType = AtomTy; // 'C'
1009 if (IsC11) {
1010 if (!AtomTy->isAtomicType()) {
1011 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1012 << Ptr->getType() << Ptr->getSourceRange();
1013 return ExprError();
1014 }
Richard Smithbc57b102012-09-15 06:09:58 +00001015 if (AtomTy.isConstQualified()) {
1016 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1017 << Ptr->getType() << Ptr->getSourceRange();
1018 return ExprError();
1019 }
Richard Smithff34d402012-04-12 05:08:17 +00001020 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedman276b0612011-10-11 02:20:01 +00001021 }
Eli Friedman276b0612011-10-11 02:20:01 +00001022
Richard Smithff34d402012-04-12 05:08:17 +00001023 // For an arithmetic operation, the implied arithmetic must be well-formed.
1024 if (Form == Arithmetic) {
1025 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1026 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1027 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1028 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1029 return ExprError();
1030 }
1031 if (!IsAddSub && !ValType->isIntegerType()) {
1032 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1033 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1034 return ExprError();
1035 }
1036 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1037 // For __atomic_*_n operations, the value type must be a scalar integral or
1038 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedman276b0612011-10-11 02:20:01 +00001039 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithff34d402012-04-12 05:08:17 +00001040 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1041 return ExprError();
1042 }
1043
Eli Friedmana3d727b2013-09-11 03:49:34 +00001044 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1045 !AtomTy->isScalarType()) {
Richard Smithff34d402012-04-12 05:08:17 +00001046 // For GNU atomics, require a trivially-copyable type. This is not part of
1047 // the GNU atomics specification, but we enforce it for sanity.
1048 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedman276b0612011-10-11 02:20:01 +00001049 << Ptr->getType() << Ptr->getSourceRange();
1050 return ExprError();
1051 }
1052
Richard Smithff34d402012-04-12 05:08:17 +00001053 // FIXME: For any builtin other than a load, the ValType must not be
1054 // const-qualified.
Eli Friedman276b0612011-10-11 02:20:01 +00001055
1056 switch (ValType.getObjCLifetime()) {
1057 case Qualifiers::OCL_None:
1058 case Qualifiers::OCL_ExplicitNone:
1059 // okay
1060 break;
1061
1062 case Qualifiers::OCL_Weak:
1063 case Qualifiers::OCL_Strong:
1064 case Qualifiers::OCL_Autoreleasing:
Richard Smithff34d402012-04-12 05:08:17 +00001065 // FIXME: Can this happen? By this point, ValType should be known
1066 // to be trivially copyable.
Eli Friedman276b0612011-10-11 02:20:01 +00001067 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1068 << ValType << Ptr->getSourceRange();
1069 return ExprError();
1070 }
1071
1072 QualType ResultType = ValType;
Richard Smithff34d402012-04-12 05:08:17 +00001073 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedman276b0612011-10-11 02:20:01 +00001074 ResultType = Context.VoidTy;
Richard Smithff34d402012-04-12 05:08:17 +00001075 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedman276b0612011-10-11 02:20:01 +00001076 ResultType = Context.BoolTy;
1077
Richard Smithff34d402012-04-12 05:08:17 +00001078 // The type of a parameter passed 'by value'. In the GNU atomics, such
1079 // arguments are actually passed as pointers.
1080 QualType ByValType = ValType; // 'CP'
1081 if (!IsC11 && !IsN)
1082 ByValType = Ptr->getType();
1083
Eli Friedman276b0612011-10-11 02:20:01 +00001084 // The first argument --- the pointer --- has a fixed type; we
1085 // deduce the types of the rest of the arguments accordingly. Walk
1086 // the remaining arguments, converting them to the deduced value type.
Richard Smithff34d402012-04-12 05:08:17 +00001087 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedman276b0612011-10-11 02:20:01 +00001088 QualType Ty;
Richard Smithff34d402012-04-12 05:08:17 +00001089 if (i < NumVals[Form] + 1) {
1090 switch (i) {
1091 case 1:
1092 // The second argument is the non-atomic operand. For arithmetic, this
1093 // is always passed by value, and for a compare_exchange it is always
1094 // passed by address. For the rest, GNU uses by-address and C11 uses
1095 // by-value.
1096 assert(Form != Load);
1097 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1098 Ty = ValType;
1099 else if (Form == Copy || Form == Xchg)
1100 Ty = ByValType;
1101 else if (Form == Arithmetic)
1102 Ty = Context.getPointerDiffType();
1103 else
1104 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1105 break;
1106 case 2:
1107 // The third argument to compare_exchange / GNU exchange is a
1108 // (pointer to a) desired value.
1109 Ty = ByValType;
1110 break;
1111 case 3:
1112 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1113 Ty = Context.BoolTy;
1114 break;
1115 }
Eli Friedman276b0612011-10-11 02:20:01 +00001116 } else {
1117 // The order(s) are always converted to int.
1118 Ty = Context.IntTy;
1119 }
Richard Smithff34d402012-04-12 05:08:17 +00001120
Eli Friedman276b0612011-10-11 02:20:01 +00001121 InitializedEntity Entity =
1122 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithff34d402012-04-12 05:08:17 +00001123 ExprResult Arg = TheCall->getArg(i);
Eli Friedman276b0612011-10-11 02:20:01 +00001124 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1125 if (Arg.isInvalid())
1126 return true;
1127 TheCall->setArg(i, Arg.get());
1128 }
1129
Richard Smithff34d402012-04-12 05:08:17 +00001130 // Permute the arguments into a 'consistent' order.
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001131 SmallVector<Expr*, 5> SubExprs;
1132 SubExprs.push_back(Ptr);
Richard Smithff34d402012-04-12 05:08:17 +00001133 switch (Form) {
1134 case Init:
1135 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnall7a7ee302012-01-16 17:27:18 +00001136 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +00001137 break;
1138 case Load:
1139 SubExprs.push_back(TheCall->getArg(1)); // Order
1140 break;
1141 case Copy:
1142 case Arithmetic:
1143 case Xchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001144 SubExprs.push_back(TheCall->getArg(2)); // Order
1145 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +00001146 break;
1147 case GNUXchg:
1148 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1149 SubExprs.push_back(TheCall->getArg(3)); // Order
1150 SubExprs.push_back(TheCall->getArg(1)); // Val1
1151 SubExprs.push_back(TheCall->getArg(2)); // Val2
1152 break;
1153 case C11CmpXchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001154 SubExprs.push_back(TheCall->getArg(3)); // Order
1155 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001156 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall2ebb98a2012-03-29 17:58:59 +00001157 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithff34d402012-04-12 05:08:17 +00001158 break;
1159 case GNUCmpXchg:
1160 SubExprs.push_back(TheCall->getArg(4)); // Order
1161 SubExprs.push_back(TheCall->getArg(1)); // Val1
1162 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1163 SubExprs.push_back(TheCall->getArg(2)); // Val2
1164 SubExprs.push_back(TheCall->getArg(3)); // Weak
1165 break;
Eli Friedman276b0612011-10-11 02:20:01 +00001166 }
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00001167
1168 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1169 SubExprs, ResultType, Op,
1170 TheCall->getRParenLoc());
1171
1172 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1173 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1174 Context.AtomicUsesUnsupportedLibcall(AE))
1175 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1176 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001177
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00001178 return Owned(AE);
Eli Friedman276b0612011-10-11 02:20:01 +00001179}
1180
1181
John McCall5f8d6042011-08-27 01:09:30 +00001182/// checkBuiltinArgument - Given a call to a builtin function, perform
1183/// normal type-checking on the given argument, updating the call in
1184/// place. This is useful when a builtin function requires custom
1185/// type-checking for some of its arguments but not necessarily all of
1186/// them.
1187///
1188/// Returns true on error.
1189static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1190 FunctionDecl *Fn = E->getDirectCallee();
1191 assert(Fn && "builtin call without direct callee!");
1192
1193 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1194 InitializedEntity Entity =
1195 InitializedEntity::InitializeParameter(S.Context, Param);
1196
1197 ExprResult Arg = E->getArg(0);
1198 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1199 if (Arg.isInvalid())
1200 return true;
1201
1202 E->setArg(ArgIndex, Arg.take());
1203 return false;
1204}
1205
Chris Lattner5caa3702009-05-08 06:58:22 +00001206/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1207/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1208/// type of its first argument. The main ActOnCallExpr routines have already
1209/// promoted the types of arguments because all of these calls are prototyped as
1210/// void(...).
1211///
1212/// This function goes through and does final semantic checking for these
1213/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +00001214ExprResult
1215Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +00001216 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +00001217 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1218 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1219
1220 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +00001221 if (TheCall->getNumArgs() < 1) {
1222 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1223 << 0 << 1 << TheCall->getNumArgs()
1224 << TheCall->getCallee()->getSourceRange();
1225 return ExprError();
1226 }
Mike Stump1eb44332009-09-09 15:08:12 +00001227
Chris Lattner5caa3702009-05-08 06:58:22 +00001228 // Inspect the first argument of the atomic builtin. This should always be
1229 // a pointer type, whose element is an integral scalar or pointer type.
1230 // Because it is a pointer type, we don't have to worry about any implicit
1231 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +00001232 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +00001233 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman8c382062012-01-23 02:35:22 +00001234 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1235 if (FirstArgResult.isInvalid())
1236 return ExprError();
1237 FirstArg = FirstArgResult.take();
1238 TheCall->setArg(0, FirstArg);
1239
John McCallf85e1932011-06-15 23:02:42 +00001240 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1241 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +00001242 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1243 << FirstArg->getType() << FirstArg->getSourceRange();
1244 return ExprError();
1245 }
Mike Stump1eb44332009-09-09 15:08:12 +00001246
John McCallf85e1932011-06-15 23:02:42 +00001247 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +00001248 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +00001249 !ValType->isBlockPointerType()) {
1250 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1251 << FirstArg->getType() << FirstArg->getSourceRange();
1252 return ExprError();
1253 }
Chris Lattner5caa3702009-05-08 06:58:22 +00001254
John McCallf85e1932011-06-15 23:02:42 +00001255 switch (ValType.getObjCLifetime()) {
1256 case Qualifiers::OCL_None:
1257 case Qualifiers::OCL_ExplicitNone:
1258 // okay
1259 break;
1260
1261 case Qualifiers::OCL_Weak:
1262 case Qualifiers::OCL_Strong:
1263 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001264 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001265 << ValType << FirstArg->getSourceRange();
1266 return ExprError();
1267 }
1268
John McCallb45ae252011-10-05 07:41:44 +00001269 // Strip any qualifiers off ValType.
1270 ValType = ValType.getUnqualifiedType();
1271
Chandler Carruth8d13d222010-07-18 20:54:12 +00001272 // The majority of builtins return a value, but a few have special return
1273 // types, so allow them to override appropriately below.
1274 QualType ResultType = ValType;
1275
Chris Lattner5caa3702009-05-08 06:58:22 +00001276 // We need to figure out which concrete builtin this maps onto. For example,
1277 // __sync_fetch_and_add with a 2 byte object turns into
1278 // __sync_fetch_and_add_2.
1279#define BUILTIN_ROW(x) \
1280 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1281 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +00001282
Chris Lattner5caa3702009-05-08 06:58:22 +00001283 static const unsigned BuiltinIndices[][5] = {
1284 BUILTIN_ROW(__sync_fetch_and_add),
1285 BUILTIN_ROW(__sync_fetch_and_sub),
1286 BUILTIN_ROW(__sync_fetch_and_or),
1287 BUILTIN_ROW(__sync_fetch_and_and),
1288 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +00001289
Chris Lattner5caa3702009-05-08 06:58:22 +00001290 BUILTIN_ROW(__sync_add_and_fetch),
1291 BUILTIN_ROW(__sync_sub_and_fetch),
1292 BUILTIN_ROW(__sync_and_and_fetch),
1293 BUILTIN_ROW(__sync_or_and_fetch),
1294 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +00001295
Chris Lattner5caa3702009-05-08 06:58:22 +00001296 BUILTIN_ROW(__sync_val_compare_and_swap),
1297 BUILTIN_ROW(__sync_bool_compare_and_swap),
1298 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +00001299 BUILTIN_ROW(__sync_lock_release),
1300 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +00001301 };
Mike Stump1eb44332009-09-09 15:08:12 +00001302#undef BUILTIN_ROW
1303
Chris Lattner5caa3702009-05-08 06:58:22 +00001304 // Determine the index of the size.
1305 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +00001306 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +00001307 case 1: SizeIndex = 0; break;
1308 case 2: SizeIndex = 1; break;
1309 case 4: SizeIndex = 2; break;
1310 case 8: SizeIndex = 3; break;
1311 case 16: SizeIndex = 4; break;
1312 default:
Chandler Carruthd2014572010-07-09 18:59:35 +00001313 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1314 << FirstArg->getType() << FirstArg->getSourceRange();
1315 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +00001316 }
Mike Stump1eb44332009-09-09 15:08:12 +00001317
Chris Lattner5caa3702009-05-08 06:58:22 +00001318 // Each of these builtins has one pointer argument, followed by some number of
1319 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1320 // that we ignore. Find out which row of BuiltinIndices to read from as well
1321 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00001322 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +00001323 unsigned BuiltinIndex, NumFixed = 1;
1324 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001325 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +00001326 case Builtin::BI__sync_fetch_and_add:
1327 case Builtin::BI__sync_fetch_and_add_1:
1328 case Builtin::BI__sync_fetch_and_add_2:
1329 case Builtin::BI__sync_fetch_and_add_4:
1330 case Builtin::BI__sync_fetch_and_add_8:
1331 case Builtin::BI__sync_fetch_and_add_16:
1332 BuiltinIndex = 0;
1333 break;
1334
1335 case Builtin::BI__sync_fetch_and_sub:
1336 case Builtin::BI__sync_fetch_and_sub_1:
1337 case Builtin::BI__sync_fetch_and_sub_2:
1338 case Builtin::BI__sync_fetch_and_sub_4:
1339 case Builtin::BI__sync_fetch_and_sub_8:
1340 case Builtin::BI__sync_fetch_and_sub_16:
1341 BuiltinIndex = 1;
1342 break;
1343
1344 case Builtin::BI__sync_fetch_and_or:
1345 case Builtin::BI__sync_fetch_and_or_1:
1346 case Builtin::BI__sync_fetch_and_or_2:
1347 case Builtin::BI__sync_fetch_and_or_4:
1348 case Builtin::BI__sync_fetch_and_or_8:
1349 case Builtin::BI__sync_fetch_and_or_16:
1350 BuiltinIndex = 2;
1351 break;
1352
1353 case Builtin::BI__sync_fetch_and_and:
1354 case Builtin::BI__sync_fetch_and_and_1:
1355 case Builtin::BI__sync_fetch_and_and_2:
1356 case Builtin::BI__sync_fetch_and_and_4:
1357 case Builtin::BI__sync_fetch_and_and_8:
1358 case Builtin::BI__sync_fetch_and_and_16:
1359 BuiltinIndex = 3;
1360 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001361
Douglas Gregora9766412011-11-28 16:30:08 +00001362 case Builtin::BI__sync_fetch_and_xor:
1363 case Builtin::BI__sync_fetch_and_xor_1:
1364 case Builtin::BI__sync_fetch_and_xor_2:
1365 case Builtin::BI__sync_fetch_and_xor_4:
1366 case Builtin::BI__sync_fetch_and_xor_8:
1367 case Builtin::BI__sync_fetch_and_xor_16:
1368 BuiltinIndex = 4;
1369 break;
1370
1371 case Builtin::BI__sync_add_and_fetch:
1372 case Builtin::BI__sync_add_and_fetch_1:
1373 case Builtin::BI__sync_add_and_fetch_2:
1374 case Builtin::BI__sync_add_and_fetch_4:
1375 case Builtin::BI__sync_add_and_fetch_8:
1376 case Builtin::BI__sync_add_and_fetch_16:
1377 BuiltinIndex = 5;
1378 break;
1379
1380 case Builtin::BI__sync_sub_and_fetch:
1381 case Builtin::BI__sync_sub_and_fetch_1:
1382 case Builtin::BI__sync_sub_and_fetch_2:
1383 case Builtin::BI__sync_sub_and_fetch_4:
1384 case Builtin::BI__sync_sub_and_fetch_8:
1385 case Builtin::BI__sync_sub_and_fetch_16:
1386 BuiltinIndex = 6;
1387 break;
1388
1389 case Builtin::BI__sync_and_and_fetch:
1390 case Builtin::BI__sync_and_and_fetch_1:
1391 case Builtin::BI__sync_and_and_fetch_2:
1392 case Builtin::BI__sync_and_and_fetch_4:
1393 case Builtin::BI__sync_and_and_fetch_8:
1394 case Builtin::BI__sync_and_and_fetch_16:
1395 BuiltinIndex = 7;
1396 break;
1397
1398 case Builtin::BI__sync_or_and_fetch:
1399 case Builtin::BI__sync_or_and_fetch_1:
1400 case Builtin::BI__sync_or_and_fetch_2:
1401 case Builtin::BI__sync_or_and_fetch_4:
1402 case Builtin::BI__sync_or_and_fetch_8:
1403 case Builtin::BI__sync_or_and_fetch_16:
1404 BuiltinIndex = 8;
1405 break;
1406
1407 case Builtin::BI__sync_xor_and_fetch:
1408 case Builtin::BI__sync_xor_and_fetch_1:
1409 case Builtin::BI__sync_xor_and_fetch_2:
1410 case Builtin::BI__sync_xor_and_fetch_4:
1411 case Builtin::BI__sync_xor_and_fetch_8:
1412 case Builtin::BI__sync_xor_and_fetch_16:
1413 BuiltinIndex = 9;
1414 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001415
Chris Lattner5caa3702009-05-08 06:58:22 +00001416 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001417 case Builtin::BI__sync_val_compare_and_swap_1:
1418 case Builtin::BI__sync_val_compare_and_swap_2:
1419 case Builtin::BI__sync_val_compare_and_swap_4:
1420 case Builtin::BI__sync_val_compare_and_swap_8:
1421 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001422 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +00001423 NumFixed = 2;
1424 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001425
Chris Lattner5caa3702009-05-08 06:58:22 +00001426 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001427 case Builtin::BI__sync_bool_compare_and_swap_1:
1428 case Builtin::BI__sync_bool_compare_and_swap_2:
1429 case Builtin::BI__sync_bool_compare_and_swap_4:
1430 case Builtin::BI__sync_bool_compare_and_swap_8:
1431 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001432 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +00001433 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001434 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001435 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001436
1437 case Builtin::BI__sync_lock_test_and_set:
1438 case Builtin::BI__sync_lock_test_and_set_1:
1439 case Builtin::BI__sync_lock_test_and_set_2:
1440 case Builtin::BI__sync_lock_test_and_set_4:
1441 case Builtin::BI__sync_lock_test_and_set_8:
1442 case Builtin::BI__sync_lock_test_and_set_16:
1443 BuiltinIndex = 12;
1444 break;
1445
Chris Lattner5caa3702009-05-08 06:58:22 +00001446 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +00001447 case Builtin::BI__sync_lock_release_1:
1448 case Builtin::BI__sync_lock_release_2:
1449 case Builtin::BI__sync_lock_release_4:
1450 case Builtin::BI__sync_lock_release_8:
1451 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001452 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +00001453 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001454 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001455 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001456
1457 case Builtin::BI__sync_swap:
1458 case Builtin::BI__sync_swap_1:
1459 case Builtin::BI__sync_swap_2:
1460 case Builtin::BI__sync_swap_4:
1461 case Builtin::BI__sync_swap_8:
1462 case Builtin::BI__sync_swap_16:
1463 BuiltinIndex = 14;
1464 break;
Chris Lattner5caa3702009-05-08 06:58:22 +00001465 }
Mike Stump1eb44332009-09-09 15:08:12 +00001466
Chris Lattner5caa3702009-05-08 06:58:22 +00001467 // Now that we know how many fixed arguments we expect, first check that we
1468 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +00001469 if (TheCall->getNumArgs() < 1+NumFixed) {
1470 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1471 << 0 << 1+NumFixed << TheCall->getNumArgs()
1472 << TheCall->getCallee()->getSourceRange();
1473 return ExprError();
1474 }
Mike Stump1eb44332009-09-09 15:08:12 +00001475
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001476 // Get the decl for the concrete builtin from this, we can tell what the
1477 // concrete integer type we should convert to is.
1478 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1479 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara2ad11cd2012-09-22 09:05:22 +00001480 FunctionDecl *NewBuiltinDecl;
1481 if (NewBuiltinID == BuiltinID)
1482 NewBuiltinDecl = FDecl;
1483 else {
1484 // Perform builtin lookup to avoid redeclaring it.
1485 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1486 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1487 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1488 assert(Res.getFoundDecl());
1489 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1490 if (NewBuiltinDecl == 0)
1491 return ExprError();
1492 }
Chandler Carruthd2014572010-07-09 18:59:35 +00001493
John McCallf871d0c2010-08-07 06:22:56 +00001494 // The first argument --- the pointer --- has a fixed type; we
1495 // deduce the types of the rest of the arguments accordingly. Walk
1496 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +00001497 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +00001498 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +00001499
Chris Lattner5caa3702009-05-08 06:58:22 +00001500 // GCC does an implicit conversion to the pointer or integer ValType. This
1501 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +00001502 // Initialize the argument.
1503 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1504 ValType, /*consume*/ false);
1505 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +00001506 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +00001507 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001508
Chris Lattner5caa3702009-05-08 06:58:22 +00001509 // Okay, we have something that *can* be converted to the right type. Check
1510 // to see if there is a potentially weird extension going on here. This can
1511 // happen when you do an atomic operation on something like an char* and
1512 // pass in 42. The 42 gets converted to char. This is even more strange
1513 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +00001514 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +00001515 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +00001516 }
Mike Stump1eb44332009-09-09 15:08:12 +00001517
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001518 ASTContext& Context = this->getASTContext();
1519
1520 // Create a new DeclRefExpr to refer to the new decl.
1521 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1522 Context,
1523 DRE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001524 SourceLocation(),
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001525 NewBuiltinDecl,
John McCallf4b88a42012-03-10 09:33:50 +00001526 /*enclosing*/ false,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001527 DRE->getLocation(),
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001528 Context.BuiltinFnTy,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001529 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +00001530
Chris Lattner5caa3702009-05-08 06:58:22 +00001531 // Set the callee in the CallExpr.
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001532 // FIXME: This loses syntactic information.
1533 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1534 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1535 CK_BuiltinFnToFnPtr);
John Wiegley429bb272011-04-08 18:41:53 +00001536 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001537
Chandler Carruthdb4325b2010-07-18 07:23:17 +00001538 // Change the result type of the call to match the original value type. This
1539 // is arbitrary, but the codegen for these builtins ins design to handle it
1540 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +00001541 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001542
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001543 return TheCallResult;
Chris Lattner5caa3702009-05-08 06:58:22 +00001544}
1545
Chris Lattner69039812009-02-18 06:01:06 +00001546/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00001547/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00001548/// Note: It might also make sense to do the UTF-16 conversion here (would
1549/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00001550bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00001551 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00001552 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1553
Douglas Gregor5cee1192011-07-27 05:40:30 +00001554 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001555 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1556 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001557 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001558 }
Mike Stump1eb44332009-09-09 15:08:12 +00001559
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001560 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001561 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001562 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001563 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divacky31ba6132012-09-06 15:59:27 +00001564 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001565 UTF16 *ToPtr = &ToBuf[0];
1566
1567 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1568 &ToPtr, ToPtr + NumBytes,
1569 strictConversion);
1570 // Check for conversion failure.
1571 if (Result != conversionOK)
1572 Diag(Arg->getLocStart(),
1573 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1574 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001575 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00001576}
1577
Chris Lattnerc27c6652007-12-20 00:05:45 +00001578/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1579/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00001580bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1581 Expr *Fn = TheCall->getCallee();
1582 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001583 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001584 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001585 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1586 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00001587 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001588 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00001589 return true;
1590 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00001591
1592 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00001593 return Diag(TheCall->getLocEnd(),
1594 diag::err_typecheck_call_too_few_args_at_least)
1595 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00001596 }
1597
John McCall5f8d6042011-08-27 01:09:30 +00001598 // Type-check the first argument normally.
1599 if (checkBuiltinArgument(*this, TheCall, 0))
1600 return true;
1601
Chris Lattnerc27c6652007-12-20 00:05:45 +00001602 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001603 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00001604 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001605 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00001606 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00001607 else if (FunctionDecl *FD = getCurFunctionDecl())
1608 isVariadic = FD->isVariadic();
1609 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001610 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00001611
Chris Lattnerc27c6652007-12-20 00:05:45 +00001612 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001613 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1614 return true;
1615 }
Mike Stump1eb44332009-09-09 15:08:12 +00001616
Chris Lattner30ce3442007-12-19 23:59:04 +00001617 // Verify that the second argument to the builtin is the last argument of the
1618 // current function or method.
1619 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00001620 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001621
Nico Weberb07d4482013-05-24 23:31:57 +00001622 // These are valid if SecondArgIsLastNamedArgument is false after the next
1623 // block.
1624 QualType Type;
1625 SourceLocation ParamLoc;
1626
Anders Carlsson88cf2262008-02-11 04:20:54 +00001627 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1628 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001629 // FIXME: This isn't correct for methods (results in bogus warning).
1630 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00001631 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001632 if (CurBlock)
1633 LastArg = *(CurBlock->TheDecl->param_end()-1);
1634 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00001635 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001636 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001637 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001638 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weberb07d4482013-05-24 23:31:57 +00001639
1640 Type = PV->getType();
1641 ParamLoc = PV->getLocation();
Chris Lattner30ce3442007-12-19 23:59:04 +00001642 }
1643 }
Mike Stump1eb44332009-09-09 15:08:12 +00001644
Chris Lattner30ce3442007-12-19 23:59:04 +00001645 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001646 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00001647 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weberb07d4482013-05-24 23:31:57 +00001648 else if (Type->isReferenceType()) {
1649 Diag(Arg->getLocStart(),
1650 diag::warn_va_start_of_reference_type_is_undefined);
1651 Diag(ParamLoc, diag::note_parameter_type) << Type;
1652 }
1653
Chris Lattner30ce3442007-12-19 23:59:04 +00001654 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00001655}
Chris Lattner30ce3442007-12-19 23:59:04 +00001656
Chris Lattner1b9a0792007-12-20 00:26:33 +00001657/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1658/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00001659bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1660 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001661 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001662 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001663 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001664 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001665 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001666 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001667 << SourceRange(TheCall->getArg(2)->getLocStart(),
1668 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001669
John Wiegley429bb272011-04-08 18:41:53 +00001670 ExprResult OrigArg0 = TheCall->getArg(0);
1671 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001672
Chris Lattner1b9a0792007-12-20 00:26:33 +00001673 // Do standard promotions between the two arguments, returning their common
1674 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001675 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001676 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1677 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001678
1679 // Make sure any conversions are pushed back into the call; this is
1680 // type safe since unordered compare builtins are declared as "_Bool
1681 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001682 TheCall->setArg(0, OrigArg0.get());
1683 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001684
John Wiegley429bb272011-04-08 18:41:53 +00001685 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001686 return false;
1687
Chris Lattner1b9a0792007-12-20 00:26:33 +00001688 // If the common type isn't a real floating type, then the arguments were
1689 // invalid for this operation.
Eli Friedman860a3192012-06-16 02:19:17 +00001690 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001691 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001692 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001693 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1694 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001695
Chris Lattner1b9a0792007-12-20 00:26:33 +00001696 return false;
1697}
1698
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001699/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1700/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001701/// to check everything. We expect the last argument to be a floating point
1702/// value.
1703bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1704 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001705 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001706 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001707 if (TheCall->getNumArgs() > NumArgs)
1708 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001709 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001710 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001711 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001712 (*(TheCall->arg_end()-1))->getLocEnd());
1713
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001714 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001715
Eli Friedman9ac6f622009-08-31 20:06:00 +00001716 if (OrigArg->isTypeDependent())
1717 return false;
1718
Chris Lattner81368fb2010-05-06 05:50:07 +00001719 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001720 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001721 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001722 diag::err_typecheck_call_invalid_unary_fp)
1723 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001724
Chris Lattner81368fb2010-05-06 05:50:07 +00001725 // If this is an implicit conversion from float -> double, remove it.
1726 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1727 Expr *CastArg = Cast->getSubExpr();
1728 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1729 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1730 "promotion from float to double is the only expected cast here");
1731 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001732 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner81368fb2010-05-06 05:50:07 +00001733 }
1734 }
1735
Eli Friedman9ac6f622009-08-31 20:06:00 +00001736 return false;
1737}
1738
Eli Friedmand38617c2008-05-14 19:38:39 +00001739/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1740// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001741ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001742 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001743 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001744 diag::err_typecheck_call_too_few_args_at_least)
Craig Topperb44545a2013-07-28 21:50:10 +00001745 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1746 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001747
Nate Begeman37b6a572010-06-08 00:16:34 +00001748 // Determine which of the following types of shufflevector we're checking:
1749 // 1) unary, vector mask: (lhs, mask)
1750 // 2) binary, vector mask: (lhs, rhs, mask)
1751 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1752 QualType resType = TheCall->getArg(0)->getType();
1753 unsigned numElements = 0;
Craig Toppere3fbbe92013-07-19 04:46:31 +00001754
Douglas Gregorcde01732009-05-19 22:10:17 +00001755 if (!TheCall->getArg(0)->isTypeDependent() &&
1756 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001757 QualType LHSType = TheCall->getArg(0)->getType();
1758 QualType RHSType = TheCall->getArg(1)->getType();
Craig Toppere3fbbe92013-07-19 04:46:31 +00001759
Craig Topperbbe759c2013-07-29 06:47:04 +00001760 if (!LHSType->isVectorType() || !RHSType->isVectorType())
1761 return ExprError(Diag(TheCall->getLocStart(),
1762 diag::err_shufflevector_non_vector)
1763 << SourceRange(TheCall->getArg(0)->getLocStart(),
1764 TheCall->getArg(1)->getLocEnd()));
Craig Toppere3fbbe92013-07-19 04:46:31 +00001765
Nate Begeman37b6a572010-06-08 00:16:34 +00001766 numElements = LHSType->getAs<VectorType>()->getNumElements();
1767 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001768
Nate Begeman37b6a572010-06-08 00:16:34 +00001769 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1770 // with mask. If so, verify that RHS is an integer vector type with the
1771 // same number of elts as lhs.
1772 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru4cb3d902013-07-06 08:00:09 +00001773 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001774 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbbe759c2013-07-29 06:47:04 +00001775 return ExprError(Diag(TheCall->getLocStart(),
1776 diag::err_shufflevector_incompatible_vector)
1777 << SourceRange(TheCall->getArg(1)->getLocStart(),
1778 TheCall->getArg(1)->getLocEnd()));
Craig Toppere3fbbe92013-07-19 04:46:31 +00001779 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbbe759c2013-07-29 06:47:04 +00001780 return ExprError(Diag(TheCall->getLocStart(),
1781 diag::err_shufflevector_incompatible_vector)
1782 << SourceRange(TheCall->getArg(0)->getLocStart(),
1783 TheCall->getArg(1)->getLocEnd()));
Nate Begeman37b6a572010-06-08 00:16:34 +00001784 } else if (numElements != numResElements) {
1785 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001786 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001787 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001788 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001789 }
1790
1791 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001792 if (TheCall->getArg(i)->isTypeDependent() ||
1793 TheCall->getArg(i)->isValueDependent())
1794 continue;
1795
Nate Begeman37b6a572010-06-08 00:16:34 +00001796 llvm::APSInt Result(32);
1797 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1798 return ExprError(Diag(TheCall->getLocStart(),
Craig Topperb44545a2013-07-28 21:50:10 +00001799 diag::err_shufflevector_nonconstant_argument)
1800 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001801
Craig Topper6f4f8082013-08-03 17:40:38 +00001802 // Allow -1 which will be translated to undef in the IR.
1803 if (Result.isSigned() && Result.isAllOnesValue())
1804 continue;
1805
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001806 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001807 return ExprError(Diag(TheCall->getLocStart(),
Craig Topperb44545a2013-07-28 21:50:10 +00001808 diag::err_shufflevector_argument_too_large)
1809 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001810 }
1811
Chris Lattner5f9e2722011-07-23 10:55:15 +00001812 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001813
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001814 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001815 exprs.push_back(TheCall->getArg(i));
1816 TheCall->setArg(i, 0);
1817 }
1818
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001819 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001820 TheCall->getCallee()->getLocStart(),
1821 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001822}
Chris Lattner30ce3442007-12-19 23:59:04 +00001823
Hal Finkel414a1bd2013-09-18 03:29:45 +00001824/// SemaConvertVectorExpr - Handle __builtin_convertvector
1825ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
1826 SourceLocation BuiltinLoc,
1827 SourceLocation RParenLoc) {
1828 ExprValueKind VK = VK_RValue;
1829 ExprObjectKind OK = OK_Ordinary;
1830 QualType DstTy = TInfo->getType();
1831 QualType SrcTy = E->getType();
1832
1833 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
1834 return ExprError(Diag(BuiltinLoc,
1835 diag::err_convertvector_non_vector)
1836 << E->getSourceRange());
1837 if (!DstTy->isVectorType() && !DstTy->isDependentType())
1838 return ExprError(Diag(BuiltinLoc,
1839 diag::err_convertvector_non_vector_type));
1840
1841 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
1842 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
1843 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
1844 if (SrcElts != DstElts)
1845 return ExprError(Diag(BuiltinLoc,
1846 diag::err_convertvector_incompatible_vector)
1847 << E->getSourceRange());
1848 }
1849
1850 return Owned(new (Context) ConvertVectorExpr(E, TInfo, DstTy, VK, OK,
1851 BuiltinLoc, RParenLoc));
1852
1853}
1854
Daniel Dunbar4493f792008-07-21 22:59:13 +00001855/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1856// This is declared to take (const void*, ...) and can take two
1857// optional constant int args.
1858bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001859 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001860
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001861 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001862 return Diag(TheCall->getLocEnd(),
1863 diag::err_typecheck_call_too_many_args_at_most)
1864 << 0 /*function call*/ << 3 << NumArgs
1865 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001866
1867 // Argument 0 is checked for us and the remaining arguments must be
1868 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001869 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001870 Expr *Arg = TheCall->getArg(i);
Douglas Gregor592a4232012-06-29 01:05:22 +00001871
1872 // We can't check the value of a dependent argument.
1873 if (Arg->isTypeDependent() || Arg->isValueDependent())
1874 continue;
1875
Eli Friedman9aef7262009-12-04 00:30:06 +00001876 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001877 if (SemaBuiltinConstantArg(TheCall, i, Result))
1878 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001879
Daniel Dunbar4493f792008-07-21 22:59:13 +00001880 // FIXME: gcc issues a warning and rewrites these to 0. These
1881 // seems especially odd for the third argument since the default
1882 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001883 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001884 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001885 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001886 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001887 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001888 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001889 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001890 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001891 }
1892 }
1893
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001894 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001895}
1896
Eric Christopher691ebc32010-04-17 02:26:23 +00001897/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1898/// TheCall is a constant expression.
1899bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1900 llvm::APSInt &Result) {
1901 Expr *Arg = TheCall->getArg(ArgNum);
1902 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1903 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1904
1905 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1906
1907 if (!Arg->isIntegerConstantExpr(Result, Context))
1908 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001909 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001910
Chris Lattner21fb98e2009-09-23 06:06:36 +00001911 return false;
1912}
1913
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001914/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1915/// int type). This simply type checks that type is one of the defined
1916/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001917// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001918bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001919 llvm::APSInt Result;
Douglas Gregor592a4232012-06-29 01:05:22 +00001920
1921 // We can't check the value of a dependent argument.
1922 if (TheCall->getArg(1)->isTypeDependent() ||
1923 TheCall->getArg(1)->isValueDependent())
1924 return false;
1925
Eric Christopher691ebc32010-04-17 02:26:23 +00001926 // Check constant-ness first.
1927 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1928 return true;
1929
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001930 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001931 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001932 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1933 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001934 }
1935
1936 return false;
1937}
1938
Eli Friedman586d6a82009-05-03 06:04:26 +00001939/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001940/// This checks that val is a constant 1.
1941bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1942 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001943 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001944
Eric Christopher691ebc32010-04-17 02:26:23 +00001945 // TODO: This is less than ideal. Overload this to take a value.
1946 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1947 return true;
1948
1949 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001950 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1951 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1952
1953 return false;
1954}
1955
Richard Smith0e218972013-08-05 18:49:43 +00001956namespace {
1957enum StringLiteralCheckType {
1958 SLCT_NotALiteral,
1959 SLCT_UncheckedLiteral,
1960 SLCT_CheckedLiteral
1961};
1962}
1963
Richard Smith831421f2012-06-25 20:30:08 +00001964// Determine if an expression is a string literal or constant string.
1965// If this function returns false on the arguments to a function expecting a
1966// format string, we will usually need to emit a warning.
1967// True string literals are then checked by CheckFormatString.
Richard Smith0e218972013-08-05 18:49:43 +00001968static StringLiteralCheckType
1969checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
1970 bool HasVAListArg, unsigned format_idx,
1971 unsigned firstDataArg, Sema::FormatStringType Type,
1972 Sema::VariadicCallType CallType, bool InFunctionCall,
1973 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001974 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001975 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith831421f2012-06-25 20:30:08 +00001976 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001977
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001978 E = E->IgnoreParenCasts();
Peter Collingbournef111d932011-04-15 00:35:48 +00001979
Richard Smith0e218972013-08-05 18:49:43 +00001980 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikiea73cdcb2012-02-10 21:07:25 +00001981 // Technically -Wformat-nonliteral does not warn about this case.
1982 // The behavior of printf and friends in this case is implementation
1983 // dependent. Ideally if the format string cannot be null then
1984 // it should have a 'nonnull' attribute in the function prototype.
Richard Smith0e218972013-08-05 18:49:43 +00001985 return SLCT_UncheckedLiteral;
David Blaikiea73cdcb2012-02-10 21:07:25 +00001986
Ted Kremenekd30ef872009-01-12 23:09:09 +00001987 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001988 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001989 case Stmt::ConditionalOperatorClass: {
Richard Smith831421f2012-06-25 20:30:08 +00001990 // The expression is a literal if both sub-expressions were, and it was
1991 // completely checked only if both sub-expressions were checked.
1992 const AbstractConditionalOperator *C =
1993 cast<AbstractConditionalOperator>(E);
1994 StringLiteralCheckType Left =
Richard Smith0e218972013-08-05 18:49:43 +00001995 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00001996 HasVAListArg, format_idx, firstDataArg,
Richard Smith0e218972013-08-05 18:49:43 +00001997 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00001998 if (Left == SLCT_NotALiteral)
1999 return SLCT_NotALiteral;
2000 StringLiteralCheckType Right =
Richard Smith0e218972013-08-05 18:49:43 +00002001 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00002002 HasVAListArg, format_idx, firstDataArg,
Richard Smith0e218972013-08-05 18:49:43 +00002003 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002004 return Left < Right ? Left : Right;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002005 }
2006
2007 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00002008 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2009 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002010 }
2011
John McCall56ca35d2011-02-17 10:25:35 +00002012 case Stmt::OpaqueValueExprClass:
2013 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2014 E = src;
2015 goto tryAgain;
2016 }
Richard Smith831421f2012-06-25 20:30:08 +00002017 return SLCT_NotALiteral;
John McCall56ca35d2011-02-17 10:25:35 +00002018
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00002019 case Stmt::PredefinedExprClass:
2020 // While __func__, etc., are technically not string literals, they
2021 // cannot contain format specifiers and thus are not a security
2022 // liability.
Richard Smith831421f2012-06-25 20:30:08 +00002023 return SLCT_UncheckedLiteral;
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00002024
Ted Kremenek082d9362009-03-20 21:35:28 +00002025 case Stmt::DeclRefExprClass: {
2026 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002027
Ted Kremenek082d9362009-03-20 21:35:28 +00002028 // As an exception, do not flag errors for variables binding to
2029 // const string literals.
2030 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2031 bool isConstant = false;
2032 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00002033
Richard Smith0e218972013-08-05 18:49:43 +00002034 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2035 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002036 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smith0e218972013-08-05 18:49:43 +00002037 isConstant = T.isConstant(S.Context) &&
2038 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupase98e5b52012-01-25 10:35:33 +00002039 } else if (T->isObjCObjectPointerType()) {
2040 // In ObjC, there is usually no "const ObjectPointer" type,
2041 // so don't check if the pointee type is constant.
Richard Smith0e218972013-08-05 18:49:43 +00002042 isConstant = T.isConstant(S.Context);
Ted Kremenek082d9362009-03-20 21:35:28 +00002043 }
Mike Stump1eb44332009-09-09 15:08:12 +00002044
Ted Kremenek082d9362009-03-20 21:35:28 +00002045 if (isConstant) {
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00002046 if (const Expr *Init = VD->getAnyInitializer()) {
2047 // Look through initializers like const char c[] = { "foo" }
2048 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2049 if (InitList->isStringLiteralInit())
2050 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2051 }
Richard Smith0e218972013-08-05 18:49:43 +00002052 return checkFormatStringExpr(S, Init, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002053 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002054 firstDataArg, Type, CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002055 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00002056 }
Ted Kremenek082d9362009-03-20 21:35:28 +00002057 }
Mike Stump1eb44332009-09-09 15:08:12 +00002058
Anders Carlssond966a552009-06-28 19:55:58 +00002059 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2060 // special check to see if the format string is a function parameter
2061 // of the function calling the printf function. If the function
2062 // has an attribute indicating it is a printf-like function, then we
2063 // should suppress warnings concerning non-literals being used in a call
2064 // to a vprintf function. For example:
2065 //
2066 // void
2067 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2068 // va_list ap;
2069 // va_start(ap, fmt);
2070 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2071 // ...
Richard Smith0e218972013-08-05 18:49:43 +00002072 // }
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00002073 if (HasVAListArg) {
2074 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2075 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2076 int PVIndex = PV->getFunctionScopeIndex() + 1;
2077 for (specific_attr_iterator<FormatAttr>
2078 i = ND->specific_attr_begin<FormatAttr>(),
2079 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
2080 FormatAttr *PVFormat = *i;
2081 // adjust for implicit parameter
2082 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2083 if (MD->isInstance())
2084 ++PVIndex;
2085 // We also check if the formats are compatible.
2086 // We can't pass a 'scanf' string to a 'printf' function.
2087 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smith0e218972013-08-05 18:49:43 +00002088 Type == S.GetFormatStringType(PVFormat))
Richard Smith831421f2012-06-25 20:30:08 +00002089 return SLCT_UncheckedLiteral;
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00002090 }
2091 }
2092 }
2093 }
Ted Kremenek082d9362009-03-20 21:35:28 +00002094 }
Mike Stump1eb44332009-09-09 15:08:12 +00002095
Richard Smith831421f2012-06-25 20:30:08 +00002096 return SLCT_NotALiteral;
Ted Kremenek082d9362009-03-20 21:35:28 +00002097 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00002098
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00002099 case Stmt::CallExprClass:
2100 case Stmt::CXXMemberCallExprClass: {
Anders Carlsson8f031b32009-06-27 04:05:33 +00002101 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00002102 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2103 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2104 unsigned ArgIndex = FA->getFormatIdx();
2105 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2106 if (MD->isInstance())
2107 --ArgIndex;
2108 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00002109
Richard Smith0e218972013-08-05 18:49:43 +00002110 return checkFormatStringExpr(S, Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002111 HasVAListArg, format_idx, firstDataArg,
Richard Smith0e218972013-08-05 18:49:43 +00002112 Type, CallType, InFunctionCall,
2113 CheckedVarArgs);
Jordan Rose50687312012-06-04 23:52:23 +00002114 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2115 unsigned BuiltinID = FD->getBuiltinID();
2116 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2117 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2118 const Expr *Arg = CE->getArg(0);
Richard Smith0e218972013-08-05 18:49:43 +00002119 return checkFormatStringExpr(S, Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002120 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002121 firstDataArg, Type, CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002122 InFunctionCall, CheckedVarArgs);
Jordan Rose50687312012-06-04 23:52:23 +00002123 }
Anders Carlsson8f031b32009-06-27 04:05:33 +00002124 }
2125 }
Mike Stump1eb44332009-09-09 15:08:12 +00002126
Richard Smith831421f2012-06-25 20:30:08 +00002127 return SLCT_NotALiteral;
Anders Carlsson8f031b32009-06-27 04:05:33 +00002128 }
Fariborz Jahanianc85832f2013-10-18 21:20:34 +00002129
2130 case Stmt::ObjCMessageExprClass: {
2131 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(E);
2132 if (const ObjCMethodDecl *MDecl = ME->getMethodDecl()) {
2133 if (const NamedDecl *ND = dyn_cast<NamedDecl>(MDecl)) {
2134 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2135 unsigned ArgIndex = FA->getFormatIdx();
2136 if (ArgIndex <= ME->getNumArgs()) {
2137 const Expr *Arg = ME->getArg(ArgIndex-1);
2138 return checkFormatStringExpr(S, Arg, Args,
2139 HasVAListArg, format_idx,
2140 firstDataArg, Type, CallType,
2141 InFunctionCall, CheckedVarArgs);
2142 }
2143 }
2144 }
2145 }
2146
2147 return SLCT_NotALiteral;
2148 }
2149
Ted Kremenek082d9362009-03-20 21:35:28 +00002150 case Stmt::ObjCStringLiteralClass:
2151 case Stmt::StringLiteralClass: {
2152 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00002153
Ted Kremenek082d9362009-03-20 21:35:28 +00002154 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00002155 StrE = ObjCFExpr->getString();
2156 else
Ted Kremenek082d9362009-03-20 21:35:28 +00002157 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002158
Ted Kremenekd30ef872009-01-12 23:09:09 +00002159 if (StrE) {
Richard Smith0e218972013-08-05 18:49:43 +00002160 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2161 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002162 return SLCT_CheckedLiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002163 }
Mike Stump1eb44332009-09-09 15:08:12 +00002164
Richard Smith831421f2012-06-25 20:30:08 +00002165 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002166 }
Mike Stump1eb44332009-09-09 15:08:12 +00002167
Ted Kremenek082d9362009-03-20 21:35:28 +00002168 default:
Richard Smith831421f2012-06-25 20:30:08 +00002169 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002170 }
2171}
2172
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00002173void
Mike Stump1eb44332009-09-09 15:08:12 +00002174Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00002175 const Expr * const *ExprArgs,
2176 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00002177 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
2178 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00002179 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00002180 const Expr *ArgExpr = ExprArgs[*i];
Nick Lewycky3edf3872013-01-23 05:08:29 +00002181
2182 // As a special case, transparent unions initialized with zero are
2183 // considered null for the purposes of the nonnull attribute.
2184 if (const RecordType *UT = ArgExpr->getType()->getAsUnionType()) {
2185 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2186 if (const CompoundLiteralExpr *CLE =
2187 dyn_cast<CompoundLiteralExpr>(ArgExpr))
2188 if (const InitListExpr *ILE =
2189 dyn_cast<InitListExpr>(CLE->getInitializer()))
2190 ArgExpr = ILE->getInit(0);
2191 }
2192
2193 bool Result;
2194 if (ArgExpr->EvaluateAsBooleanCondition(Result, Context) && !Result)
Nick Lewycky909a70d2011-03-25 01:44:32 +00002195 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00002196 }
2197}
Ted Kremenekd30ef872009-01-12 23:09:09 +00002198
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002199Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmancaa5ab22013-09-03 21:02:22 +00002200 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002201 .Case("scanf", FST_Scanf)
2202 .Cases("printf", "printf0", FST_Printf)
2203 .Cases("NSString", "CFString", FST_NSString)
2204 .Case("strftime", FST_Strftime)
2205 .Case("strfmon", FST_Strfmon)
2206 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2207 .Default(FST_Unknown);
2208}
2209
Jordan Roseddcfbc92012-07-19 18:10:23 +00002210/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek826a3452010-07-16 02:11:22 +00002211/// functions) for correct use of format strings.
Richard Smith831421f2012-06-25 20:30:08 +00002212/// Returns true if a format string has been fully checked.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002213bool Sema::CheckFormatArguments(const FormatAttr *Format,
2214 ArrayRef<const Expr *> Args,
2215 bool IsCXXMember,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002216 VariadicCallType CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002217 SourceLocation Loc, SourceRange Range,
2218 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith831421f2012-06-25 20:30:08 +00002219 FormatStringInfo FSI;
2220 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002221 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith831421f2012-06-25 20:30:08 +00002222 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smith0e218972013-08-05 18:49:43 +00002223 CallType, Loc, Range, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002224 return false;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002225}
Sebastian Redl4a2614e2009-11-17 18:02:24 +00002226
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002227bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002228 bool HasVAListArg, unsigned format_idx,
2229 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002230 VariadicCallType CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002231 SourceLocation Loc, SourceRange Range,
2232 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002233 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002234 if (format_idx >= Args.size()) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002235 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith831421f2012-06-25 20:30:08 +00002236 return false;
Ted Kremenek71895b92007-08-14 17:39:48 +00002237 }
Mike Stump1eb44332009-09-09 15:08:12 +00002238
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002239 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00002240
Chris Lattner59907c42007-08-10 20:18:51 +00002241 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00002242 //
Ted Kremenek71895b92007-08-14 17:39:48 +00002243 // Dynamically generated format strings are difficult to
2244 // automatically vet at compile time. Requiring that format strings
2245 // are string literals: (1) permits the checking of format strings by
2246 // the compiler and thereby (2) can practically remove the source of
2247 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002248
Mike Stump1eb44332009-09-09 15:08:12 +00002249 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002250 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00002251 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002252 // the same format string checking logic for both ObjC and C strings.
Richard Smith831421f2012-06-25 20:30:08 +00002253 StringLiteralCheckType CT =
Richard Smith0e218972013-08-05 18:49:43 +00002254 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2255 format_idx, firstDataArg, Type, CallType,
2256 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002257 if (CT != SLCT_NotALiteral)
2258 // Literal format string found, check done!
2259 return CT == SLCT_CheckedLiteral;
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002260
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00002261 // Strftime is particular as it always uses a single 'time' argument,
2262 // so it is safe to pass a non-literal string.
2263 if (Type == FST_Strftime)
Richard Smith831421f2012-06-25 20:30:08 +00002264 return false;
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00002265
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00002266 // Do not emit diag when the string param is a macro expansion and the
2267 // format is either NSString or CFString. This is a hack to prevent
2268 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2269 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupasdc170202012-05-04 21:08:08 +00002270 if (Type == FST_NSString &&
2271 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith831421f2012-06-25 20:30:08 +00002272 return false;
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00002273
Chris Lattner655f1412009-04-29 04:59:47 +00002274 // If there are no arguments specified, warn with -Wformat-security, otherwise
2275 // warn only with -Wformat-nonliteral.
Eli Friedman2243e782013-06-18 18:10:01 +00002276 if (Args.size() == firstDataArg)
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002277 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00002278 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00002279 << OrigFormatExpr->getSourceRange();
2280 else
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002281 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00002282 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00002283 << OrigFormatExpr->getSourceRange();
Richard Smith831421f2012-06-25 20:30:08 +00002284 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002285}
Ted Kremenek71895b92007-08-14 17:39:48 +00002286
Ted Kremeneke0e53132010-01-28 23:39:18 +00002287namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00002288class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2289protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00002290 Sema &S;
2291 const StringLiteral *FExpr;
2292 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00002293 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00002294 const unsigned NumDataArgs;
Ted Kremeneke0e53132010-01-28 23:39:18 +00002295 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00002296 const bool HasVAListArg;
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002297 ArrayRef<const Expr *> Args;
Ted Kremenek0d277352010-01-29 01:06:55 +00002298 unsigned FormatIdx;
Richard Smith0e218972013-08-05 18:49:43 +00002299 llvm::SmallBitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00002300 bool usesPositionalArgs;
2301 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00002302 bool inFunctionCall;
Jordan Roseddcfbc92012-07-19 18:10:23 +00002303 Sema::VariadicCallType CallType;
Richard Smith0e218972013-08-05 18:49:43 +00002304 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002305public:
Ted Kremenek826a3452010-07-16 02:11:22 +00002306 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00002307 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002308 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002309 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002310 unsigned formatIdx, bool inFunctionCall,
Richard Smith0e218972013-08-05 18:49:43 +00002311 Sema::VariadicCallType callType,
2312 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremeneke0e53132010-01-28 23:39:18 +00002313 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose50687312012-06-04 23:52:23 +00002314 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2315 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002316 Args(Args), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00002317 usesPositionalArgs(false), atFirstArg(true),
Richard Smith0e218972013-08-05 18:49:43 +00002318 inFunctionCall(inFunctionCall), CallType(callType),
2319 CheckedVarArgs(CheckedVarArgs) {
2320 CoveredArgs.resize(numDataArgs);
2321 CoveredArgs.reset();
2322 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002323
Ted Kremenek07d161f2010-01-29 01:50:07 +00002324 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002325
Ted Kremenek826a3452010-07-16 02:11:22 +00002326 void HandleIncompleteSpecifier(const char *startSpecifier,
2327 unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00002328
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002329 void HandleInvalidLengthModifier(
2330 const analyze_format_string::FormatSpecifier &FS,
2331 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00002332 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002333
Hans Wennborg76517422012-02-22 10:17:01 +00002334 void HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00002335 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00002336 const char *startSpecifier, unsigned specifierLen);
2337
2338 void HandleNonStandardConversionSpecifier(
2339 const analyze_format_string::ConversionSpecifier &CS,
2340 const char *startSpecifier, unsigned specifierLen);
2341
Hans Wennborgf8562642012-03-09 10:10:54 +00002342 virtual void HandlePosition(const char *startPos, unsigned posLen);
2343
Ted Kremenekefaff192010-02-27 01:41:03 +00002344 virtual void HandleInvalidPosition(const char *startSpecifier,
2345 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00002346 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00002347
2348 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
2349
Ted Kremeneke0e53132010-01-28 23:39:18 +00002350 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002351
Richard Trieu55733de2011-10-28 00:41:25 +00002352 template <typename Range>
2353 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2354 const Expr *ArgumentExpr,
2355 PartialDiagnostic PDiag,
2356 SourceLocation StringLoc,
2357 bool IsStringLocation, Range StringRange,
Dmitri Gribenko55431692013-05-05 00:41:58 +00002358 ArrayRef<FixItHint> Fixit = None);
Richard Trieu55733de2011-10-28 00:41:25 +00002359
Ted Kremenek826a3452010-07-16 02:11:22 +00002360protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002361 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2362 const char *startSpec,
2363 unsigned specifierLen,
2364 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00002365
2366 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2367 const char *startSpec,
2368 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002369
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002370 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00002371 CharSourceRange getSpecifierRange(const char *startSpecifier,
2372 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002373 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002374
Ted Kremenek0d277352010-01-29 01:06:55 +00002375 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00002376
2377 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2378 const analyze_format_string::ConversionSpecifier &CS,
2379 const char *startSpecifier, unsigned specifierLen,
2380 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00002381
2382 template <typename Range>
2383 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2384 bool IsStringLocation, Range StringRange,
Dmitri Gribenko55431692013-05-05 00:41:58 +00002385 ArrayRef<FixItHint> Fixit = None);
Richard Trieu55733de2011-10-28 00:41:25 +00002386
2387 void CheckPositionalAndNonpositionalArgs(
2388 const analyze_format_string::FormatSpecifier *FS);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002389};
2390}
2391
Ted Kremenek826a3452010-07-16 02:11:22 +00002392SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00002393 return OrigFormatExpr->getSourceRange();
2394}
2395
Ted Kremenek826a3452010-07-16 02:11:22 +00002396CharSourceRange CheckFormatHandler::
2397getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002398 SourceLocation Start = getLocationOfByte(startSpecifier);
2399 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2400
2401 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002402 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00002403
2404 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002405}
2406
Ted Kremenek826a3452010-07-16 02:11:22 +00002407SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002408 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002409}
2410
Ted Kremenek826a3452010-07-16 02:11:22 +00002411void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2412 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00002413 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2414 getLocationOfByte(startSpecifier),
2415 /*IsStringLocation*/true,
2416 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00002417}
2418
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002419void CheckFormatHandler::HandleInvalidLengthModifier(
2420 const analyze_format_string::FormatSpecifier &FS,
2421 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00002422 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002423 using namespace analyze_format_string;
2424
2425 const LengthModifier &LM = FS.getLengthModifier();
2426 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2427
2428 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002429 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002430 if (FixedLM) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002431 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002432 getLocationOfByte(LM.getStart()),
2433 /*IsStringLocation*/true,
2434 getSpecifierRange(startSpecifier, specifierLen));
2435
2436 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2437 << FixedLM->toString()
2438 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2439
2440 } else {
Jordan Rose8be066e2012-09-08 04:00:12 +00002441 FixItHint Hint;
2442 if (DiagID == diag::warn_format_nonsensical_length)
2443 Hint = FixItHint::CreateRemoval(LMRange);
2444
2445 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002446 getLocationOfByte(LM.getStart()),
2447 /*IsStringLocation*/true,
2448 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose8be066e2012-09-08 04:00:12 +00002449 Hint);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002450 }
2451}
2452
Hans Wennborg76517422012-02-22 10:17:01 +00002453void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00002454 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00002455 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002456 using namespace analyze_format_string;
2457
2458 const LengthModifier &LM = FS.getLengthModifier();
2459 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2460
2461 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002462 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose8be066e2012-09-08 04:00:12 +00002463 if (FixedLM) {
2464 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2465 << LM.toString() << 0,
2466 getLocationOfByte(LM.getStart()),
2467 /*IsStringLocation*/true,
2468 getSpecifierRange(startSpecifier, specifierLen));
2469
2470 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2471 << FixedLM->toString()
2472 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2473
2474 } else {
2475 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2476 << LM.toString() << 0,
2477 getLocationOfByte(LM.getStart()),
2478 /*IsStringLocation*/true,
2479 getSpecifierRange(startSpecifier, specifierLen));
2480 }
Hans Wennborg76517422012-02-22 10:17:01 +00002481}
2482
2483void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2484 const analyze_format_string::ConversionSpecifier &CS,
2485 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose670941c2012-09-13 02:11:15 +00002486 using namespace analyze_format_string;
2487
2488 // See if we know how to fix this conversion specifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002489 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose670941c2012-09-13 02:11:15 +00002490 if (FixedCS) {
2491 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2492 << CS.toString() << /*conversion specifier*/1,
2493 getLocationOfByte(CS.getStart()),
2494 /*IsStringLocation*/true,
2495 getSpecifierRange(startSpecifier, specifierLen));
2496
2497 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2498 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2499 << FixedCS->toString()
2500 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2501 } else {
2502 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2503 << CS.toString() << /*conversion specifier*/1,
2504 getLocationOfByte(CS.getStart()),
2505 /*IsStringLocation*/true,
2506 getSpecifierRange(startSpecifier, specifierLen));
2507 }
Hans Wennborg76517422012-02-22 10:17:01 +00002508}
2509
Hans Wennborgf8562642012-03-09 10:10:54 +00002510void CheckFormatHandler::HandlePosition(const char *startPos,
2511 unsigned posLen) {
2512 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2513 getLocationOfByte(startPos),
2514 /*IsStringLocation*/true,
2515 getSpecifierRange(startPos, posLen));
2516}
2517
Ted Kremenekefaff192010-02-27 01:41:03 +00002518void
Ted Kremenek826a3452010-07-16 02:11:22 +00002519CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2520 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00002521 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2522 << (unsigned) p,
2523 getLocationOfByte(startPos), /*IsStringLocation*/true,
2524 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002525}
2526
Ted Kremenek826a3452010-07-16 02:11:22 +00002527void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00002528 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00002529 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2530 getLocationOfByte(startPos),
2531 /*IsStringLocation*/true,
2532 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002533}
2534
Ted Kremenek826a3452010-07-16 02:11:22 +00002535void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose50687312012-06-04 23:52:23 +00002536 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0c069442011-03-15 21:18:48 +00002537 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00002538 EmitFormatDiagnostic(
2539 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2540 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2541 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00002542 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002543}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002544
Jordan Rose48716662012-07-19 18:10:08 +00002545// Note that this may return NULL if there was an error parsing or building
2546// one of the argument expressions.
Ted Kremenek826a3452010-07-16 02:11:22 +00002547const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002548 return Args[FirstDataArg + i];
Ted Kremenek826a3452010-07-16 02:11:22 +00002549}
2550
2551void CheckFormatHandler::DoneProcessing() {
2552 // Does the number of data arguments exceed the number of
2553 // format conversions in the format string?
2554 if (!HasVAListArg) {
2555 // Find any arguments that weren't covered.
2556 CoveredArgs.flip();
2557 signed notCoveredArg = CoveredArgs.find_first();
2558 if (notCoveredArg >= 0) {
2559 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose48716662012-07-19 18:10:08 +00002560 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2561 SourceLocation Loc = E->getLocStart();
2562 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2563 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2564 Loc, /*IsStringLocation*/false,
2565 getFormatStringRange());
2566 }
Bob Wilsonc03f2df2012-05-03 19:47:19 +00002567 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002568 }
2569 }
2570}
2571
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002572bool
2573CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2574 SourceLocation Loc,
2575 const char *startSpec,
2576 unsigned specifierLen,
2577 const char *csStart,
2578 unsigned csLen) {
2579
2580 bool keepGoing = true;
2581 if (argIndex < NumDataArgs) {
2582 // Consider the argument coverered, even though the specifier doesn't
2583 // make sense.
2584 CoveredArgs.set(argIndex);
2585 }
2586 else {
2587 // If argIndex exceeds the number of data arguments we
2588 // don't issue a warning because that is just a cascade of warnings (and
2589 // they may have intended '%%' anyway). We don't want to continue processing
2590 // the format string after this point, however, as we will like just get
2591 // gibberish when trying to match arguments.
2592 keepGoing = false;
2593 }
2594
Richard Trieu55733de2011-10-28 00:41:25 +00002595 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2596 << StringRef(csStart, csLen),
2597 Loc, /*IsStringLocation*/true,
2598 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002599
2600 return keepGoing;
2601}
2602
Richard Trieu55733de2011-10-28 00:41:25 +00002603void
2604CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2605 const char *startSpec,
2606 unsigned specifierLen) {
2607 EmitFormatDiagnostic(
2608 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2609 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2610}
2611
Ted Kremenek666a1972010-07-26 19:45:42 +00002612bool
2613CheckFormatHandler::CheckNumArgs(
2614 const analyze_format_string::FormatSpecifier &FS,
2615 const analyze_format_string::ConversionSpecifier &CS,
2616 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2617
2618 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002619 PartialDiagnostic PDiag = FS.usesPositionalArg()
2620 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2621 << (argIndex+1) << NumDataArgs)
2622 : S.PDiag(diag::warn_printf_insufficient_data_args);
2623 EmitFormatDiagnostic(
2624 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2625 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00002626 return false;
2627 }
2628 return true;
2629}
2630
Richard Trieu55733de2011-10-28 00:41:25 +00002631template<typename Range>
2632void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2633 SourceLocation Loc,
2634 bool IsStringLocation,
2635 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002636 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002637 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu55733de2011-10-28 00:41:25 +00002638 Loc, IsStringLocation, StringRange, FixIt);
2639}
2640
2641/// \brief If the format string is not within the funcion call, emit a note
2642/// so that the function call and string are in diagnostic messages.
2643///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002644/// \param InFunctionCall if true, the format string is within the function
Richard Trieu55733de2011-10-28 00:41:25 +00002645/// call and only one diagnostic message will be produced. Otherwise, an
2646/// extra note will be emitted pointing to location of the format string.
2647///
2648/// \param ArgumentExpr the expression that is passed as the format string
2649/// argument in the function call. Used for getting locations when two
2650/// diagnostics are emitted.
2651///
2652/// \param PDiag the callee should already have provided any strings for the
2653/// diagnostic message. This function only adds locations and fixits
2654/// to diagnostics.
2655///
2656/// \param Loc primary location for diagnostic. If two diagnostics are
2657/// required, one will be at Loc and a new SourceLocation will be created for
2658/// the other one.
2659///
2660/// \param IsStringLocation if true, Loc points to the format string should be
2661/// used for the note. Otherwise, Loc points to the argument list and will
2662/// be used with PDiag.
2663///
2664/// \param StringRange some or all of the string to highlight. This is
2665/// templated so it can accept either a CharSourceRange or a SourceRange.
2666///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002667/// \param FixIt optional fix it hint for the format string.
Richard Trieu55733de2011-10-28 00:41:25 +00002668template<typename Range>
2669void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2670 const Expr *ArgumentExpr,
2671 PartialDiagnostic PDiag,
2672 SourceLocation Loc,
2673 bool IsStringLocation,
2674 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002675 ArrayRef<FixItHint> FixIt) {
2676 if (InFunctionCall) {
2677 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2678 D << StringRange;
2679 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2680 I != E; ++I) {
2681 D << *I;
2682 }
2683 } else {
Richard Trieu55733de2011-10-28 00:41:25 +00002684 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2685 << ArgumentExpr->getSourceRange();
Jordan Roseec087352012-09-05 22:56:26 +00002686
2687 const Sema::SemaDiagnosticBuilder &Note =
2688 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2689 diag::note_format_string_defined);
2690
2691 Note << StringRange;
2692 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2693 I != E; ++I) {
2694 Note << *I;
2695 }
Richard Trieu55733de2011-10-28 00:41:25 +00002696 }
2697}
2698
Ted Kremenek826a3452010-07-16 02:11:22 +00002699//===--- CHECK: Printf format string checking ------------------------------===//
2700
2701namespace {
2702class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose50687312012-06-04 23:52:23 +00002703 bool ObjCContext;
Ted Kremenek826a3452010-07-16 02:11:22 +00002704public:
2705 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2706 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002707 unsigned numDataArgs, bool isObjC,
Ted Kremenek826a3452010-07-16 02:11:22 +00002708 const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002709 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002710 unsigned formatIdx, bool inFunctionCall,
Richard Smith0e218972013-08-05 18:49:43 +00002711 Sema::VariadicCallType CallType,
2712 llvm::SmallBitVector &CheckedVarArgs)
2713 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2714 numDataArgs, beg, hasVAListArg, Args,
2715 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
2716 ObjCContext(isObjC)
Jordan Roseddcfbc92012-07-19 18:10:23 +00002717 {}
2718
Ted Kremenek826a3452010-07-16 02:11:22 +00002719
2720 bool HandleInvalidPrintfConversionSpecifier(
2721 const analyze_printf::PrintfSpecifier &FS,
2722 const char *startSpecifier,
2723 unsigned specifierLen);
2724
2725 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2726 const char *startSpecifier,
2727 unsigned specifierLen);
Richard Smith831421f2012-06-25 20:30:08 +00002728 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2729 const char *StartSpecifier,
2730 unsigned SpecifierLen,
2731 const Expr *E);
2732
Ted Kremenek826a3452010-07-16 02:11:22 +00002733 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2734 const char *startSpecifier, unsigned specifierLen);
2735 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2736 const analyze_printf::OptionalAmount &Amt,
2737 unsigned type,
2738 const char *startSpecifier, unsigned specifierLen);
2739 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2740 const analyze_printf::OptionalFlag &flag,
2741 const char *startSpecifier, unsigned specifierLen);
2742 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2743 const analyze_printf::OptionalFlag &ignoredFlag,
2744 const analyze_printf::OptionalFlag &flag,
2745 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgf3749f42012-08-07 08:11:26 +00002746 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith831421f2012-06-25 20:30:08 +00002747 const Expr *E, const CharSourceRange &CSR);
2748
Ted Kremenek826a3452010-07-16 02:11:22 +00002749};
2750}
2751
2752bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2753 const analyze_printf::PrintfSpecifier &FS,
2754 const char *startSpecifier,
2755 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002756 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002757 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002758
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002759 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2760 getLocationOfByte(CS.getStart()),
2761 startSpecifier, specifierLen,
2762 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00002763}
2764
Ted Kremenek826a3452010-07-16 02:11:22 +00002765bool CheckPrintfHandler::HandleAmount(
2766 const analyze_format_string::OptionalAmount &Amt,
2767 unsigned k, const char *startSpecifier,
2768 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002769
2770 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002771 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002772 unsigned argIndex = Amt.getArgIndex();
2773 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002774 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2775 << k,
2776 getLocationOfByte(Amt.getStart()),
2777 /*IsStringLocation*/true,
2778 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002779 // Don't do any more checking. We will just emit
2780 // spurious errors.
2781 return false;
2782 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002783
Ted Kremenek0d277352010-01-29 01:06:55 +00002784 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00002785 // Although not in conformance with C99, we also allow the argument to be
2786 // an 'unsigned int' as that is a reasonably safe case. GCC also
2787 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002788 CoveredArgs.set(argIndex);
2789 const Expr *Arg = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00002790 if (!Arg)
2791 return false;
2792
Ted Kremenek0d277352010-01-29 01:06:55 +00002793 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002794
Hans Wennborgf3749f42012-08-07 08:11:26 +00002795 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2796 assert(AT.isValid());
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002797
Hans Wennborgf3749f42012-08-07 08:11:26 +00002798 if (!AT.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00002799 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgf3749f42012-08-07 08:11:26 +00002800 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00002801 << T << Arg->getSourceRange(),
2802 getLocationOfByte(Amt.getStart()),
2803 /*IsStringLocation*/true,
2804 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002805 // Don't do any more checking. We will just emit
2806 // spurious errors.
2807 return false;
2808 }
2809 }
2810 }
2811 return true;
2812}
Ted Kremenek0d277352010-01-29 01:06:55 +00002813
Tom Caree4ee9662010-06-17 19:00:27 +00002814void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00002815 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002816 const analyze_printf::OptionalAmount &Amt,
2817 unsigned type,
2818 const char *startSpecifier,
2819 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002820 const analyze_printf::PrintfConversionSpecifier &CS =
2821 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00002822
Richard Trieu55733de2011-10-28 00:41:25 +00002823 FixItHint fixit =
2824 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2825 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2826 Amt.getConstantLength()))
2827 : FixItHint();
2828
2829 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2830 << type << CS.toString(),
2831 getLocationOfByte(Amt.getStart()),
2832 /*IsStringLocation*/true,
2833 getSpecifierRange(startSpecifier, specifierLen),
2834 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00002835}
2836
Ted Kremenek826a3452010-07-16 02:11:22 +00002837void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002838 const analyze_printf::OptionalFlag &flag,
2839 const char *startSpecifier,
2840 unsigned specifierLen) {
2841 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002842 const analyze_printf::PrintfConversionSpecifier &CS =
2843 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00002844 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2845 << flag.toString() << CS.toString(),
2846 getLocationOfByte(flag.getPosition()),
2847 /*IsStringLocation*/true,
2848 getSpecifierRange(startSpecifier, specifierLen),
2849 FixItHint::CreateRemoval(
2850 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002851}
2852
2853void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00002854 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002855 const analyze_printf::OptionalFlag &ignoredFlag,
2856 const analyze_printf::OptionalFlag &flag,
2857 const char *startSpecifier,
2858 unsigned specifierLen) {
2859 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00002860 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2861 << ignoredFlag.toString() << flag.toString(),
2862 getLocationOfByte(ignoredFlag.getPosition()),
2863 /*IsStringLocation*/true,
2864 getSpecifierRange(startSpecifier, specifierLen),
2865 FixItHint::CreateRemoval(
2866 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002867}
2868
Richard Smith831421f2012-06-25 20:30:08 +00002869// Determines if the specified is a C++ class or struct containing
2870// a member with the specified name and kind (e.g. a CXXMethodDecl named
2871// "c_str()").
2872template<typename MemberKind>
2873static llvm::SmallPtrSet<MemberKind*, 1>
2874CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2875 const RecordType *RT = Ty->getAs<RecordType>();
2876 llvm::SmallPtrSet<MemberKind*, 1> Results;
2877
2878 if (!RT)
2879 return Results;
2880 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2881 if (!RD)
2882 return Results;
2883
2884 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2885 Sema::LookupMemberName);
2886
2887 // We just need to include all members of the right kind turned up by the
2888 // filter, at this point.
2889 if (S.LookupQualifiedName(R, RT->getDecl()))
2890 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2891 NamedDecl *decl = (*I)->getUnderlyingDecl();
2892 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2893 Results.insert(FK);
2894 }
2895 return Results;
2896}
2897
2898// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgf3749f42012-08-07 08:11:26 +00002899// better diagnostic if so. AT is assumed to be valid.
Richard Smith831421f2012-06-25 20:30:08 +00002900// Returns true when a c_str() conversion method is found.
2901bool CheckPrintfHandler::checkForCStrMembers(
Hans Wennborgf3749f42012-08-07 08:11:26 +00002902 const analyze_printf::ArgType &AT, const Expr *E,
Richard Smith831421f2012-06-25 20:30:08 +00002903 const CharSourceRange &CSR) {
2904 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2905
2906 MethodSet Results =
2907 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2908
2909 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2910 MI != ME; ++MI) {
2911 const CXXMethodDecl *Method = *MI;
2912 if (Method->getNumParams() == 0 &&
Hans Wennborgf3749f42012-08-07 08:11:26 +00002913 AT.matchesType(S.Context, Method->getResultType())) {
Richard Smith831421f2012-06-25 20:30:08 +00002914 // FIXME: Suggest parens if the expression needs them.
2915 SourceLocation EndLoc =
2916 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2917 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2918 << "c_str()"
2919 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2920 return true;
2921 }
2922 }
2923
2924 return false;
2925}
2926
Ted Kremeneke0e53132010-01-28 23:39:18 +00002927bool
Ted Kremenek826a3452010-07-16 02:11:22 +00002928CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002929 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00002930 const char *startSpecifier,
2931 unsigned specifierLen) {
2932
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002933 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00002934 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002935 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00002936
Ted Kremenekbaa40062010-07-19 22:01:06 +00002937 if (FS.consumesDataArgument()) {
2938 if (atFirstArg) {
2939 atFirstArg = false;
2940 usesPositionalArgs = FS.usesPositionalArg();
2941 }
2942 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002943 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2944 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002945 return false;
2946 }
Ted Kremenek0d277352010-01-29 01:06:55 +00002947 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002948
Ted Kremenekefaff192010-02-27 01:41:03 +00002949 // First check if the field width, precision, and conversion specifier
2950 // have matching data arguments.
2951 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2952 startSpecifier, specifierLen)) {
2953 return false;
2954 }
2955
2956 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2957 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002958 return false;
2959 }
2960
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002961 if (!CS.consumesDataArgument()) {
2962 // FIXME: Technically specifying a precision or field width here
2963 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002964 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002965 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002966
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002967 // Consume the argument.
2968 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00002969 if (argIndex < NumDataArgs) {
2970 // The check to see if the argIndex is valid will come later.
2971 // We set the bit here because we may exit early from this
2972 // function if we encounter some other error.
2973 CoveredArgs.set(argIndex);
2974 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002975
2976 // Check for using an Objective-C specific conversion specifier
2977 // in a non-ObjC literal.
Jordan Rose50687312012-06-04 23:52:23 +00002978 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002979 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2980 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002981 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002982
Tom Caree4ee9662010-06-17 19:00:27 +00002983 // Check for invalid use of field width
2984 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002985 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00002986 startSpecifier, specifierLen);
2987 }
2988
2989 // Check for invalid use of precision
2990 if (!FS.hasValidPrecision()) {
2991 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2992 startSpecifier, specifierLen);
2993 }
2994
2995 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00002996 if (!FS.hasValidThousandsGroupingPrefix())
2997 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002998 if (!FS.hasValidLeadingZeros())
2999 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3000 if (!FS.hasValidPlusPrefix())
3001 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00003002 if (!FS.hasValidSpacePrefix())
3003 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00003004 if (!FS.hasValidAlternativeForm())
3005 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3006 if (!FS.hasValidLeftJustified())
3007 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3008
3009 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00003010 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3011 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3012 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00003013 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3014 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3015 startSpecifier, specifierLen);
3016
3017 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003018 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00003019 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3020 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003021 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00003022 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003023 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00003024 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3025 diag::warn_format_non_standard_conversion_spec);
Tom Caree4ee9662010-06-17 19:00:27 +00003026
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003027 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3028 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3029
Ted Kremenekda51f0d2010-01-29 01:43:31 +00003030 // The remaining checks depend on the data arguments.
3031 if (HasVAListArg)
3032 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003033
Ted Kremenek666a1972010-07-26 19:45:42 +00003034 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00003035 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003036
Jordan Rose48716662012-07-19 18:10:08 +00003037 const Expr *Arg = getDataArg(argIndex);
3038 if (!Arg)
3039 return true;
3040
3041 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith831421f2012-06-25 20:30:08 +00003042}
3043
Jordan Roseec087352012-09-05 22:56:26 +00003044static bool requiresParensToAddCast(const Expr *E) {
3045 // FIXME: We should have a general way to reason about operator
3046 // precedence and whether parens are actually needed here.
3047 // Take care of a few common cases where they aren't.
3048 const Expr *Inside = E->IgnoreImpCasts();
3049 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3050 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3051
3052 switch (Inside->getStmtClass()) {
3053 case Stmt::ArraySubscriptExprClass:
3054 case Stmt::CallExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003055 case Stmt::CharacterLiteralClass:
3056 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00003057 case Stmt::DeclRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003058 case Stmt::FloatingLiteralClass:
3059 case Stmt::IntegerLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00003060 case Stmt::MemberExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003061 case Stmt::ObjCArrayLiteralClass:
3062 case Stmt::ObjCBoolLiteralExprClass:
3063 case Stmt::ObjCBoxedExprClass:
3064 case Stmt::ObjCDictionaryLiteralClass:
3065 case Stmt::ObjCEncodeExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00003066 case Stmt::ObjCIvarRefExprClass:
3067 case Stmt::ObjCMessageExprClass:
3068 case Stmt::ObjCPropertyRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003069 case Stmt::ObjCStringLiteralClass:
3070 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00003071 case Stmt::ParenExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003072 case Stmt::StringLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00003073 case Stmt::UnaryOperatorClass:
3074 return false;
3075 default:
3076 return true;
3077 }
3078}
3079
Richard Smith831421f2012-06-25 20:30:08 +00003080bool
3081CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3082 const char *StartSpecifier,
3083 unsigned SpecifierLen,
3084 const Expr *E) {
3085 using namespace analyze_format_string;
3086 using namespace analyze_printf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003087 // Now type check the data expression that matches the
3088 // format specifier.
Hans Wennborgf3749f42012-08-07 08:11:26 +00003089 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3090 ObjCContext);
Jordan Rose614a8652012-09-05 22:56:19 +00003091 if (!AT.isValid())
3092 return true;
Jordan Roseec087352012-09-05 22:56:26 +00003093
Jordan Rose448ac3e2012-12-05 18:44:40 +00003094 QualType ExprTy = E->getType();
Ted Kremenek02be9682013-04-10 06:26:26 +00003095 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3096 ExprTy = TET->getUnderlyingExpr()->getType();
3097 }
3098
Jordan Rose448ac3e2012-12-05 18:44:40 +00003099 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00003100 return true;
Jordan Roseee0259d2012-06-04 22:48:57 +00003101
Jordan Rose614a8652012-09-05 22:56:19 +00003102 // Look through argument promotions for our error message's reported type.
3103 // This includes the integral and floating promotions, but excludes array
3104 // and function pointer decay; seeing that an argument intended to be a
3105 // string has type 'char [6]' is probably more confusing than 'char *'.
3106 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3107 if (ICE->getCastKind() == CK_IntegralCast ||
3108 ICE->getCastKind() == CK_FloatingCast) {
3109 E = ICE->getSubExpr();
Jordan Rose448ac3e2012-12-05 18:44:40 +00003110 ExprTy = E->getType();
Jordan Rose614a8652012-09-05 22:56:19 +00003111
3112 // Check if we didn't match because of an implicit cast from a 'char'
3113 // or 'short' to an 'int'. This is done because printf is a varargs
3114 // function.
3115 if (ICE->getType() == S.Context.IntTy ||
3116 ICE->getType() == S.Context.UnsignedIntTy) {
3117 // All further checking is done on the subexpression.
Jordan Rose448ac3e2012-12-05 18:44:40 +00003118 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00003119 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00003120 }
Jordan Roseee0259d2012-06-04 22:48:57 +00003121 }
Jordan Rose448ac3e2012-12-05 18:44:40 +00003122 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3123 // Special case for 'a', which has type 'int' in C.
3124 // Note, however, that we do /not/ want to treat multibyte constants like
3125 // 'MooV' as characters! This form is deprecated but still exists.
3126 if (ExprTy == S.Context.IntTy)
3127 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3128 ExprTy = S.Context.CharTy;
Jordan Rose614a8652012-09-05 22:56:19 +00003129 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003130
Jordan Rose2cd34402012-12-05 18:44:49 +00003131 // %C in an Objective-C context prints a unichar, not a wchar_t.
3132 // If the argument is an integer of some kind, believe the %C and suggest
3133 // a cast instead of changing the conversion specifier.
Jordan Rose448ac3e2012-12-05 18:44:40 +00003134 QualType IntendedTy = ExprTy;
Jordan Rose2cd34402012-12-05 18:44:49 +00003135 if (ObjCContext &&
3136 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3137 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3138 !ExprTy->isCharType()) {
3139 // 'unichar' is defined as a typedef of unsigned short, but we should
3140 // prefer using the typedef if it is visible.
3141 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenek656465d2013-10-15 05:25:17 +00003142
3143 // While we are here, check if the value is an IntegerLiteral that happens
3144 // to be within the valid range.
3145 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3146 const llvm::APInt &V = IL->getValue();
3147 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3148 return true;
3149 }
3150
Jordan Rose2cd34402012-12-05 18:44:49 +00003151 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3152 Sema::LookupOrdinaryName);
3153 if (S.LookupName(Result, S.getCurScope())) {
3154 NamedDecl *ND = Result.getFoundDecl();
3155 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3156 if (TD->getUnderlyingType() == IntendedTy)
3157 IntendedTy = S.Context.getTypedefType(TD);
3158 }
3159 }
3160 }
3161
3162 // Special-case some of Darwin's platform-independence types by suggesting
3163 // casts to primitive types that are known to be large enough.
3164 bool ShouldNotPrintDirectly = false;
Jordan Roseec087352012-09-05 22:56:26 +00003165 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Ted Kremenek6edb0292013-03-25 22:28:37 +00003166 // Use a 'while' to peel off layers of typedefs.
3167 QualType TyTy = IntendedTy;
3168 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
Jordan Roseec087352012-09-05 22:56:26 +00003169 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose2cd34402012-12-05 18:44:49 +00003170 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseec087352012-09-05 22:56:26 +00003171 .Case("NSInteger", S.Context.LongTy)
3172 .Case("NSUInteger", S.Context.UnsignedLongTy)
3173 .Case("SInt32", S.Context.IntTy)
3174 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose2cd34402012-12-05 18:44:49 +00003175 .Default(QualType());
3176
3177 if (!CastTy.isNull()) {
3178 ShouldNotPrintDirectly = true;
3179 IntendedTy = CastTy;
Ted Kremenek6edb0292013-03-25 22:28:37 +00003180 break;
Jordan Rose2cd34402012-12-05 18:44:49 +00003181 }
Ted Kremenek6edb0292013-03-25 22:28:37 +00003182 TyTy = UserTy->desugar();
Jordan Roseec087352012-09-05 22:56:26 +00003183 }
3184 }
3185
Jordan Rose614a8652012-09-05 22:56:19 +00003186 // We may be able to offer a FixItHint if it is a supported type.
3187 PrintfSpecifier fixedFS = FS;
Jordan Roseec087352012-09-05 22:56:26 +00003188 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose614a8652012-09-05 22:56:19 +00003189 S.Context, ObjCContext);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003190
Jordan Rose614a8652012-09-05 22:56:19 +00003191 if (success) {
3192 // Get the fix string from the fixed format specifier
3193 SmallString<16> buf;
3194 llvm::raw_svector_ostream os(buf);
3195 fixedFS.toString(os);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003196
Jordan Roseec087352012-09-05 22:56:26 +00003197 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3198
Jordan Rose2cd34402012-12-05 18:44:49 +00003199 if (IntendedTy == ExprTy) {
3200 // In this case, the specifier is wrong and should be changed to match
3201 // the argument.
3202 EmitFormatDiagnostic(
3203 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3204 << AT.getRepresentativeTypeName(S.Context) << IntendedTy
3205 << E->getSourceRange(),
3206 E->getLocStart(),
3207 /*IsStringLocation*/false,
3208 SpecRange,
3209 FixItHint::CreateReplacement(SpecRange, os.str()));
3210
3211 } else {
Jordan Roseec087352012-09-05 22:56:26 +00003212 // The canonical type for formatting this value is different from the
3213 // actual type of the expression. (This occurs, for example, with Darwin's
3214 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3215 // should be printed as 'long' for 64-bit compatibility.)
3216 // Rather than emitting a normal format/argument mismatch, we want to
3217 // add a cast to the recommended type (and correct the format string
3218 // if necessary).
3219 SmallString<16> CastBuf;
3220 llvm::raw_svector_ostream CastFix(CastBuf);
3221 CastFix << "(";
3222 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3223 CastFix << ")";
3224
3225 SmallVector<FixItHint,4> Hints;
3226 if (!AT.matchesType(S.Context, IntendedTy))
3227 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3228
3229 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3230 // If there's already a cast present, just replace it.
3231 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3232 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3233
3234 } else if (!requiresParensToAddCast(E)) {
3235 // If the expression has high enough precedence,
3236 // just write the C-style cast.
3237 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3238 CastFix.str()));
3239 } else {
3240 // Otherwise, add parens around the expression as well as the cast.
3241 CastFix << "(";
3242 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3243 CastFix.str()));
3244
3245 SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
3246 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3247 }
3248
Jordan Rose2cd34402012-12-05 18:44:49 +00003249 if (ShouldNotPrintDirectly) {
3250 // The expression has a type that should not be printed directly.
3251 // We extract the name from the typedef because we don't want to show
3252 // the underlying type in the diagnostic.
3253 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseec087352012-09-05 22:56:26 +00003254
Jordan Rose2cd34402012-12-05 18:44:49 +00003255 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
3256 << Name << IntendedTy
3257 << E->getSourceRange(),
3258 E->getLocStart(), /*IsStringLocation=*/false,
3259 SpecRange, Hints);
3260 } else {
3261 // In this case, the expression could be printed using a different
3262 // specifier, but we've decided that the specifier is probably correct
3263 // and we should cast instead. Just use the normal warning message.
3264 EmitFormatDiagnostic(
3265 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3266 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3267 << E->getSourceRange(),
3268 E->getLocStart(), /*IsStringLocation*/false,
3269 SpecRange, Hints);
3270 }
Jordan Roseec087352012-09-05 22:56:26 +00003271 }
Jordan Rose614a8652012-09-05 22:56:19 +00003272 } else {
3273 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3274 SpecifierLen);
3275 // Since the warning for passing non-POD types to variadic functions
3276 // was deferred until now, we emit a warning for non-POD
3277 // arguments here.
Richard Smith0e218972013-08-05 18:49:43 +00003278 switch (S.isValidVarArgType(ExprTy)) {
3279 case Sema::VAK_Valid:
3280 case Sema::VAK_ValidInCXX11:
Jordan Rose614a8652012-09-05 22:56:19 +00003281 EmitFormatDiagnostic(
Richard Smith0e218972013-08-05 18:49:43 +00003282 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3283 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3284 << CSR
3285 << E->getSourceRange(),
3286 E->getLocStart(), /*IsStringLocation*/false, CSR);
3287 break;
3288
3289 case Sema::VAK_Undefined:
3290 EmitFormatDiagnostic(
3291 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith80ad52f2013-01-02 11:42:31 +00003292 << S.getLangOpts().CPlusPlus11
Jordan Rose448ac3e2012-12-05 18:44:40 +00003293 << ExprTy
Jordan Rose614a8652012-09-05 22:56:19 +00003294 << CallType
3295 << AT.getRepresentativeTypeName(S.Context)
3296 << CSR
3297 << E->getSourceRange(),
3298 E->getLocStart(), /*IsStringLocation*/false, CSR);
Jordan Rose614a8652012-09-05 22:56:19 +00003299 checkForCStrMembers(AT, E, CSR);
Richard Smith0e218972013-08-05 18:49:43 +00003300 break;
3301
3302 case Sema::VAK_Invalid:
3303 if (ExprTy->isObjCObjectType())
3304 EmitFormatDiagnostic(
3305 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3306 << S.getLangOpts().CPlusPlus11
3307 << ExprTy
3308 << CallType
3309 << AT.getRepresentativeTypeName(S.Context)
3310 << CSR
3311 << E->getSourceRange(),
3312 E->getLocStart(), /*IsStringLocation*/false, CSR);
3313 else
3314 // FIXME: If this is an initializer list, suggest removing the braces
3315 // or inserting a cast to the target type.
3316 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3317 << isa<InitListExpr>(E) << ExprTy << CallType
3318 << AT.getRepresentativeTypeName(S.Context)
3319 << E->getSourceRange();
3320 break;
3321 }
3322
3323 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3324 "format string specifier index out of range");
3325 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003326 }
3327
Ted Kremeneke0e53132010-01-28 23:39:18 +00003328 return true;
3329}
3330
Ted Kremenek826a3452010-07-16 02:11:22 +00003331//===--- CHECK: Scanf format string checking ------------------------------===//
3332
3333namespace {
3334class CheckScanfHandler : public CheckFormatHandler {
3335public:
3336 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3337 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003338 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003339 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003340 unsigned formatIdx, bool inFunctionCall,
Richard Smith0e218972013-08-05 18:49:43 +00003341 Sema::VariadicCallType CallType,
3342 llvm::SmallBitVector &CheckedVarArgs)
3343 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3344 numDataArgs, beg, hasVAListArg,
3345 Args, formatIdx, inFunctionCall, CallType,
3346 CheckedVarArgs)
Jordan Roseddcfbc92012-07-19 18:10:23 +00003347 {}
Ted Kremenek826a3452010-07-16 02:11:22 +00003348
3349 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3350 const char *startSpecifier,
3351 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003352
3353 bool HandleInvalidScanfConversionSpecifier(
3354 const analyze_scanf::ScanfSpecifier &FS,
3355 const char *startSpecifier,
3356 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00003357
3358 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00003359};
Ted Kremenek07d161f2010-01-29 01:50:07 +00003360}
Ted Kremeneke0e53132010-01-28 23:39:18 +00003361
Ted Kremenekb7c21012010-07-16 18:28:03 +00003362void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3363 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00003364 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3365 getLocationOfByte(end), /*IsStringLocation*/true,
3366 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00003367}
3368
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003369bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3370 const analyze_scanf::ScanfSpecifier &FS,
3371 const char *startSpecifier,
3372 unsigned specifierLen) {
3373
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003374 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003375 FS.getConversionSpecifier();
3376
3377 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3378 getLocationOfByte(CS.getStart()),
3379 startSpecifier, specifierLen,
3380 CS.getStart(), CS.getLength());
3381}
3382
Ted Kremenek826a3452010-07-16 02:11:22 +00003383bool CheckScanfHandler::HandleScanfSpecifier(
3384 const analyze_scanf::ScanfSpecifier &FS,
3385 const char *startSpecifier,
3386 unsigned specifierLen) {
3387
3388 using namespace analyze_scanf;
3389 using namespace analyze_format_string;
3390
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003391 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00003392
Ted Kremenekbaa40062010-07-19 22:01:06 +00003393 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3394 // be used to decide if we are using positional arguments consistently.
3395 if (FS.consumesDataArgument()) {
3396 if (atFirstArg) {
3397 atFirstArg = false;
3398 usesPositionalArgs = FS.usesPositionalArg();
3399 }
3400 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003401 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3402 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00003403 return false;
3404 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003405 }
3406
3407 // Check if the field with is non-zero.
3408 const OptionalAmount &Amt = FS.getFieldWidth();
3409 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3410 if (Amt.getConstantAmount() == 0) {
3411 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3412 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00003413 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3414 getLocationOfByte(Amt.getStart()),
3415 /*IsStringLocation*/true, R,
3416 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00003417 }
3418 }
3419
3420 if (!FS.consumesDataArgument()) {
3421 // FIXME: Technically specifying a precision or field width here
3422 // makes no sense. Worth issuing a warning at some point.
3423 return true;
3424 }
3425
3426 // Consume the argument.
3427 unsigned argIndex = FS.getArgIndex();
3428 if (argIndex < NumDataArgs) {
3429 // The check to see if the argIndex is valid will come later.
3430 // We set the bit here because we may exit early from this
3431 // function if we encounter some other error.
3432 CoveredArgs.set(argIndex);
3433 }
3434
Ted Kremenek1e51c202010-07-20 20:04:47 +00003435 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003436 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00003437 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3438 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003439 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00003440 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003441 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00003442 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3443 diag::warn_format_non_standard_conversion_spec);
Hans Wennborg76517422012-02-22 10:17:01 +00003444
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003445 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3446 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3447
Ted Kremenek826a3452010-07-16 02:11:22 +00003448 // The remaining checks depend on the data arguments.
3449 if (HasVAListArg)
3450 return true;
3451
Ted Kremenek666a1972010-07-26 19:45:42 +00003452 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00003453 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00003454
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003455 // Check that the argument type matches the format specifier.
3456 const Expr *Ex = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00003457 if (!Ex)
3458 return true;
3459
Hans Wennborg58e1e542012-08-07 08:59:46 +00003460 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3461 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003462 ScanfSpecifier fixedFS = FS;
David Blaikie4e4d0842012-03-11 07:00:24 +00003463 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgbe6126a2012-02-15 09:59:46 +00003464 S.Context);
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003465
3466 if (success) {
3467 // Get the fix string from the fixed format specifier.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003468 SmallString<128> buf;
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003469 llvm::raw_svector_ostream os(buf);
3470 fixedFS.toString(os);
3471
3472 EmitFormatDiagnostic(
3473 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003474 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003475 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003476 Ex->getLocStart(),
3477 /*IsStringLocation*/false,
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003478 getSpecifierRange(startSpecifier, specifierLen),
3479 FixItHint::CreateReplacement(
3480 getSpecifierRange(startSpecifier, specifierLen),
3481 os.str()));
3482 } else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003483 EmitFormatDiagnostic(
3484 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003485 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003486 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003487 Ex->getLocStart(),
3488 /*IsStringLocation*/false,
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003489 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003490 }
3491 }
3492
Ted Kremenek826a3452010-07-16 02:11:22 +00003493 return true;
3494}
3495
3496void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00003497 const Expr *OrigFormatExpr,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003498 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003499 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003500 unsigned firstDataArg, FormatStringType Type,
Richard Smith0e218972013-08-05 18:49:43 +00003501 bool inFunctionCall, VariadicCallType CallType,
3502 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003503
Ted Kremeneke0e53132010-01-28 23:39:18 +00003504 // CHECK: is the format string a wide literal?
Richard Smithdf9ef1b2012-06-13 05:37:23 +00003505 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003506 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003507 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003508 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3509 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003510 return;
3511 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003512
Ted Kremeneke0e53132010-01-28 23:39:18 +00003513 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00003514 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00003515 const char *Str = StrRef.data();
3516 unsigned StrLen = StrRef.size();
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003517 const unsigned numDataArgs = Args.size() - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00003518
Ted Kremeneke0e53132010-01-28 23:39:18 +00003519 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00003520 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00003521 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003522 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003523 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3524 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003525 return;
3526 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003527
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003528 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003529 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003530 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003531 Str, HasVAListArg, Args, format_idx,
Richard Smith0e218972013-08-05 18:49:43 +00003532 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek826a3452010-07-16 02:11:22 +00003533
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003534 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003535 getLangOpts(),
3536 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003537 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003538 } else if (Type == FST_Scanf) {
Jordan Rose50687312012-06-04 23:52:23 +00003539 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003540 Str, HasVAListArg, Args, format_idx,
Richard Smith0e218972013-08-05 18:49:43 +00003541 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek826a3452010-07-16 02:11:22 +00003542
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003543 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003544 getLangOpts(),
3545 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003546 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003547 } // TODO: handle other formats
Ted Kremenekce7024e2010-01-28 01:18:22 +00003548}
3549
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003550//===--- CHECK: Standard memory functions ---------------------------------===//
3551
Douglas Gregor2a053a32011-05-03 20:05:22 +00003552/// \brief Determine whether the given type is a dynamic class type (e.g.,
3553/// whether it has a vtable).
3554static bool isDynamicClassType(QualType T) {
3555 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3556 if (CXXRecordDecl *Definition = Record->getDefinition())
3557 if (Definition->isDynamicClass())
3558 return true;
3559
3560 return false;
3561}
3562
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003563/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00003564/// otherwise returns NULL.
3565static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00003566 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00003567 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3568 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
3569 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003570
Chandler Carruth000d4282011-06-16 09:09:40 +00003571 return 0;
3572}
3573
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003574/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00003575static QualType getSizeOfArgType(const Expr* E) {
3576 if (const UnaryExprOrTypeTraitExpr *SizeOf =
3577 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3578 if (SizeOf->getKind() == clang::UETT_SizeOf)
3579 return SizeOf->getTypeOfArgument();
3580
3581 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00003582}
3583
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003584/// \brief Check for dangerous or invalid arguments to memset().
3585///
Chandler Carruth929f0132011-06-03 06:23:57 +00003586/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003587/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3588/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003589///
3590/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003591void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00003592 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003593 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00003594 assert(BId != 0);
3595
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003596 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00003597 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00003598 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00003599 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003600 return;
3601
Anna Zaks0a151a12012-01-17 00:37:07 +00003602 unsigned LastArg = (BId == Builtin::BImemset ||
3603 BId == Builtin::BIstrndup ? 1 : 2);
3604 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00003605 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00003606
3607 // We have special checking when the length is a sizeof expression.
3608 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
3609 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
3610 llvm::FoldingSetNodeID SizeOfArgID;
3611
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003612 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
3613 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003614 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003615
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003616 QualType DestTy = Dest->getType();
3617 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
3618 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00003619
Chandler Carruth000d4282011-06-16 09:09:40 +00003620 // Never warn about void type pointers. This can be used to suppress
3621 // false positives.
3622 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003623 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003624
Chandler Carruth000d4282011-06-16 09:09:40 +00003625 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
3626 // actually comparing the expressions for equality. Because computing the
3627 // expression IDs can be expensive, we only do this if the diagnostic is
3628 // enabled.
3629 if (SizeOfArg &&
3630 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
3631 SizeOfArg->getExprLoc())) {
3632 // We only compute IDs for expressions if the warning is enabled, and
3633 // cache the sizeof arg's ID.
3634 if (SizeOfArgID == llvm::FoldingSetNodeID())
3635 SizeOfArg->Profile(SizeOfArgID, Context, true);
3636 llvm::FoldingSetNodeID DestID;
3637 Dest->Profile(DestID, Context, true);
3638 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00003639 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
3640 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00003641 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003642 StringRef ReadableName = FnName->getName();
3643
Chandler Carruth000d4282011-06-16 09:09:40 +00003644 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaks90c78322012-05-30 23:14:52 +00003645 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth000d4282011-06-16 09:09:40 +00003646 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian7adf4172013-01-30 01:12:44 +00003647 if (!PointeeTy->isIncompleteType() &&
3648 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth000d4282011-06-16 09:09:40 +00003649 ActionIdx = 2; // If the pointee's size is sizeof(char),
3650 // suggest an explicit length.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003651
3652 // If the function is defined as a builtin macro, do not show macro
3653 // expansion.
3654 SourceLocation SL = SizeOfArg->getExprLoc();
3655 SourceRange DSR = Dest->getSourceRange();
3656 SourceRange SSR = SizeOfArg->getSourceRange();
3657 SourceManager &SM = PP.getSourceManager();
3658
3659 if (SM.isMacroArgExpansion(SL)) {
3660 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
3661 SL = SM.getSpellingLoc(SL);
3662 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
3663 SM.getSpellingLoc(DSR.getEnd()));
3664 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
3665 SM.getSpellingLoc(SSR.getEnd()));
3666 }
3667
Anna Zaks90c78322012-05-30 23:14:52 +00003668 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth000d4282011-06-16 09:09:40 +00003669 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks6fcb3722012-05-30 00:34:21 +00003670 << ReadableName
Anna Zaks90c78322012-05-30 23:14:52 +00003671 << PointeeTy
3672 << DestTy
Anna Zaks6fcb3722012-05-30 00:34:21 +00003673 << DSR
Anna Zaks90c78322012-05-30 23:14:52 +00003674 << SSR);
3675 DiagRuntimeBehavior(SL, SizeOfArg,
3676 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
3677 << ActionIdx
3678 << SSR);
3679
Chandler Carruth000d4282011-06-16 09:09:40 +00003680 break;
3681 }
3682 }
3683
3684 // Also check for cases where the sizeof argument is the exact same
3685 // type as the memory argument, and where it points to a user-defined
3686 // record type.
3687 if (SizeOfArgTy != QualType()) {
3688 if (PointeeTy->isRecordType() &&
3689 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
3690 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
3691 PDiag(diag::warn_sizeof_pointer_type_memaccess)
3692 << FnName << SizeOfArgTy << ArgIdx
3693 << PointeeTy << Dest->getSourceRange()
3694 << LenExpr->getSourceRange());
3695 break;
3696 }
Nico Webere4a1c642011-06-14 16:14:58 +00003697 }
3698
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003699 // Always complain about dynamic classes.
Anna Zaks0a151a12012-01-17 00:37:07 +00003700 if (isDynamicClassType(PointeeTy)) {
3701
3702 unsigned OperationType = 0;
3703 // "overwritten" if we're warning about the destination for any call
3704 // but memcmp; otherwise a verb appropriate to the call.
3705 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
3706 if (BId == Builtin::BImemcpy)
3707 OperationType = 1;
3708 else if(BId == Builtin::BImemmove)
3709 OperationType = 2;
3710 else if (BId == Builtin::BImemcmp)
3711 OperationType = 3;
3712 }
3713
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003714 DiagRuntimeBehavior(
3715 Dest->getExprLoc(), Dest,
3716 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks0a151a12012-01-17 00:37:07 +00003717 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaksd9b859a2012-01-13 21:52:01 +00003718 << FnName << PointeeTy
Anna Zaks0a151a12012-01-17 00:37:07 +00003719 << OperationType
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003720 << Call->getCallee()->getSourceRange());
Anna Zaks0a151a12012-01-17 00:37:07 +00003721 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
3722 BId != Builtin::BImemset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003723 DiagRuntimeBehavior(
3724 Dest->getExprLoc(), Dest,
3725 PDiag(diag::warn_arc_object_memaccess)
3726 << ArgIdx << FnName << PointeeTy
3727 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00003728 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003729 continue;
John McCallf85e1932011-06-15 23:02:42 +00003730
3731 DiagRuntimeBehavior(
3732 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00003733 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003734 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
3735 break;
3736 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003737 }
3738}
3739
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003740// A little helper routine: ignore addition and subtraction of integer literals.
3741// This intentionally does not ignore all integer constant expressions because
3742// we don't want to remove sizeof().
3743static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
3744 Ex = Ex->IgnoreParenCasts();
3745
3746 for (;;) {
3747 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
3748 if (!BO || !BO->isAdditiveOp())
3749 break;
3750
3751 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
3752 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
3753
3754 if (isa<IntegerLiteral>(RHS))
3755 Ex = LHS;
3756 else if (isa<IntegerLiteral>(LHS))
3757 Ex = RHS;
3758 else
3759 break;
3760 }
3761
3762 return Ex;
3763}
3764
Anna Zaks0f38ace2012-08-08 21:42:23 +00003765static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
3766 ASTContext &Context) {
3767 // Only handle constant-sized or VLAs, but not flexible members.
3768 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
3769 // Only issue the FIXIT for arrays of size > 1.
3770 if (CAT->getSize().getSExtValue() <= 1)
3771 return false;
3772 } else if (!Ty->isVariableArrayType()) {
3773 return false;
3774 }
3775 return true;
3776}
3777
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003778// Warn if the user has made the 'size' argument to strlcpy or strlcat
3779// be the size of the source, instead of the destination.
3780void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
3781 IdentifierInfo *FnName) {
3782
3783 // Don't crash if the user has the wrong number of arguments
3784 if (Call->getNumArgs() != 3)
3785 return;
3786
3787 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
3788 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
3789 const Expr *CompareWithSrc = NULL;
3790
3791 // Look for 'strlcpy(dst, x, sizeof(x))'
3792 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
3793 CompareWithSrc = Ex;
3794 else {
3795 // Look for 'strlcpy(dst, x, strlen(x))'
3796 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smith180f4792011-11-10 06:34:14 +00003797 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003798 && SizeCall->getNumArgs() == 1)
3799 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
3800 }
3801 }
3802
3803 if (!CompareWithSrc)
3804 return;
3805
3806 // Determine if the argument to sizeof/strlen is equal to the source
3807 // argument. In principle there's all kinds of things you could do
3808 // here, for instance creating an == expression and evaluating it with
3809 // EvaluateAsBooleanCondition, but this uses a more direct technique:
3810 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
3811 if (!SrcArgDRE)
3812 return;
3813
3814 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
3815 if (!CompareWithSrcDRE ||
3816 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
3817 return;
3818
3819 const Expr *OriginalSizeArg = Call->getArg(2);
3820 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
3821 << OriginalSizeArg->getSourceRange() << FnName;
3822
3823 // Output a FIXIT hint if the destination is an array (rather than a
3824 // pointer to an array). This could be enhanced to handle some
3825 // pointers if we know the actual size, like if DstArg is 'array+2'
3826 // we could say 'sizeof(array)-2'.
3827 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks0f38ace2012-08-08 21:42:23 +00003828 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek8f746222011-08-18 22:48:41 +00003829 return;
Ted Kremenek8f746222011-08-18 22:48:41 +00003830
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003831 SmallString<128> sizeString;
Ted Kremenek8f746222011-08-18 22:48:41 +00003832 llvm::raw_svector_ostream OS(sizeString);
3833 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003834 DstArg->printPretty(OS, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00003835 OS << ")";
3836
3837 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
3838 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
3839 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003840}
3841
Anna Zaksc36bedc2012-02-01 19:08:57 +00003842/// Check if two expressions refer to the same declaration.
3843static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
3844 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
3845 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
3846 return D1->getDecl() == D2->getDecl();
3847 return false;
3848}
3849
3850static const Expr *getStrlenExprArg(const Expr *E) {
3851 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
3852 const FunctionDecl *FD = CE->getDirectCallee();
3853 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
3854 return 0;
3855 return CE->getArg(0)->IgnoreParenCasts();
3856 }
3857 return 0;
3858}
3859
3860// Warn on anti-patterns as the 'size' argument to strncat.
3861// The correct size argument should look like following:
3862// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3863void Sema::CheckStrncatArguments(const CallExpr *CE,
3864 IdentifierInfo *FnName) {
3865 // Don't crash if the user has the wrong number of arguments.
3866 if (CE->getNumArgs() < 3)
3867 return;
3868 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
3869 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
3870 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
3871
3872 // Identify common expressions, which are wrongly used as the size argument
3873 // to strncat and may lead to buffer overflows.
3874 unsigned PatternType = 0;
3875 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
3876 // - sizeof(dst)
3877 if (referToTheSameDecl(SizeOfArg, DstArg))
3878 PatternType = 1;
3879 // - sizeof(src)
3880 else if (referToTheSameDecl(SizeOfArg, SrcArg))
3881 PatternType = 2;
3882 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
3883 if (BE->getOpcode() == BO_Sub) {
3884 const Expr *L = BE->getLHS()->IgnoreParenCasts();
3885 const Expr *R = BE->getRHS()->IgnoreParenCasts();
3886 // - sizeof(dst) - strlen(dst)
3887 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
3888 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
3889 PatternType = 1;
3890 // - sizeof(src) - (anything)
3891 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
3892 PatternType = 2;
3893 }
3894 }
3895
3896 if (PatternType == 0)
3897 return;
3898
Anna Zaksafdb0412012-02-03 01:27:37 +00003899 // Generate the diagnostic.
3900 SourceLocation SL = LenArg->getLocStart();
3901 SourceRange SR = LenArg->getSourceRange();
3902 SourceManager &SM = PP.getSourceManager();
3903
3904 // If the function is defined as a builtin macro, do not show macro expansion.
3905 if (SM.isMacroArgExpansion(SL)) {
3906 SL = SM.getSpellingLoc(SL);
3907 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
3908 SM.getSpellingLoc(SR.getEnd()));
3909 }
3910
Anna Zaks0f38ace2012-08-08 21:42:23 +00003911 // Check if the destination is an array (rather than a pointer to an array).
3912 QualType DstTy = DstArg->getType();
3913 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
3914 Context);
3915 if (!isKnownSizeArray) {
3916 if (PatternType == 1)
3917 Diag(SL, diag::warn_strncat_wrong_size) << SR;
3918 else
3919 Diag(SL, diag::warn_strncat_src_size) << SR;
3920 return;
3921 }
3922
Anna Zaksc36bedc2012-02-01 19:08:57 +00003923 if (PatternType == 1)
Anna Zaksafdb0412012-02-03 01:27:37 +00003924 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003925 else
Anna Zaksafdb0412012-02-03 01:27:37 +00003926 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003927
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003928 SmallString<128> sizeString;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003929 llvm::raw_svector_ostream OS(sizeString);
3930 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003931 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003932 OS << ") - ";
3933 OS << "strlen(";
Richard Smithd1420c62012-08-16 03:56:14 +00003934 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003935 OS << ") - 1";
3936
Anna Zaksafdb0412012-02-03 01:27:37 +00003937 Diag(SL, diag::note_strncat_wrong_size)
3938 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003939}
3940
Ted Kremenek06de2762007-08-17 16:46:58 +00003941//===--- CHECK: Return Address of Stack Variable --------------------------===//
3942
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003943static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3944 Decl *ParentDecl);
3945static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
3946 Decl *ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003947
3948/// CheckReturnStackAddr - Check if a return statement returns the address
3949/// of a stack variable.
3950void
3951Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
3952 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00003953
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003954 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003955 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003956
3957 // Perform checking for returned stack addresses, local blocks,
3958 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00003959 if (lhsType->isPointerType() ||
David Blaikie4e4d0842012-03-11 07:00:24 +00003960 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003961 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003962 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003963 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003964 }
3965
3966 if (stackE == 0)
3967 return; // Nothing suspicious was found.
3968
3969 SourceLocation diagLoc;
3970 SourceRange diagRange;
3971 if (refVars.empty()) {
3972 diagLoc = stackE->getLocStart();
3973 diagRange = stackE->getSourceRange();
3974 } else {
3975 // We followed through a reference variable. 'stackE' contains the
3976 // problematic expression but we will warn at the return statement pointing
3977 // at the reference variable. We will later display the "trail" of
3978 // reference variables using notes.
3979 diagLoc = refVars[0]->getLocStart();
3980 diagRange = refVars[0]->getSourceRange();
3981 }
3982
3983 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
3984 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
3985 : diag::warn_ret_stack_addr)
3986 << DR->getDecl()->getDeclName() << diagRange;
3987 } else if (isa<BlockExpr>(stackE)) { // local block.
3988 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
3989 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
3990 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
3991 } else { // local temporary.
3992 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
3993 : diag::warn_ret_local_temp_addr)
3994 << diagRange;
3995 }
3996
3997 // Display the "trail" of reference variables that we followed until we
3998 // found the problematic expression using notes.
3999 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4000 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4001 // If this var binds to another reference var, show the range of the next
4002 // var, otherwise the var binds to the problematic expression, in which case
4003 // show the range of the expression.
4004 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4005 : stackE->getSourceRange();
4006 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4007 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00004008 }
4009}
4010
4011/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4012/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004013/// to a location on the stack, a local block, an address of a label, or a
4014/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00004015/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004016/// encounter a subexpression that (1) clearly does not lead to one of the
4017/// above problematic expressions (2) is something we cannot determine leads to
4018/// a problematic expression based on such local checking.
4019///
4020/// Both EvalAddr and EvalVal follow through reference variables to evaluate
4021/// the expression that they point to. Such variables are added to the
4022/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00004023///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00004024/// EvalAddr processes expressions that are pointers that are used as
4025/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004026/// At the base case of the recursion is a check for the above problematic
4027/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00004028///
4029/// This implementation handles:
4030///
4031/// * pointer-to-pointer casts
4032/// * implicit conversions from array references to pointers
4033/// * taking the address of fields
4034/// * arbitrary interplay between "&" and "*" operators
4035/// * pointer arithmetic from an address of a stack variable
4036/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004037static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4038 Decl *ParentDecl) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004039 if (E->isTypeDependent())
Craig Topperb61c2942013-08-02 05:10:31 +00004040 return NULL;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004041
Ted Kremenek06de2762007-08-17 16:46:58 +00004042 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00004043 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00004044 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004045 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004046 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00004047
Peter Collingbournef111d932011-04-15 00:35:48 +00004048 E = E->IgnoreParens();
4049
Ted Kremenek06de2762007-08-17 16:46:58 +00004050 // Our "symbolic interpreter" is just a dispatch off the currently
4051 // viewed AST node. We then recursively traverse the AST by calling
4052 // EvalAddr and EvalVal appropriately.
4053 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004054 case Stmt::DeclRefExprClass: {
4055 DeclRefExpr *DR = cast<DeclRefExpr>(E);
4056
4057 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
4058 // If this is a reference variable, follow through to the expression that
4059 // it points to.
4060 if (V->hasLocalStorage() &&
4061 V->getType()->isReferenceType() && V->hasInit()) {
4062 // Add the reference variable to the "trail".
4063 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004064 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004065 }
4066
4067 return NULL;
4068 }
Ted Kremenek06de2762007-08-17 16:46:58 +00004069
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004070 case Stmt::UnaryOperatorClass: {
4071 // The only unary operator that make sense to handle here
4072 // is AddrOf. All others don't make sense as pointers.
4073 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004074
John McCall2de56d12010-08-25 11:45:40 +00004075 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004076 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004077 else
Ted Kremenek06de2762007-08-17 16:46:58 +00004078 return NULL;
4079 }
Mike Stump1eb44332009-09-09 15:08:12 +00004080
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004081 case Stmt::BinaryOperatorClass: {
4082 // Handle pointer arithmetic. All other binary operators are not valid
4083 // in this context.
4084 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00004085 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00004086
John McCall2de56d12010-08-25 11:45:40 +00004087 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004088 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00004089
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004090 Expr *Base = B->getLHS();
4091
4092 // Determine which argument is the real pointer base. It could be
4093 // the RHS argument instead of the LHS.
4094 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00004095
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004096 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004097 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004098 }
Steve Naroff61f40a22008-09-10 19:17:48 +00004099
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004100 // For conditional operators we need to see if either the LHS or RHS are
4101 // valid DeclRefExpr*s. If one of them is valid, we return it.
4102 case Stmt::ConditionalOperatorClass: {
4103 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004104
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004105 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00004106 if (Expr *lhsExpr = C->getLHS()) {
4107 // In C++, we can have a throw-expression, which has 'void' type.
4108 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004109 if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00004110 return LHS;
4111 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004112
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00004113 // In C++, we can have a throw-expression, which has 'void' type.
4114 if (C->getRHS()->getType()->isVoidType())
4115 return NULL;
4116
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004117 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004118 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004119
4120 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00004121 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004122 return E; // local block.
4123 return NULL;
4124
4125 case Stmt::AddrLabelExprClass:
4126 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00004127
John McCall80ee6e82011-11-10 05:35:25 +00004128 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004129 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4130 ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00004131
Ted Kremenek54b52742008-08-07 00:49:01 +00004132 // For casts, we need to handle conversions from arrays to
4133 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00004134 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00004135 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00004136 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8b9414e2012-02-23 23:04:32 +00004137 case Stmt::ObjCBridgedCastExprClass:
Mike Stump1eb44332009-09-09 15:08:12 +00004138 case Stmt::CXXStaticCastExprClass:
4139 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00004140 case Stmt::CXXConstCastExprClass:
4141 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8b9414e2012-02-23 23:04:32 +00004142 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4143 switch (cast<CastExpr>(E)->getCastKind()) {
4144 case CK_BitCast:
4145 case CK_LValueToRValue:
4146 case CK_NoOp:
4147 case CK_BaseToDerived:
4148 case CK_DerivedToBase:
4149 case CK_UncheckedDerivedToBase:
4150 case CK_Dynamic:
4151 case CK_CPointerToObjCPointerCast:
4152 case CK_BlockPointerToObjCPointerCast:
4153 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004154 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00004155
4156 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004157 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00004158
4159 default:
4160 return 0;
4161 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004162 }
Mike Stump1eb44332009-09-09 15:08:12 +00004163
Douglas Gregor03e80032011-06-21 17:03:29 +00004164 case Stmt::MaterializeTemporaryExprClass:
4165 if (Expr *Result = EvalAddr(
4166 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004167 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00004168 return Result;
4169
4170 return E;
4171
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004172 // Everything else: we simply don't reason about them.
4173 default:
4174 return NULL;
4175 }
Ted Kremenek06de2762007-08-17 16:46:58 +00004176}
Mike Stump1eb44332009-09-09 15:08:12 +00004177
Ted Kremenek06de2762007-08-17 16:46:58 +00004178
4179/// EvalVal - This function is complements EvalAddr in the mutual recursion.
4180/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004181static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4182 Decl *ParentDecl) {
Ted Kremenek68957a92010-08-04 20:01:07 +00004183do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00004184 // We should only be called for evaluating non-pointer expressions, or
4185 // expressions with a pointer type that are not used as references but instead
4186 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00004187
Ted Kremenek06de2762007-08-17 16:46:58 +00004188 // Our "symbolic interpreter" is just a dispatch off the currently
4189 // viewed AST node. We then recursively traverse the AST by calling
4190 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00004191
4192 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00004193 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00004194 case Stmt::ImplicitCastExprClass: {
4195 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00004196 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00004197 E = IE->getSubExpr();
4198 continue;
4199 }
4200 return NULL;
4201 }
4202
John McCall80ee6e82011-11-10 05:35:25 +00004203 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004204 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00004205
Douglas Gregora2813ce2009-10-23 18:54:35 +00004206 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004207 // When we hit a DeclRefExpr we are looking at code that refers to a
4208 // variable's name. If it's not a reference variable we check if it has
4209 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00004210 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004211
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004212 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
4213 // Check if it refers to itself, e.g. "int& i = i;".
4214 if (V == ParentDecl)
4215 return DR;
4216
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004217 if (V->hasLocalStorage()) {
4218 if (!V->getType()->isReferenceType())
4219 return DR;
4220
4221 // Reference variable, follow through to the expression that
4222 // it points to.
4223 if (V->hasInit()) {
4224 // Add the reference variable to the "trail".
4225 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004226 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004227 }
4228 }
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004229 }
Mike Stump1eb44332009-09-09 15:08:12 +00004230
Ted Kremenek06de2762007-08-17 16:46:58 +00004231 return NULL;
4232 }
Mike Stump1eb44332009-09-09 15:08:12 +00004233
Ted Kremenek06de2762007-08-17 16:46:58 +00004234 case Stmt::UnaryOperatorClass: {
4235 // The only unary operator that make sense to handle here
4236 // is Deref. All others don't resolve to a "name." This includes
4237 // handling all sorts of rvalues passed to a unary operator.
4238 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004239
John McCall2de56d12010-08-25 11:45:40 +00004240 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004241 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004242
4243 return NULL;
4244 }
Mike Stump1eb44332009-09-09 15:08:12 +00004245
Ted Kremenek06de2762007-08-17 16:46:58 +00004246 case Stmt::ArraySubscriptExprClass: {
4247 // Array subscripts are potential references to data on the stack. We
4248 // retrieve the DeclRefExpr* for the array variable if it indeed
4249 // has local storage.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004250 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004251 }
Mike Stump1eb44332009-09-09 15:08:12 +00004252
Ted Kremenek06de2762007-08-17 16:46:58 +00004253 case Stmt::ConditionalOperatorClass: {
4254 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004255 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00004256 ConditionalOperator *C = cast<ConditionalOperator>(E);
4257
Anders Carlsson39073232007-11-30 19:04:31 +00004258 // Handle the GNU extension for missing LHS.
4259 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004260 if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl))
Anders Carlsson39073232007-11-30 19:04:31 +00004261 return LHS;
4262
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004263 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004264 }
Mike Stump1eb44332009-09-09 15:08:12 +00004265
Ted Kremenek06de2762007-08-17 16:46:58 +00004266 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00004267 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00004268 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004269
Ted Kremenek06de2762007-08-17 16:46:58 +00004270 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00004271 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00004272 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00004273
4274 // Check whether the member type is itself a reference, in which case
4275 // we're not going to refer to the member, but to what the member refers to.
4276 if (M->getMemberDecl()->getType()->isReferenceType())
4277 return NULL;
4278
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004279 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004280 }
Mike Stump1eb44332009-09-09 15:08:12 +00004281
Douglas Gregor03e80032011-06-21 17:03:29 +00004282 case Stmt::MaterializeTemporaryExprClass:
4283 if (Expr *Result = EvalVal(
4284 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004285 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00004286 return Result;
4287
4288 return E;
4289
Ted Kremenek06de2762007-08-17 16:46:58 +00004290 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004291 // Check that we don't return or take the address of a reference to a
4292 // temporary. This is only useful in C++.
4293 if (!E->isTypeDependent() && E->isRValue())
4294 return E;
4295
4296 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00004297 return NULL;
4298 }
Ted Kremenek68957a92010-08-04 20:01:07 +00004299} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00004300}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004301
4302//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
4303
4304/// Check for comparisons of floating point operands using != and ==.
4305/// Issue a warning if these are no self-comparisons, as they are not likely
4306/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00004307void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieudd225092011-09-15 21:56:47 +00004308 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
4309 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004310
4311 // Special case: check for x == x (which is OK).
4312 // Do not emit warnings for such cases.
4313 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
4314 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
4315 if (DRL->getDecl() == DRR->getDecl())
David Blaikie980343b2012-07-16 20:47:22 +00004316 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004317
4318
Ted Kremenek1b500bb2007-11-29 00:59:04 +00004319 // Special case: check for comparisons against literals that can be exactly
4320 // represented by APFloat. In such cases, do not emit a warning. This
4321 // is a heuristic: often comparison against such literals are used to
4322 // detect if a value in a variable has not changed. This clearly can
4323 // lead to false negatives.
David Blaikie980343b2012-07-16 20:47:22 +00004324 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
4325 if (FLL->isExact())
4326 return;
4327 } else
4328 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
4329 if (FLR->isExact())
4330 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004331
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004332 // Check for comparisons with builtin types.
David Blaikie980343b2012-07-16 20:47:22 +00004333 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
4334 if (CL->isBuiltinCall())
4335 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004336
David Blaikie980343b2012-07-16 20:47:22 +00004337 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
4338 if (CR->isBuiltinCall())
4339 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004340
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004341 // Emit the diagnostic.
David Blaikie980343b2012-07-16 20:47:22 +00004342 Diag(Loc, diag::warn_floatingpoint_eq)
4343 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004344}
John McCallba26e582010-01-04 23:21:16 +00004345
John McCallf2370c92010-01-06 05:24:50 +00004346//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
4347//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00004348
John McCallf2370c92010-01-06 05:24:50 +00004349namespace {
John McCallba26e582010-01-04 23:21:16 +00004350
John McCallf2370c92010-01-06 05:24:50 +00004351/// Structure recording the 'active' range of an integer-valued
4352/// expression.
4353struct IntRange {
4354 /// The number of bits active in the int.
4355 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00004356
John McCallf2370c92010-01-06 05:24:50 +00004357 /// True if the int is known not to have negative values.
4358 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00004359
John McCallf2370c92010-01-06 05:24:50 +00004360 IntRange(unsigned Width, bool NonNegative)
4361 : Width(Width), NonNegative(NonNegative)
4362 {}
John McCallba26e582010-01-04 23:21:16 +00004363
John McCall1844a6e2010-11-10 23:38:19 +00004364 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00004365 static IntRange forBoolType() {
4366 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00004367 }
4368
John McCall1844a6e2010-11-10 23:38:19 +00004369 /// Returns the range of an opaque value of the given integral type.
4370 static IntRange forValueOfType(ASTContext &C, QualType T) {
4371 return forValueOfCanonicalType(C,
4372 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00004373 }
4374
John McCall1844a6e2010-11-10 23:38:19 +00004375 /// Returns the range of an opaque value of a canonical integral type.
4376 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00004377 assert(T->isCanonicalUnqualified());
4378
4379 if (const VectorType *VT = dyn_cast<VectorType>(T))
4380 T = VT->getElementType().getTypePtr();
4381 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4382 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00004383
David Majnemerf9eaf982013-06-07 22:07:20 +00004384 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00004385 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemerf9eaf982013-06-07 22:07:20 +00004386 EnumDecl *Enum = ET->getDecl();
4387 if (!Enum->isCompleteDefinition())
4388 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall091f23f2010-11-09 22:22:12 +00004389
David Majnemerf9eaf982013-06-07 22:07:20 +00004390 unsigned NumPositive = Enum->getNumPositiveBits();
4391 unsigned NumNegative = Enum->getNumNegativeBits();
John McCall323ed742010-05-06 08:58:33 +00004392
David Majnemerf9eaf982013-06-07 22:07:20 +00004393 if (NumNegative == 0)
4394 return IntRange(NumPositive, true/*NonNegative*/);
4395 else
4396 return IntRange(std::max(NumPositive + 1, NumNegative),
4397 false/*NonNegative*/);
John McCall323ed742010-05-06 08:58:33 +00004398 }
John McCallf2370c92010-01-06 05:24:50 +00004399
4400 const BuiltinType *BT = cast<BuiltinType>(T);
4401 assert(BT->isInteger());
4402
4403 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4404 }
4405
John McCall1844a6e2010-11-10 23:38:19 +00004406 /// Returns the "target" range of a canonical integral type, i.e.
4407 /// the range of values expressible in the type.
4408 ///
4409 /// This matches forValueOfCanonicalType except that enums have the
4410 /// full range of their type, not the range of their enumerators.
4411 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4412 assert(T->isCanonicalUnqualified());
4413
4414 if (const VectorType *VT = dyn_cast<VectorType>(T))
4415 T = VT->getElementType().getTypePtr();
4416 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4417 T = CT->getElementType().getTypePtr();
4418 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00004419 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00004420
4421 const BuiltinType *BT = cast<BuiltinType>(T);
4422 assert(BT->isInteger());
4423
4424 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4425 }
4426
4427 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00004428 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00004429 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00004430 L.NonNegative && R.NonNegative);
4431 }
4432
John McCall1844a6e2010-11-10 23:38:19 +00004433 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00004434 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00004435 return IntRange(std::min(L.Width, R.Width),
4436 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00004437 }
4438};
4439
Ted Kremenek0692a192012-01-31 05:37:37 +00004440static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4441 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004442 if (value.isSigned() && value.isNegative())
4443 return IntRange(value.getMinSignedBits(), false);
4444
4445 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00004446 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004447
4448 // isNonNegative() just checks the sign bit without considering
4449 // signedness.
4450 return IntRange(value.getActiveBits(), true);
4451}
4452
Ted Kremenek0692a192012-01-31 05:37:37 +00004453static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4454 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004455 if (result.isInt())
4456 return GetValueRange(C, result.getInt(), MaxWidth);
4457
4458 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00004459 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4460 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4461 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4462 R = IntRange::join(R, El);
4463 }
John McCallf2370c92010-01-06 05:24:50 +00004464 return R;
4465 }
4466
4467 if (result.isComplexInt()) {
4468 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4469 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4470 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00004471 }
4472
4473 // This can happen with lossless casts to intptr_t of "based" lvalues.
4474 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00004475 // FIXME: The only reason we need to pass the type in here is to get
4476 // the sign right on this one case. It would be nice if APValue
4477 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00004478 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004479 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00004480}
John McCallf2370c92010-01-06 05:24:50 +00004481
Eli Friedman09bddcf2013-07-08 20:20:06 +00004482static QualType GetExprType(Expr *E) {
4483 QualType Ty = E->getType();
4484 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
4485 Ty = AtomicRHS->getValueType();
4486 return Ty;
4487}
4488
John McCallf2370c92010-01-06 05:24:50 +00004489/// Pseudo-evaluate the given integer expression, estimating the
4490/// range of values it might take.
4491///
4492/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek0692a192012-01-31 05:37:37 +00004493static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004494 E = E->IgnoreParens();
4495
4496 // Try a full evaluation first.
4497 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004498 if (E->EvaluateAsRValue(result, C))
Eli Friedman09bddcf2013-07-08 20:20:06 +00004499 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004500
4501 // I think we only want to look through implicit casts here; if the
4502 // user has an explicit widening cast, we should treat the value as
4503 // being of the new, wider type.
4504 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00004505 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00004506 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4507
Eli Friedman09bddcf2013-07-08 20:20:06 +00004508 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCallf2370c92010-01-06 05:24:50 +00004509
John McCall2de56d12010-08-25 11:45:40 +00004510 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00004511
John McCallf2370c92010-01-06 05:24:50 +00004512 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00004513 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00004514 return OutputTypeRange;
4515
4516 IntRange SubRange
4517 = GetExprRange(C, CE->getSubExpr(),
4518 std::min(MaxWidth, OutputTypeRange.Width));
4519
4520 // Bail out if the subexpr's range is as wide as the cast type.
4521 if (SubRange.Width >= OutputTypeRange.Width)
4522 return OutputTypeRange;
4523
4524 // Otherwise, we take the smaller width, and we're non-negative if
4525 // either the output type or the subexpr is.
4526 return IntRange(SubRange.Width,
4527 SubRange.NonNegative || OutputTypeRange.NonNegative);
4528 }
4529
4530 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4531 // If we can fold the condition, just take that operand.
4532 bool CondResult;
4533 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
4534 return GetExprRange(C, CondResult ? CO->getTrueExpr()
4535 : CO->getFalseExpr(),
4536 MaxWidth);
4537
4538 // Otherwise, conservatively merge.
4539 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
4540 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
4541 return IntRange::join(L, R);
4542 }
4543
4544 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4545 switch (BO->getOpcode()) {
4546
4547 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00004548 case BO_LAnd:
4549 case BO_LOr:
4550 case BO_LT:
4551 case BO_GT:
4552 case BO_LE:
4553 case BO_GE:
4554 case BO_EQ:
4555 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00004556 return IntRange::forBoolType();
4557
John McCall862ff872011-07-13 06:35:24 +00004558 // The type of the assignments is the type of the LHS, so the RHS
4559 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00004560 case BO_MulAssign:
4561 case BO_DivAssign:
4562 case BO_RemAssign:
4563 case BO_AddAssign:
4564 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00004565 case BO_XorAssign:
4566 case BO_OrAssign:
4567 // TODO: bitfields?
Eli Friedman09bddcf2013-07-08 20:20:06 +00004568 return IntRange::forValueOfType(C, GetExprType(E));
John McCallc0cd21d2010-02-23 19:22:29 +00004569
John McCall862ff872011-07-13 06:35:24 +00004570 // Simple assignments just pass through the RHS, which will have
4571 // been coerced to the LHS type.
4572 case BO_Assign:
4573 // TODO: bitfields?
4574 return GetExprRange(C, BO->getRHS(), MaxWidth);
4575
John McCallf2370c92010-01-06 05:24:50 +00004576 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004577 case BO_PtrMemD:
4578 case BO_PtrMemI:
Eli Friedman09bddcf2013-07-08 20:20:06 +00004579 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004580
John McCall60fad452010-01-06 22:07:33 +00004581 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00004582 case BO_And:
4583 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00004584 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
4585 GetExprRange(C, BO->getRHS(), MaxWidth));
4586
John McCallf2370c92010-01-06 05:24:50 +00004587 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00004588 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00004589 // ...except that we want to treat '1 << (blah)' as logically
4590 // positive. It's an important idiom.
4591 if (IntegerLiteral *I
4592 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
4593 if (I->getValue() == 1) {
Eli Friedman09bddcf2013-07-08 20:20:06 +00004594 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall3aae6092010-04-07 01:14:35 +00004595 return IntRange(R.Width, /*NonNegative*/ true);
4596 }
4597 }
4598 // fallthrough
4599
John McCall2de56d12010-08-25 11:45:40 +00004600 case BO_ShlAssign:
Eli Friedman09bddcf2013-07-08 20:20:06 +00004601 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004602
John McCall60fad452010-01-06 22:07:33 +00004603 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00004604 case BO_Shr:
4605 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00004606 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4607
4608 // If the shift amount is a positive constant, drop the width by
4609 // that much.
4610 llvm::APSInt shift;
4611 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
4612 shift.isNonNegative()) {
4613 unsigned zext = shift.getZExtValue();
4614 if (zext >= L.Width)
4615 L.Width = (L.NonNegative ? 0 : 1);
4616 else
4617 L.Width -= zext;
4618 }
4619
4620 return L;
4621 }
4622
4623 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00004624 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00004625 return GetExprRange(C, BO->getRHS(), MaxWidth);
4626
John McCall60fad452010-01-06 22:07:33 +00004627 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00004628 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00004629 if (BO->getLHS()->getType()->isPointerType())
Eli Friedman09bddcf2013-07-08 20:20:06 +00004630 return IntRange::forValueOfType(C, GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00004631 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00004632
John McCall00fe7612011-07-14 22:39:48 +00004633 // The width of a division result is mostly determined by the size
4634 // of the LHS.
4635 case BO_Div: {
4636 // Don't 'pre-truncate' the operands.
Eli Friedman09bddcf2013-07-08 20:20:06 +00004637 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00004638 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4639
4640 // If the divisor is constant, use that.
4641 llvm::APSInt divisor;
4642 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
4643 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
4644 if (log2 >= L.Width)
4645 L.Width = (L.NonNegative ? 0 : 1);
4646 else
4647 L.Width = std::min(L.Width - log2, MaxWidth);
4648 return L;
4649 }
4650
4651 // Otherwise, just use the LHS's width.
4652 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4653 return IntRange(L.Width, L.NonNegative && R.NonNegative);
4654 }
4655
4656 // The result of a remainder can't be larger than the result of
4657 // either side.
4658 case BO_Rem: {
4659 // Don't 'pre-truncate' the operands.
Eli Friedman09bddcf2013-07-08 20:20:06 +00004660 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00004661 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4662 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4663
4664 IntRange meet = IntRange::meet(L, R);
4665 meet.Width = std::min(meet.Width, MaxWidth);
4666 return meet;
4667 }
4668
4669 // The default behavior is okay for these.
4670 case BO_Mul:
4671 case BO_Add:
4672 case BO_Xor:
4673 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00004674 break;
4675 }
4676
John McCall00fe7612011-07-14 22:39:48 +00004677 // The default case is to treat the operation as if it were closed
4678 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00004679 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4680 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
4681 return IntRange::join(L, R);
4682 }
4683
4684 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
4685 switch (UO->getOpcode()) {
4686 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00004687 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00004688 return IntRange::forBoolType();
4689
4690 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004691 case UO_Deref:
4692 case UO_AddrOf: // should be impossible
Eli Friedman09bddcf2013-07-08 20:20:06 +00004693 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004694
4695 default:
4696 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
4697 }
4698 }
4699
Ted Kremenek728a1fb2013-10-14 18:55:27 +00004700 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
4701 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
4702
John McCall993f43f2013-05-06 21:39:12 +00004703 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004704 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004705 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00004706
Eli Friedman09bddcf2013-07-08 20:20:06 +00004707 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004708}
John McCall51313c32010-01-04 23:31:57 +00004709
Ted Kremenek0692a192012-01-31 05:37:37 +00004710static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedman09bddcf2013-07-08 20:20:06 +00004711 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCall323ed742010-05-06 08:58:33 +00004712}
4713
John McCall51313c32010-01-04 23:31:57 +00004714/// Checks whether the given value, which currently has the given
4715/// source semantics, has the same value when coerced through the
4716/// target semantics.
Ted Kremenek0692a192012-01-31 05:37:37 +00004717static bool IsSameFloatAfterCast(const llvm::APFloat &value,
4718 const llvm::fltSemantics &Src,
4719 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004720 llvm::APFloat truncated = value;
4721
4722 bool ignored;
4723 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
4724 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
4725
4726 return truncated.bitwiseIsEqual(value);
4727}
4728
4729/// Checks whether the given value, which currently has the given
4730/// source semantics, has the same value when coerced through the
4731/// target semantics.
4732///
4733/// The value might be a vector of floats (or a complex number).
Ted Kremenek0692a192012-01-31 05:37:37 +00004734static bool IsSameFloatAfterCast(const APValue &value,
4735 const llvm::fltSemantics &Src,
4736 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004737 if (value.isFloat())
4738 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
4739
4740 if (value.isVector()) {
4741 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
4742 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
4743 return false;
4744 return true;
4745 }
4746
4747 assert(value.isComplexFloat());
4748 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
4749 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
4750}
4751
Ted Kremenek0692a192012-01-31 05:37:37 +00004752static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00004753
Ted Kremeneke3b159c2010-09-23 21:43:44 +00004754static bool IsZero(Sema &S, Expr *E) {
4755 // Suppress cases where we are comparing against an enum constant.
4756 if (const DeclRefExpr *DR =
4757 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
4758 if (isa<EnumConstantDecl>(DR->getDecl()))
4759 return false;
4760
4761 // Suppress cases where the '0' value is expanded from a macro.
4762 if (E->getLocStart().isMacroID())
4763 return false;
4764
John McCall323ed742010-05-06 08:58:33 +00004765 llvm::APSInt Value;
4766 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
4767}
4768
John McCall372e1032010-10-06 00:25:24 +00004769static bool HasEnumType(Expr *E) {
4770 // Strip off implicit integral promotions.
4771 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004772 if (ICE->getCastKind() != CK_IntegralCast &&
4773 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00004774 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004775 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00004776 }
4777
4778 return E->getType()->isEnumeralType();
4779}
4780
Ted Kremenek0692a192012-01-31 05:37:37 +00004781static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieucbc19872013-11-01 21:47:19 +00004782 // Disable warning in template instantiations.
4783 if (!S.ActiveTemplateInstantiations.empty())
4784 return;
4785
John McCall2de56d12010-08-25 11:45:40 +00004786 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00004787 if (E->isValueDependent())
4788 return;
4789
John McCall2de56d12010-08-25 11:45:40 +00004790 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004791 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004792 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004793 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004794 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004795 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004796 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004797 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004798 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004799 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004800 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004801 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004802 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004803 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004804 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004805 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4806 }
4807}
4808
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004809static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004810 Expr *Constant, Expr *Other,
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004811 llvm::APSInt Value,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004812 bool RhsConstant) {
Richard Trieu311cb2b2013-11-01 21:19:43 +00004813 // Disable warning in template instantiations.
4814 if (!S.ActiveTemplateInstantiations.empty())
4815 return;
4816
Richard Trieu526e6272012-11-14 22:50:24 +00004817 // 0 values are handled later by CheckTrivialUnsignedComparison().
4818 if (Value == 0)
4819 return;
4820
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004821 BinaryOperatorKind op = E->getOpcode();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004822 QualType OtherT = Other->getType();
4823 QualType ConstantT = Constant->getType();
Richard Trieu526e6272012-11-14 22:50:24 +00004824 QualType CommonT = E->getLHS()->getType();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004825 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004826 return;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004827 assert((OtherT->isIntegerType() && ConstantT->isIntegerType())
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004828 && "comparison with non-integer type");
Richard Trieu526e6272012-11-14 22:50:24 +00004829
4830 bool ConstantSigned = ConstantT->isSignedIntegerType();
Richard Trieu526e6272012-11-14 22:50:24 +00004831 bool CommonSigned = CommonT->isSignedIntegerType();
4832
4833 bool EqualityOnly = false;
4834
4835 // TODO: Investigate using GetExprRange() to get tighter bounds on
4836 // on the bit ranges.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004837 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
Richard Trieu526e6272012-11-14 22:50:24 +00004838 unsigned OtherWidth = OtherRange.Width;
4839
4840 if (CommonSigned) {
4841 // The common type is signed, therefore no signed to unsigned conversion.
Eli Friedmand87de7b2012-11-30 23:09:29 +00004842 if (!OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00004843 // Check that the constant is representable in type OtherT.
4844 if (ConstantSigned) {
4845 if (OtherWidth >= Value.getMinSignedBits())
4846 return;
4847 } else { // !ConstantSigned
4848 if (OtherWidth >= Value.getActiveBits() + 1)
4849 return;
4850 }
4851 } else { // !OtherSigned
4852 // Check that the constant is representable in type OtherT.
4853 // Negative values are out of range.
4854 if (ConstantSigned) {
4855 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
4856 return;
4857 } else { // !ConstantSigned
4858 if (OtherWidth >= Value.getActiveBits())
4859 return;
4860 }
4861 }
4862 } else { // !CommonSigned
Eli Friedmand87de7b2012-11-30 23:09:29 +00004863 if (OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00004864 if (OtherWidth >= Value.getActiveBits())
4865 return;
Eli Friedmand87de7b2012-11-30 23:09:29 +00004866 } else if (!OtherRange.NonNegative && !ConstantSigned) {
Richard Trieu526e6272012-11-14 22:50:24 +00004867 // Check to see if the constant is representable in OtherT.
4868 if (OtherWidth > Value.getActiveBits())
4869 return;
4870 // Check to see if the constant is equivalent to a negative value
4871 // cast to CommonT.
4872 if (S.Context.getIntWidth(ConstantT) == S.Context.getIntWidth(CommonT) &&
Richard Trieu5d1cf4f2012-11-15 03:43:50 +00004873 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
Richard Trieu526e6272012-11-14 22:50:24 +00004874 return;
4875 // The constant value rests between values that OtherT can represent after
4876 // conversion. Relational comparison still works, but equality
4877 // comparisons will be tautological.
4878 EqualityOnly = true;
4879 } else { // OtherSigned && ConstantSigned
4880 assert(0 && "Two signed types converted to unsigned types.");
4881 }
4882 }
4883
4884 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
4885
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004886 bool IsTrue = true;
Richard Trieu526e6272012-11-14 22:50:24 +00004887 if (op == BO_EQ || op == BO_NE) {
4888 IsTrue = op == BO_NE;
4889 } else if (EqualityOnly) {
4890 return;
4891 } else if (RhsConstant) {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004892 if (op == BO_GT || op == BO_GE)
Richard Trieu526e6272012-11-14 22:50:24 +00004893 IsTrue = !PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004894 else // op == BO_LT || op == BO_LE
Richard Trieu526e6272012-11-14 22:50:24 +00004895 IsTrue = PositiveConstant;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004896 } else {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004897 if (op == BO_LT || op == BO_LE)
Richard Trieu526e6272012-11-14 22:50:24 +00004898 IsTrue = !PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004899 else // op == BO_GT || op == BO_GE
Richard Trieu526e6272012-11-14 22:50:24 +00004900 IsTrue = PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004901 }
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004902
4903 // If this is a comparison to an enum constant, include that
4904 // constant in the diagnostic.
4905 const EnumConstantDecl *ED = 0;
4906 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
4907 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
4908
4909 SmallString<64> PrettySourceValue;
4910 llvm::raw_svector_ostream OS(PrettySourceValue);
4911 if (ED)
Ted Kremenek9de50942013-03-15 22:02:46 +00004912 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004913 else
4914 OS << Value;
4915
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004916 S.Diag(E->getOperatorLoc(), diag::warn_out_of_range_compare)
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004917 << OS.str() << OtherT << IsTrue
Richard Trieu526e6272012-11-14 22:50:24 +00004918 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004919}
4920
John McCall323ed742010-05-06 08:58:33 +00004921/// Analyze the operands of the given comparison. Implements the
4922/// fallback case from AnalyzeComparison.
Ted Kremenek0692a192012-01-31 05:37:37 +00004923static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00004924 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4925 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00004926}
John McCall51313c32010-01-04 23:31:57 +00004927
John McCallba26e582010-01-04 23:21:16 +00004928/// \brief Implements -Wsign-compare.
4929///
Richard Trieudd225092011-09-15 21:56:47 +00004930/// \param E the binary operator to check for warnings
Ted Kremenek0692a192012-01-31 05:37:37 +00004931static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCall323ed742010-05-06 08:58:33 +00004932 // The type the comparison is being performed in.
4933 QualType T = E->getLHS()->getType();
4934 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
4935 && "comparison with mismatched types");
Fariborz Jahanianab4702f2012-09-18 17:46:26 +00004936 if (E->isValueDependent())
4937 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004938
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004939 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
4940 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004941
4942 bool IsComparisonConstant = false;
4943
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004944 // Check whether an integer constant comparison results in a value
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004945 // of 'true' or 'false'.
4946 if (T->isIntegralType(S.Context)) {
4947 llvm::APSInt RHSValue;
4948 bool IsRHSIntegralLiteral =
4949 RHS->isIntegerConstantExpr(RHSValue, S.Context);
4950 llvm::APSInt LHSValue;
4951 bool IsLHSIntegralLiteral =
4952 LHS->isIntegerConstantExpr(LHSValue, S.Context);
4953 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
4954 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
4955 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
4956 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
4957 else
4958 IsComparisonConstant =
4959 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004960 } else if (!T->hasUnsignedIntegerRepresentation())
4961 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004962
John McCall323ed742010-05-06 08:58:33 +00004963 // We don't do anything special if this isn't an unsigned integral
4964 // comparison: we're only interested in integral comparisons, and
4965 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00004966 //
4967 // We also don't care about value-dependent expressions or expressions
4968 // whose result is a constant.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004969 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCall323ed742010-05-06 08:58:33 +00004970 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004971
John McCall323ed742010-05-06 08:58:33 +00004972 // Check to see if one of the (unmodified) operands is of different
4973 // signedness.
4974 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00004975 if (LHS->getType()->hasSignedIntegerRepresentation()) {
4976 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00004977 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00004978 signedOperand = LHS;
4979 unsignedOperand = RHS;
4980 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
4981 signedOperand = RHS;
4982 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00004983 } else {
John McCall323ed742010-05-06 08:58:33 +00004984 CheckTrivialUnsignedComparison(S, E);
4985 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004986 }
4987
John McCall323ed742010-05-06 08:58:33 +00004988 // Otherwise, calculate the effective range of the signed operand.
4989 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00004990
John McCall323ed742010-05-06 08:58:33 +00004991 // Go ahead and analyze implicit conversions in the operands. Note
4992 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00004993 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
4994 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00004995
John McCall323ed742010-05-06 08:58:33 +00004996 // If the signed range is non-negative, -Wsign-compare won't fire,
4997 // but we should still check for comparisons which are always true
4998 // or false.
4999 if (signedRange.NonNegative)
5000 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00005001
5002 // For (in)equality comparisons, if the unsigned operand is a
5003 // constant which cannot collide with a overflowed signed operand,
5004 // then reinterpreting the signed operand as unsigned will not
5005 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00005006 if (E->isEqualityOp()) {
5007 unsigned comparisonWidth = S.Context.getIntWidth(T);
5008 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00005009
John McCall323ed742010-05-06 08:58:33 +00005010 // We should never be unable to prove that the unsigned operand is
5011 // non-negative.
5012 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
5013
5014 if (unsignedRange.Width < comparisonWidth)
5015 return;
5016 }
5017
Douglas Gregor6d3b93d2012-05-01 01:53:49 +00005018 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5019 S.PDiag(diag::warn_mixed_sign_comparison)
5020 << LHS->getType() << RHS->getType()
5021 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallba26e582010-01-04 23:21:16 +00005022}
5023
John McCall15d7d122010-11-11 03:21:53 +00005024/// Analyzes an attempt to assign the given value to a bitfield.
5025///
5026/// Returns true if there was something fishy about the attempt.
Ted Kremenek0692a192012-01-31 05:37:37 +00005027static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
5028 SourceLocation InitLoc) {
John McCall15d7d122010-11-11 03:21:53 +00005029 assert(Bitfield->isBitField());
5030 if (Bitfield->isInvalidDecl())
5031 return false;
5032
John McCall91b60142010-11-11 05:33:51 +00005033 // White-list bool bitfields.
5034 if (Bitfield->getType()->isBooleanType())
5035 return false;
5036
Douglas Gregor46ff3032011-02-04 13:09:01 +00005037 // Ignore value- or type-dependent expressions.
5038 if (Bitfield->getBitWidth()->isValueDependent() ||
5039 Bitfield->getBitWidth()->isTypeDependent() ||
5040 Init->isValueDependent() ||
5041 Init->isTypeDependent())
5042 return false;
5043
John McCall15d7d122010-11-11 03:21:53 +00005044 Expr *OriginalInit = Init->IgnoreParenImpCasts();
5045
Richard Smith80d4b552011-12-28 19:48:30 +00005046 llvm::APSInt Value;
5047 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00005048 return false;
5049
John McCall15d7d122010-11-11 03:21:53 +00005050 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005051 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00005052
5053 if (OriginalWidth <= FieldWidth)
5054 return false;
5055
Eli Friedman3a643af2012-01-26 23:11:39 +00005056 // Compute the value which the bitfield will contain.
Jay Foad9f71a8f2010-12-07 08:25:34 +00005057 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedman3a643af2012-01-26 23:11:39 +00005058 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall15d7d122010-11-11 03:21:53 +00005059
Eli Friedman3a643af2012-01-26 23:11:39 +00005060 // Check whether the stored value is equal to the original value.
5061 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieue1ecdc12012-07-23 20:21:35 +00005062 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall15d7d122010-11-11 03:21:53 +00005063 return false;
5064
Eli Friedman3a643af2012-01-26 23:11:39 +00005065 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedman34ff0622012-02-02 00:40:20 +00005066 // therefore don't strictly fit into a signed bitfield of width 1.
5067 if (FieldWidth == 1 && Value == 1)
Eli Friedman3a643af2012-01-26 23:11:39 +00005068 return false;
5069
John McCall15d7d122010-11-11 03:21:53 +00005070 std::string PrettyValue = Value.toString(10);
5071 std::string PrettyTrunc = TruncatedValue.toString(10);
5072
5073 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
5074 << PrettyValue << PrettyTrunc << OriginalInit->getType()
5075 << Init->getSourceRange();
5076
5077 return true;
5078}
5079
John McCallbeb22aa2010-11-09 23:24:47 +00005080/// Analyze the given simple or compound assignment for warning-worthy
5081/// operations.
Ted Kremenek0692a192012-01-31 05:37:37 +00005082static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCallbeb22aa2010-11-09 23:24:47 +00005083 // Just recurse on the LHS.
5084 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5085
5086 // We want to recurse on the RHS as normal unless we're assigning to
5087 // a bitfield.
John McCall993f43f2013-05-06 21:39:12 +00005088 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005089 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall15d7d122010-11-11 03:21:53 +00005090 E->getOperatorLoc())) {
5091 // Recurse, ignoring any implicit conversions on the RHS.
5092 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
5093 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00005094 }
5095 }
5096
5097 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
5098}
5099
John McCall51313c32010-01-04 23:31:57 +00005100/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00005101static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00005102 SourceLocation CContext, unsigned diag,
5103 bool pruneControlFlow = false) {
5104 if (pruneControlFlow) {
5105 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5106 S.PDiag(diag)
5107 << SourceType << T << E->getSourceRange()
5108 << SourceRange(CContext));
5109 return;
5110 }
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005111 S.Diag(E->getExprLoc(), diag)
5112 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
5113}
5114
Chandler Carruthe1b02e02011-04-05 06:47:57 +00005115/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00005116static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00005117 SourceLocation CContext, unsigned diag,
5118 bool pruneControlFlow = false) {
5119 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruthe1b02e02011-04-05 06:47:57 +00005120}
5121
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005122/// Diagnose an implicit cast from a literal expression. Does not warn when the
5123/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00005124void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
5125 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005126 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00005127 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005128 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00005129 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
5130 T->hasUnsignedIntegerRepresentation());
5131 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00005132 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005133 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00005134 return;
5135
Eli Friedman4e1a82c2013-08-29 23:44:43 +00005136 // FIXME: Force the precision of the source value down so we don't print
5137 // digits which are usually useless (we don't really care here if we
5138 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
5139 // would automatically print the shortest representation, but it's a bit
5140 // tricky to implement.
David Blaikiebe0ee872012-05-15 16:56:36 +00005141 SmallString<16> PrettySourceValue;
Eli Friedman4e1a82c2013-08-29 23:44:43 +00005142 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
5143 precision = (precision * 59 + 195) / 196;
5144 Value.toString(PrettySourceValue, precision);
5145
David Blaikiede7e7b82012-05-15 17:18:27 +00005146 SmallString<16> PrettyTargetValue;
David Blaikiebe0ee872012-05-15 16:56:36 +00005147 if (T->isSpecificBuiltinType(BuiltinType::Bool))
5148 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
5149 else
David Blaikiede7e7b82012-05-15 17:18:27 +00005150 IntegerValue.toString(PrettyTargetValue);
David Blaikiebe0ee872012-05-15 16:56:36 +00005151
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005152 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikiebe0ee872012-05-15 16:56:36 +00005153 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
5154 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00005155}
5156
John McCall091f23f2010-11-09 22:22:12 +00005157std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
5158 if (!Range.Width) return "0";
5159
5160 llvm::APSInt ValueInRange = Value;
5161 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00005162 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00005163 return ValueInRange.toString(10);
5164}
5165
Hans Wennborg88617a22012-08-28 15:44:30 +00005166static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
5167 if (!isa<ImplicitCastExpr>(Ex))
5168 return false;
5169
5170 Expr *InnerE = Ex->IgnoreParenImpCasts();
5171 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
5172 const Type *Source =
5173 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5174 if (Target->isDependentType())
5175 return false;
5176
5177 const BuiltinType *FloatCandidateBT =
5178 dyn_cast<BuiltinType>(ToBool ? Source : Target);
5179 const Type *BoolCandidateType = ToBool ? Target : Source;
5180
5181 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
5182 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
5183}
5184
5185void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
5186 SourceLocation CC) {
5187 unsigned NumArgs = TheCall->getNumArgs();
5188 for (unsigned i = 0; i < NumArgs; ++i) {
5189 Expr *CurrA = TheCall->getArg(i);
5190 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
5191 continue;
5192
5193 bool IsSwapped = ((i > 0) &&
5194 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
5195 IsSwapped |= ((i < (NumArgs - 1)) &&
5196 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
5197 if (IsSwapped) {
5198 // Warn on this floating-point to bool conversion.
5199 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
5200 CurrA->getType(), CC,
5201 diag::warn_impcast_floating_point_to_bool);
5202 }
5203 }
5204}
5205
John McCall323ed742010-05-06 08:58:33 +00005206void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005207 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00005208 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00005209
John McCall323ed742010-05-06 08:58:33 +00005210 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
5211 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
5212 if (Source == Target) return;
5213 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00005214
Chandler Carruth108f7562011-07-26 05:40:03 +00005215 // If the conversion context location is invalid don't complain. We also
5216 // don't want to emit a warning if the issue occurs from the expansion of
5217 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
5218 // delay this check as long as possible. Once we detect we are in that
5219 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00005220 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00005221 return;
5222
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005223 // Diagnose implicit casts to bool.
5224 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
5225 if (isa<StringLiteral>(E))
5226 // Warn on string literal to bool. Checks for string literals in logical
5227 // expressions, for instances, assert(0 && "error here"), is prevented
5228 // by a check in AnalyzeImplicitConversions().
5229 return DiagnoseImpCast(S, E, T, CC,
5230 diag::warn_impcast_string_literal_to_bool);
Lang Hamese14ca9f2011-12-05 20:49:50 +00005231 if (Source->isFunctionType()) {
5232 // Warn on function to bool. Checks free functions and static member
5233 // functions. Weakly imported functions are excluded from the check,
5234 // since it's common to test their value to check whether the linker
5235 // found a definition for them.
5236 ValueDecl *D = 0;
5237 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
5238 D = R->getDecl();
5239 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
5240 D = M->getMemberDecl();
5241 }
5242
5243 if (D && !D->isWeak()) {
Richard Trieu26b45d82011-12-06 04:48:01 +00005244 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
5245 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
5246 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie2def7732011-12-09 21:42:37 +00005247 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
5248 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
5249 QualType ReturnType;
5250 UnresolvedSet<4> NonTemplateOverloads;
David Blaikiec8fa5252013-06-21 23:54:45 +00005251 S.tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
David Blaikie2def7732011-12-09 21:42:37 +00005252 if (!ReturnType.isNull()
5253 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
5254 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
5255 << FixItHint::CreateInsertion(
5256 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu26b45d82011-12-06 04:48:01 +00005257 return;
5258 }
Lang Hamese14ca9f2011-12-05 20:49:50 +00005259 }
5260 }
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005261 }
John McCall51313c32010-01-04 23:31:57 +00005262
5263 // Strip vector types.
5264 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00005265 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005266 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005267 return;
John McCallb4eb64d2010-10-08 02:01:28 +00005268 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005269 }
Chris Lattnerb792b302011-06-14 04:51:15 +00005270
5271 // If the vector cast is cast between two vectors of the same size, it is
5272 // a bitcast, not a conversion.
5273 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
5274 return;
John McCall51313c32010-01-04 23:31:57 +00005275
5276 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
5277 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
5278 }
5279
5280 // Strip complex types.
5281 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00005282 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005283 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005284 return;
5285
John McCallb4eb64d2010-10-08 02:01:28 +00005286 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005287 }
John McCall51313c32010-01-04 23:31:57 +00005288
5289 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
5290 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
5291 }
5292
5293 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
5294 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
5295
5296 // If the source is floating point...
5297 if (SourceBT && SourceBT->isFloatingPoint()) {
5298 // ...and the target is floating point...
5299 if (TargetBT && TargetBT->isFloatingPoint()) {
5300 // ...then warn if we're dropping FP rank.
5301
5302 // Builtin FP kinds are ordered by increasing FP rank.
5303 if (SourceBT->getKind() > TargetBT->getKind()) {
5304 // Don't warn about float constants that are precisely
5305 // representable in the target type.
5306 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00005307 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00005308 // Value might be a float, a float vector, or a float complex.
5309 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00005310 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
5311 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00005312 return;
5313 }
5314
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005315 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005316 return;
5317
John McCallb4eb64d2010-10-08 02:01:28 +00005318 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00005319 }
5320 return;
5321 }
5322
Ted Kremenekef9ff882011-03-10 20:03:42 +00005323 // If the target is integral, always warn.
David Blaikiebe0ee872012-05-15 16:56:36 +00005324 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005325 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005326 return;
5327
Chandler Carrutha5b93322011-02-17 11:05:49 +00005328 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00005329 // We also want to warn on, e.g., "int i = -1.234"
5330 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
5331 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
5332 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
5333
Chandler Carruthf65076e2011-04-10 08:36:24 +00005334 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
5335 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00005336 } else {
5337 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
5338 }
5339 }
John McCall51313c32010-01-04 23:31:57 +00005340
Hans Wennborg88617a22012-08-28 15:44:30 +00005341 // If the target is bool, warn if expr is a function or method call.
5342 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
5343 isa<CallExpr>(E)) {
5344 // Check last argument of function call to see if it is an
5345 // implicit cast from a type matching the type the result
5346 // is being cast to.
5347 CallExpr *CEx = cast<CallExpr>(E);
5348 unsigned NumArgs = CEx->getNumArgs();
5349 if (NumArgs > 0) {
5350 Expr *LastA = CEx->getArg(NumArgs - 1);
5351 Expr *InnerE = LastA->IgnoreParenImpCasts();
5352 const Type *InnerType =
5353 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5354 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
5355 // Warn on this floating-point to bool conversion
5356 DiagnoseImpCast(S, E, T, CC,
5357 diag::warn_impcast_floating_point_to_bool);
5358 }
5359 }
5360 }
John McCall51313c32010-01-04 23:31:57 +00005361 return;
5362 }
5363
Richard Trieu1838ca52011-05-29 19:59:02 +00005364 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikieb26331b2012-06-19 21:19:06 +00005365 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiee81b43b2012-11-08 00:41:20 +00005366 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikie896c7dd2013-02-16 00:56:22 +00005367 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieb1360492012-03-16 20:30:12 +00005368 SourceLocation Loc = E->getSourceRange().getBegin();
5369 if (Loc.isMacroID())
5370 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie9fb1ac52012-05-15 21:57:38 +00005371 if (!Loc.isMacroID() || CC.isMacroID())
5372 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
5373 << T << clang::SourceRange(CC)
Richard Smith8adf8372013-09-20 00:27:40 +00005374 << FixItHint::CreateReplacement(Loc,
5375 S.getFixItZeroLiteralForType(T, Loc));
Richard Trieu1838ca52011-05-29 19:59:02 +00005376 }
5377
David Blaikieb26331b2012-06-19 21:19:06 +00005378 if (!Source->isIntegerType() || !Target->isIntegerType())
5379 return;
5380
David Blaikiebe0ee872012-05-15 16:56:36 +00005381 // TODO: remove this early return once the false positives for constant->bool
5382 // in templates, macros, etc, are reduced or removed.
5383 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
5384 return;
5385
John McCall323ed742010-05-06 08:58:33 +00005386 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00005387 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00005388
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005389 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer25ffbef2013-03-28 19:07:11 +00005390 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005391 // TODO: this should happen for bitfield stores, too.
5392 llvm::APSInt Value(32);
5393 if (E->isIntegerConstantExpr(Value, S.Context)) {
5394 if (S.SourceMgr.isInSystemMacro(CC))
5395 return;
5396
John McCall091f23f2010-11-09 22:22:12 +00005397 std::string PrettySourceValue = Value.toString(10);
5398 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005399
Ted Kremenek5e745da2011-10-22 02:37:33 +00005400 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5401 S.PDiag(diag::warn_impcast_integer_precision_constant)
5402 << PrettySourceValue << PrettyTargetValue
5403 << E->getType() << T << E->getSourceRange()
5404 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00005405 return;
5406 }
5407
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005408 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
5409 if (S.SourceMgr.isInSystemMacro(CC))
5410 return;
5411
David Blaikie37050842012-04-12 22:40:54 +00005412 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaksc36bedc2012-02-01 19:08:57 +00005413 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
5414 /* pruneControlFlow */ true);
John McCallb4eb64d2010-10-08 02:01:28 +00005415 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00005416 }
5417
5418 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
5419 (!TargetRange.NonNegative && SourceRange.NonNegative &&
5420 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00005421
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005422 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005423 return;
5424
John McCall323ed742010-05-06 08:58:33 +00005425 unsigned DiagID = diag::warn_impcast_integer_sign;
5426
5427 // Traditionally, gcc has warned about this under -Wsign-compare.
5428 // We also want to warn about it in -Wconversion.
5429 // So if -Wconversion is off, use a completely identical diagnostic
5430 // in the sign-compare group.
5431 // The conditional-checking code will
5432 if (ICContext) {
5433 DiagID = diag::warn_impcast_integer_sign_conditional;
5434 *ICContext = true;
5435 }
5436
John McCallb4eb64d2010-10-08 02:01:28 +00005437 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00005438 }
5439
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005440 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005441 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
5442 // type, to give us better diagnostics.
5443 QualType SourceType = E->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +00005444 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005445 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5446 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
5447 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
5448 SourceType = S.Context.getTypeDeclType(Enum);
5449 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
5450 }
5451 }
5452
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005453 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
5454 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall83972f12013-03-09 00:54:27 +00005455 if (SourceEnum->getDecl()->hasNameForLinkage() &&
5456 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00005457 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005458 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005459 return;
5460
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005461 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005462 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005463 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005464
John McCall51313c32010-01-04 23:31:57 +00005465 return;
5466}
5467
David Blaikie9fb1ac52012-05-15 21:57:38 +00005468void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5469 SourceLocation CC, QualType T);
John McCall323ed742010-05-06 08:58:33 +00005470
5471void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00005472 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00005473 E = E->IgnoreParenImpCasts();
5474
5475 if (isa<ConditionalOperator>(E))
David Blaikie9fb1ac52012-05-15 21:57:38 +00005476 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCall323ed742010-05-06 08:58:33 +00005477
John McCallb4eb64d2010-10-08 02:01:28 +00005478 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005479 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00005480 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00005481 return;
5482}
5483
David Blaikie9fb1ac52012-05-15 21:57:38 +00005484void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5485 SourceLocation CC, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00005486 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00005487
5488 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00005489 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
5490 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00005491
5492 // If -Wconversion would have warned about either of the candidates
5493 // for a signedness conversion to the context type...
5494 if (!Suspicious) return;
5495
5496 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005497 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
5498 CC))
John McCall323ed742010-05-06 08:58:33 +00005499 return;
5500
John McCall323ed742010-05-06 08:58:33 +00005501 // ...then check whether it would have warned about either of the
5502 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00005503 if (E->getType() == T) return;
5504
5505 Suspicious = false;
5506 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
5507 E->getType(), CC, &Suspicious);
5508 if (!Suspicious)
5509 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00005510 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00005511}
5512
5513/// AnalyzeImplicitConversions - Find and report any interesting
5514/// implicit conversions in the given expression. There are a couple
5515/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00005516void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00005517 QualType T = OrigE->getType();
5518 Expr *E = OrigE->IgnoreParenImpCasts();
5519
Douglas Gregorf8b6e152011-10-10 17:38:18 +00005520 if (E->isTypeDependent() || E->isValueDependent())
5521 return;
5522
John McCall323ed742010-05-06 08:58:33 +00005523 // For conditional operators, we analyze the arguments as if they
5524 // were being fed directly into the output.
5525 if (isa<ConditionalOperator>(E)) {
5526 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie9fb1ac52012-05-15 21:57:38 +00005527 CheckConditionalOperator(S, CO, CC, T);
John McCall323ed742010-05-06 08:58:33 +00005528 return;
5529 }
5530
Hans Wennborg88617a22012-08-28 15:44:30 +00005531 // Check implicit argument conversions for function calls.
5532 if (CallExpr *Call = dyn_cast<CallExpr>(E))
5533 CheckImplicitArgumentConversions(S, Call, CC);
5534
John McCall323ed742010-05-06 08:58:33 +00005535 // Go ahead and check any implicit conversions we might have skipped.
5536 // The non-canonical typecheck is just an optimization;
5537 // CheckImplicitConversion will filter out dead implicit conversions.
5538 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00005539 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00005540
5541 // Now continue drilling into this expression.
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00005542
5543 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00005544 if (POE->getResultExpr())
5545 E = POE->getResultExpr();
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00005546 }
5547
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00005548 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5549 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
5550
John McCall323ed742010-05-06 08:58:33 +00005551 // Skip past explicit casts.
5552 if (isa<ExplicitCastExpr>(E)) {
5553 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00005554 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005555 }
5556
John McCallbeb22aa2010-11-09 23:24:47 +00005557 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5558 // Do a somewhat different check with comparison operators.
5559 if (BO->isComparisonOp())
5560 return AnalyzeComparison(S, BO);
5561
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005562 // And with simple assignments.
5563 if (BO->getOpcode() == BO_Assign)
John McCallbeb22aa2010-11-09 23:24:47 +00005564 return AnalyzeAssignment(S, BO);
5565 }
John McCall323ed742010-05-06 08:58:33 +00005566
5567 // These break the otherwise-useful invariant below. Fortunately,
5568 // we don't really need to recurse into them, because any internal
5569 // expressions should have been analyzed already when they were
5570 // built into statements.
5571 if (isa<StmtExpr>(E)) return;
5572
5573 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005574 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00005575
5576 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00005577 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005578 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
5579 bool IsLogicalOperator = BO && BO->isLogicalOp();
5580 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor54042f12012-02-09 10:18:50 +00005581 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor503384f2012-02-09 00:47:04 +00005582 if (!ChildExpr)
5583 continue;
5584
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005585 if (IsLogicalOperator &&
5586 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
5587 // Ignore checking string literals that are in logical operators.
5588 continue;
5589 AnalyzeImplicitConversions(S, ChildExpr, CC);
5590 }
John McCall323ed742010-05-06 08:58:33 +00005591}
5592
5593} // end anonymous namespace
5594
5595/// Diagnoses "dangerous" implicit conversions within the given
5596/// expression (which is a full expression). Implements -Wconversion
5597/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00005598///
5599/// \param CC the "context" location of the implicit conversion, i.e.
5600/// the most location of the syntactic entity requiring the implicit
5601/// conversion
5602void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00005603 // Don't diagnose in unevaluated contexts.
David Blaikie71f55f72012-08-06 22:47:24 +00005604 if (isUnevaluatedContext())
John McCall323ed742010-05-06 08:58:33 +00005605 return;
5606
5607 // Don't diagnose for value- or type-dependent expressions.
5608 if (E->isTypeDependent() || E->isValueDependent())
5609 return;
5610
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005611 // Check for array bounds violations in cases where the check isn't triggered
5612 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
5613 // ArraySubscriptExpr is on the RHS of a variable initialization.
5614 CheckArrayAccess(E);
5615
John McCallb4eb64d2010-10-08 02:01:28 +00005616 // This is not the right CC for (e.g.) a variable initialization.
5617 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005618}
5619
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005620/// Diagnose when expression is an integer constant expression and its evaluation
5621/// results in integer overflow
5622void Sema::CheckForIntOverflow (Expr *E) {
Richard Smith00043292013-11-05 22:23:30 +00005623 if (isa<BinaryOperator>(E->IgnoreParens()))
5624 E->EvaluateForOverflow(Context);
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005625}
5626
Richard Smith6c3af3d2013-01-17 01:17:56 +00005627namespace {
5628/// \brief Visitor for expressions which looks for unsequenced operations on the
5629/// same object.
5630class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smith0c0b3902013-06-30 10:40:20 +00005631 typedef EvaluatedExprVisitor<SequenceChecker> Base;
5632
Richard Smith6c3af3d2013-01-17 01:17:56 +00005633 /// \brief A tree of sequenced regions within an expression. Two regions are
5634 /// unsequenced if one is an ancestor or a descendent of the other. When we
5635 /// finish processing an expression with sequencing, such as a comma
5636 /// expression, we fold its tree nodes into its parent, since they are
5637 /// unsequenced with respect to nodes we will visit later.
5638 class SequenceTree {
5639 struct Value {
5640 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
5641 unsigned Parent : 31;
5642 bool Merged : 1;
5643 };
Robert Wilhelme7205c02013-08-10 12:33:24 +00005644 SmallVector<Value, 8> Values;
Richard Smith6c3af3d2013-01-17 01:17:56 +00005645
5646 public:
5647 /// \brief A region within an expression which may be sequenced with respect
5648 /// to some other region.
5649 class Seq {
5650 explicit Seq(unsigned N) : Index(N) {}
5651 unsigned Index;
5652 friend class SequenceTree;
5653 public:
5654 Seq() : Index(0) {}
5655 };
5656
5657 SequenceTree() { Values.push_back(Value(0)); }
5658 Seq root() const { return Seq(0); }
5659
5660 /// \brief Create a new sequence of operations, which is an unsequenced
5661 /// subset of \p Parent. This sequence of operations is sequenced with
5662 /// respect to other children of \p Parent.
5663 Seq allocate(Seq Parent) {
5664 Values.push_back(Value(Parent.Index));
5665 return Seq(Values.size() - 1);
5666 }
5667
5668 /// \brief Merge a sequence of operations into its parent.
5669 void merge(Seq S) {
5670 Values[S.Index].Merged = true;
5671 }
5672
5673 /// \brief Determine whether two operations are unsequenced. This operation
5674 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
5675 /// should have been merged into its parent as appropriate.
5676 bool isUnsequenced(Seq Cur, Seq Old) {
5677 unsigned C = representative(Cur.Index);
5678 unsigned Target = representative(Old.Index);
5679 while (C >= Target) {
5680 if (C == Target)
5681 return true;
5682 C = Values[C].Parent;
5683 }
5684 return false;
5685 }
5686
5687 private:
5688 /// \brief Pick a representative for a sequence.
5689 unsigned representative(unsigned K) {
5690 if (Values[K].Merged)
5691 // Perform path compression as we go.
5692 return Values[K].Parent = representative(Values[K].Parent);
5693 return K;
5694 }
5695 };
5696
5697 /// An object for which we can track unsequenced uses.
5698 typedef NamedDecl *Object;
5699
5700 /// Different flavors of object usage which we track. We only track the
5701 /// least-sequenced usage of each kind.
5702 enum UsageKind {
5703 /// A read of an object. Multiple unsequenced reads are OK.
5704 UK_Use,
5705 /// A modification of an object which is sequenced before the value
Richard Smith418dd3e2013-06-26 23:16:51 +00005706 /// computation of the expression, such as ++n in C++.
Richard Smith6c3af3d2013-01-17 01:17:56 +00005707 UK_ModAsValue,
5708 /// A modification of an object which is not sequenced before the value
5709 /// computation of the expression, such as n++.
5710 UK_ModAsSideEffect,
5711
5712 UK_Count = UK_ModAsSideEffect + 1
5713 };
5714
5715 struct Usage {
5716 Usage() : Use(0), Seq() {}
5717 Expr *Use;
5718 SequenceTree::Seq Seq;
5719 };
5720
5721 struct UsageInfo {
5722 UsageInfo() : Diagnosed(false) {}
5723 Usage Uses[UK_Count];
5724 /// Have we issued a diagnostic for this variable already?
5725 bool Diagnosed;
5726 };
5727 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
5728
5729 Sema &SemaRef;
5730 /// Sequenced regions within the expression.
5731 SequenceTree Tree;
5732 /// Declaration modifications and references which we have seen.
5733 UsageInfoMap UsageMap;
5734 /// The region we are currently within.
5735 SequenceTree::Seq Region;
5736 /// Filled in with declarations which were modified as a side-effect
5737 /// (that is, post-increment operations).
Robert Wilhelme7205c02013-08-10 12:33:24 +00005738 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smith1a2dcd52013-01-17 23:18:09 +00005739 /// Expressions to check later. We defer checking these to reduce
5740 /// stack usage.
Robert Wilhelme7205c02013-08-10 12:33:24 +00005741 SmallVectorImpl<Expr *> &WorkList;
Richard Smith6c3af3d2013-01-17 01:17:56 +00005742
5743 /// RAII object wrapping the visitation of a sequenced subexpression of an
5744 /// expression. At the end of this process, the side-effects of the evaluation
5745 /// become sequenced with respect to the value computation of the result, so
5746 /// we downgrade any UK_ModAsSideEffect within the evaluation to
5747 /// UK_ModAsValue.
5748 struct SequencedSubexpression {
5749 SequencedSubexpression(SequenceChecker &Self)
5750 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
5751 Self.ModAsSideEffect = &ModAsSideEffect;
5752 }
5753 ~SequencedSubexpression() {
5754 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
5755 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
5756 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
5757 Self.addUsage(U, ModAsSideEffect[I].first,
5758 ModAsSideEffect[I].second.Use, UK_ModAsValue);
5759 }
5760 Self.ModAsSideEffect = OldModAsSideEffect;
5761 }
5762
5763 SequenceChecker &Self;
Robert Wilhelme7205c02013-08-10 12:33:24 +00005764 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
5765 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smith6c3af3d2013-01-17 01:17:56 +00005766 };
5767
Richard Smith67470052013-06-20 22:21:56 +00005768 /// RAII object wrapping the visitation of a subexpression which we might
5769 /// choose to evaluate as a constant. If any subexpression is evaluated and
5770 /// found to be non-constant, this allows us to suppress the evaluation of
5771 /// the outer expression.
5772 class EvaluationTracker {
5773 public:
5774 EvaluationTracker(SequenceChecker &Self)
5775 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
5776 Self.EvalTracker = this;
5777 }
5778 ~EvaluationTracker() {
5779 Self.EvalTracker = Prev;
5780 if (Prev)
5781 Prev->EvalOK &= EvalOK;
5782 }
5783
5784 bool evaluate(const Expr *E, bool &Result) {
5785 if (!EvalOK || E->isValueDependent())
5786 return false;
5787 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
5788 return EvalOK;
5789 }
5790
5791 private:
5792 SequenceChecker &Self;
5793 EvaluationTracker *Prev;
5794 bool EvalOK;
5795 } *EvalTracker;
5796
Richard Smith6c3af3d2013-01-17 01:17:56 +00005797 /// \brief Find the object which is produced by the specified expression,
5798 /// if any.
5799 Object getObject(Expr *E, bool Mod) const {
5800 E = E->IgnoreParenCasts();
5801 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5802 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
5803 return getObject(UO->getSubExpr(), Mod);
5804 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5805 if (BO->getOpcode() == BO_Comma)
5806 return getObject(BO->getRHS(), Mod);
5807 if (Mod && BO->isAssignmentOp())
5808 return getObject(BO->getLHS(), Mod);
5809 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
5810 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
5811 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
5812 return ME->getMemberDecl();
5813 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5814 // FIXME: If this is a reference, map through to its value.
5815 return DRE->getDecl();
5816 return 0;
5817 }
5818
5819 /// \brief Note that an object was modified or used by an expression.
5820 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
5821 Usage &U = UI.Uses[UK];
5822 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
5823 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
5824 ModAsSideEffect->push_back(std::make_pair(O, U));
5825 U.Use = Ref;
5826 U.Seq = Region;
5827 }
5828 }
5829 /// \brief Check whether a modification or use conflicts with a prior usage.
5830 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
5831 bool IsModMod) {
5832 if (UI.Diagnosed)
5833 return;
5834
5835 const Usage &U = UI.Uses[OtherKind];
5836 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
5837 return;
5838
5839 Expr *Mod = U.Use;
5840 Expr *ModOrUse = Ref;
5841 if (OtherKind == UK_Use)
5842 std::swap(Mod, ModOrUse);
5843
5844 SemaRef.Diag(Mod->getExprLoc(),
5845 IsModMod ? diag::warn_unsequenced_mod_mod
5846 : diag::warn_unsequenced_mod_use)
5847 << O << SourceRange(ModOrUse->getExprLoc());
5848 UI.Diagnosed = true;
5849 }
5850
5851 void notePreUse(Object O, Expr *Use) {
5852 UsageInfo &U = UsageMap[O];
5853 // Uses conflict with other modifications.
5854 checkUsage(O, U, Use, UK_ModAsValue, false);
5855 }
5856 void notePostUse(Object O, Expr *Use) {
5857 UsageInfo &U = UsageMap[O];
5858 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
5859 addUsage(U, O, Use, UK_Use);
5860 }
5861
5862 void notePreMod(Object O, Expr *Mod) {
5863 UsageInfo &U = UsageMap[O];
5864 // Modifications conflict with other modifications and with uses.
5865 checkUsage(O, U, Mod, UK_ModAsValue, true);
5866 checkUsage(O, U, Mod, UK_Use, false);
5867 }
5868 void notePostMod(Object O, Expr *Use, UsageKind UK) {
5869 UsageInfo &U = UsageMap[O];
5870 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
5871 addUsage(U, O, Use, UK);
5872 }
5873
5874public:
Robert Wilhelme7205c02013-08-10 12:33:24 +00005875 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
5876 : Base(S.Context), SemaRef(S), Region(Tree.root()), ModAsSideEffect(0),
5877 WorkList(WorkList), EvalTracker(0) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00005878 Visit(E);
5879 }
5880
5881 void VisitStmt(Stmt *S) {
5882 // Skip all statements which aren't expressions for now.
5883 }
5884
5885 void VisitExpr(Expr *E) {
5886 // By default, just recurse to evaluated subexpressions.
Richard Smith0c0b3902013-06-30 10:40:20 +00005887 Base::VisitStmt(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005888 }
5889
5890 void VisitCastExpr(CastExpr *E) {
5891 Object O = Object();
5892 if (E->getCastKind() == CK_LValueToRValue)
5893 O = getObject(E->getSubExpr(), false);
5894
5895 if (O)
5896 notePreUse(O, E);
5897 VisitExpr(E);
5898 if (O)
5899 notePostUse(O, E);
5900 }
5901
5902 void VisitBinComma(BinaryOperator *BO) {
5903 // C++11 [expr.comma]p1:
5904 // Every value computation and side effect associated with the left
5905 // expression is sequenced before every value computation and side
5906 // effect associated with the right expression.
5907 SequenceTree::Seq LHS = Tree.allocate(Region);
5908 SequenceTree::Seq RHS = Tree.allocate(Region);
5909 SequenceTree::Seq OldRegion = Region;
5910
5911 {
5912 SequencedSubexpression SeqLHS(*this);
5913 Region = LHS;
5914 Visit(BO->getLHS());
5915 }
5916
5917 Region = RHS;
5918 Visit(BO->getRHS());
5919
5920 Region = OldRegion;
5921
5922 // Forget that LHS and RHS are sequenced. They are both unsequenced
5923 // with respect to other stuff.
5924 Tree.merge(LHS);
5925 Tree.merge(RHS);
5926 }
5927
5928 void VisitBinAssign(BinaryOperator *BO) {
5929 // The modification is sequenced after the value computation of the LHS
5930 // and RHS, so check it before inspecting the operands and update the
5931 // map afterwards.
5932 Object O = getObject(BO->getLHS(), true);
5933 if (!O)
5934 return VisitExpr(BO);
5935
5936 notePreMod(O, BO);
5937
5938 // C++11 [expr.ass]p7:
5939 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
5940 // only once.
5941 //
5942 // Therefore, for a compound assignment operator, O is considered used
5943 // everywhere except within the evaluation of E1 itself.
5944 if (isa<CompoundAssignOperator>(BO))
5945 notePreUse(O, BO);
5946
5947 Visit(BO->getLHS());
5948
5949 if (isa<CompoundAssignOperator>(BO))
5950 notePostUse(O, BO);
5951
5952 Visit(BO->getRHS());
5953
Richard Smith418dd3e2013-06-26 23:16:51 +00005954 // C++11 [expr.ass]p1:
5955 // the assignment is sequenced [...] before the value computation of the
5956 // assignment expression.
5957 // C11 6.5.16/3 has no such rule.
5958 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
5959 : UK_ModAsSideEffect);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005960 }
5961 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
5962 VisitBinAssign(CAO);
5963 }
5964
5965 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
5966 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
5967 void VisitUnaryPreIncDec(UnaryOperator *UO) {
5968 Object O = getObject(UO->getSubExpr(), true);
5969 if (!O)
5970 return VisitExpr(UO);
5971
5972 notePreMod(O, UO);
5973 Visit(UO->getSubExpr());
Richard Smith418dd3e2013-06-26 23:16:51 +00005974 // C++11 [expr.pre.incr]p1:
5975 // the expression ++x is equivalent to x+=1
5976 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
5977 : UK_ModAsSideEffect);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005978 }
5979
5980 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
5981 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
5982 void VisitUnaryPostIncDec(UnaryOperator *UO) {
5983 Object O = getObject(UO->getSubExpr(), true);
5984 if (!O)
5985 return VisitExpr(UO);
5986
5987 notePreMod(O, UO);
5988 Visit(UO->getSubExpr());
5989 notePostMod(O, UO, UK_ModAsSideEffect);
5990 }
5991
5992 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
5993 void VisitBinLOr(BinaryOperator *BO) {
5994 // The side-effects of the LHS of an '&&' are sequenced before the
5995 // value computation of the RHS, and hence before the value computation
5996 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
5997 // as if they were unconditionally sequenced.
Richard Smith67470052013-06-20 22:21:56 +00005998 EvaluationTracker Eval(*this);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005999 {
6000 SequencedSubexpression Sequenced(*this);
6001 Visit(BO->getLHS());
6002 }
6003
6004 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00006005 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith995e4a72013-01-17 22:06:26 +00006006 if (!Result)
6007 Visit(BO->getRHS());
6008 } else {
6009 // Check for unsequenced operations in the RHS, treating it as an
6010 // entirely separate evaluation.
6011 //
6012 // FIXME: If there are operations in the RHS which are unsequenced
6013 // with respect to operations outside the RHS, and those operations
6014 // are unconditionally evaluated, diagnose them.
Richard Smith1a2dcd52013-01-17 23:18:09 +00006015 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00006016 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00006017 }
6018 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith67470052013-06-20 22:21:56 +00006019 EvaluationTracker Eval(*this);
Richard Smith6c3af3d2013-01-17 01:17:56 +00006020 {
6021 SequencedSubexpression Sequenced(*this);
6022 Visit(BO->getLHS());
6023 }
6024
6025 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00006026 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith995e4a72013-01-17 22:06:26 +00006027 if (Result)
6028 Visit(BO->getRHS());
6029 } else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00006030 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00006031 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00006032 }
6033
6034 // Only visit the condition, unless we can be sure which subexpression will
6035 // be chosen.
6036 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith67470052013-06-20 22:21:56 +00006037 EvaluationTracker Eval(*this);
Richard Smith418dd3e2013-06-26 23:16:51 +00006038 {
6039 SequencedSubexpression Sequenced(*this);
6040 Visit(CO->getCond());
6041 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00006042
6043 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00006044 if (Eval.evaluate(CO->getCond(), Result))
Richard Smith6c3af3d2013-01-17 01:17:56 +00006045 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00006046 else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00006047 WorkList.push_back(CO->getTrueExpr());
6048 WorkList.push_back(CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00006049 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00006050 }
6051
Richard Smith0c0b3902013-06-30 10:40:20 +00006052 void VisitCallExpr(CallExpr *CE) {
6053 // C++11 [intro.execution]p15:
6054 // When calling a function [...], every value computation and side effect
6055 // associated with any argument expression, or with the postfix expression
6056 // designating the called function, is sequenced before execution of every
6057 // expression or statement in the body of the function [and thus before
6058 // the value computation of its result].
6059 SequencedSubexpression Sequenced(*this);
6060 Base::VisitCallExpr(CE);
6061
6062 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
6063 }
6064
Richard Smith6c3af3d2013-01-17 01:17:56 +00006065 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smith0c0b3902013-06-30 10:40:20 +00006066 // This is a call, so all subexpressions are sequenced before the result.
6067 SequencedSubexpression Sequenced(*this);
6068
Richard Smith6c3af3d2013-01-17 01:17:56 +00006069 if (!CCE->isListInitialization())
6070 return VisitExpr(CCE);
6071
6072 // In C++11, list initializations are sequenced.
Robert Wilhelme7205c02013-08-10 12:33:24 +00006073 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smith6c3af3d2013-01-17 01:17:56 +00006074 SequenceTree::Seq Parent = Region;
6075 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
6076 E = CCE->arg_end();
6077 I != E; ++I) {
6078 Region = Tree.allocate(Parent);
6079 Elts.push_back(Region);
6080 Visit(*I);
6081 }
6082
6083 // Forget that the initializers are sequenced.
6084 Region = Parent;
6085 for (unsigned I = 0; I < Elts.size(); ++I)
6086 Tree.merge(Elts[I]);
6087 }
6088
6089 void VisitInitListExpr(InitListExpr *ILE) {
6090 if (!SemaRef.getLangOpts().CPlusPlus11)
6091 return VisitExpr(ILE);
6092
6093 // In C++11, list initializations are sequenced.
Robert Wilhelme7205c02013-08-10 12:33:24 +00006094 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smith6c3af3d2013-01-17 01:17:56 +00006095 SequenceTree::Seq Parent = Region;
6096 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
6097 Expr *E = ILE->getInit(I);
6098 if (!E) continue;
6099 Region = Tree.allocate(Parent);
6100 Elts.push_back(Region);
6101 Visit(E);
6102 }
6103
6104 // Forget that the initializers are sequenced.
6105 Region = Parent;
6106 for (unsigned I = 0; I < Elts.size(); ++I)
6107 Tree.merge(Elts[I]);
6108 }
6109};
6110}
6111
6112void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelme7205c02013-08-10 12:33:24 +00006113 SmallVector<Expr *, 8> WorkList;
Richard Smith1a2dcd52013-01-17 23:18:09 +00006114 WorkList.push_back(E);
6115 while (!WorkList.empty()) {
Robert Wilhelm344472e2013-08-23 16:11:15 +00006116 Expr *Item = WorkList.pop_back_val();
Richard Smith1a2dcd52013-01-17 23:18:09 +00006117 SequenceChecker(*this, Item, WorkList);
6118 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00006119}
6120
Fariborz Jahanianad48a502013-01-24 22:11:45 +00006121void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
6122 bool IsConstexpr) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00006123 CheckImplicitConversions(E, CheckLoc);
6124 CheckUnsequencedOperations(E);
Fariborz Jahanianad48a502013-01-24 22:11:45 +00006125 if (!IsConstexpr && !E->isValueDependent())
6126 CheckForIntOverflow(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00006127}
6128
John McCall15d7d122010-11-11 03:21:53 +00006129void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
6130 FieldDecl *BitField,
6131 Expr *Init) {
6132 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
6133}
6134
Mike Stumpf8c49212010-01-21 03:59:47 +00006135/// CheckParmsForFunctionDef - Check that the parameters of the given
6136/// function are appropriate for the definition of a function. This
6137/// takes care of any checks that cannot be performed on the
6138/// declaration itself, e.g., that the types of each of the function
6139/// parameters are complete.
Reid Kleckner8c0501c2013-06-24 14:38:26 +00006140bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
6141 ParmVarDecl *const *PEnd,
Douglas Gregor82aa7132010-11-01 18:37:59 +00006142 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00006143 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00006144 for (; P != PEnd; ++P) {
6145 ParmVarDecl *Param = *P;
6146
Mike Stumpf8c49212010-01-21 03:59:47 +00006147 // C99 6.7.5.3p4: the parameters in a parameter type list in a
6148 // function declarator that is part of a function definition of
6149 // that function shall not have incomplete type.
6150 //
6151 // This is also C++ [dcl.fct]p6.
6152 if (!Param->isInvalidDecl() &&
6153 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00006154 diag::err_typecheck_decl_incomplete_type)) {
Mike Stumpf8c49212010-01-21 03:59:47 +00006155 Param->setInvalidDecl();
6156 HasInvalidParm = true;
6157 }
6158
6159 // C99 6.9.1p5: If the declarator includes a parameter type list, the
6160 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00006161 if (CheckParameterNames &&
6162 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00006163 !Param->isImplicit() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006164 !getLangOpts().CPlusPlus)
Mike Stumpf8c49212010-01-21 03:59:47 +00006165 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00006166
6167 // C99 6.7.5.3p12:
6168 // If the function declarator is not part of a definition of that
6169 // function, parameters may have incomplete type and may use the [*]
6170 // notation in their sequences of declarator specifiers to specify
6171 // variable length array types.
6172 QualType PType = Param->getOriginalType();
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00006173 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigd17e3402010-02-01 05:02:49 +00006174 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitfc093362013-03-01 21:41:22 +00006175 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigd17e3402010-02-01 05:02:49 +00006176 // information is added for it.
6177 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00006178 break;
Sam Weinigd17e3402010-02-01 05:02:49 +00006179 }
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00006180 PType= AT->getElementType();
Sam Weinigd17e3402010-02-01 05:02:49 +00006181 }
Reid Kleckner9b601952013-06-21 12:45:15 +00006182
6183 // MSVC destroys objects passed by value in the callee. Therefore a
6184 // function definition which takes such a parameter must be able to call the
6185 // object's destructor.
6186 if (getLangOpts().CPlusPlus &&
6187 Context.getTargetInfo().getCXXABI().isArgumentDestroyedByCallee()) {
6188 if (const RecordType *RT = Param->getType()->getAs<RecordType>())
6189 FinalizeVarWithDestructor(Param, RT);
6190 }
Mike Stumpf8c49212010-01-21 03:59:47 +00006191 }
6192
6193 return HasInvalidParm;
6194}
John McCallb7f4ffe2010-08-12 21:44:57 +00006195
6196/// CheckCastAlign - Implements -Wcast-align, which warns when a
6197/// pointer cast increases the alignment requirements.
6198void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
6199 // This is actually a lot of work to potentially be doing on every
6200 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00006201 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
6202 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00006203 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00006204 return;
6205
6206 // Ignore dependent types.
6207 if (T->isDependentType() || Op->getType()->isDependentType())
6208 return;
6209
6210 // Require that the destination be a pointer type.
6211 const PointerType *DestPtr = T->getAs<PointerType>();
6212 if (!DestPtr) return;
6213
6214 // If the destination has alignment 1, we're done.
6215 QualType DestPointee = DestPtr->getPointeeType();
6216 if (DestPointee->isIncompleteType()) return;
6217 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
6218 if (DestAlign.isOne()) return;
6219
6220 // Require that the source be a pointer type.
6221 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
6222 if (!SrcPtr) return;
6223 QualType SrcPointee = SrcPtr->getPointeeType();
6224
6225 // Whitelist casts from cv void*. We already implicitly
6226 // whitelisted casts to cv void*, since they have alignment 1.
6227 // Also whitelist casts involving incomplete types, which implicitly
6228 // includes 'void'.
6229 if (SrcPointee->isIncompleteType()) return;
6230
6231 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
6232 if (SrcAlign >= DestAlign) return;
6233
6234 Diag(TRange.getBegin(), diag::warn_cast_align)
6235 << Op->getType() << T
6236 << static_cast<unsigned>(SrcAlign.getQuantity())
6237 << static_cast<unsigned>(DestAlign.getQuantity())
6238 << TRange << Op->getSourceRange();
6239}
6240
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006241static const Type* getElementType(const Expr *BaseExpr) {
6242 const Type* EltType = BaseExpr->getType().getTypePtr();
6243 if (EltType->isAnyPointerType())
6244 return EltType->getPointeeType().getTypePtr();
6245 else if (EltType->isArrayType())
6246 return EltType->getBaseElementTypeUnsafe();
6247 return EltType;
6248}
6249
Chandler Carruthc2684342011-08-05 09:10:50 +00006250/// \brief Check whether this array fits the idiom of a size-one tail padded
6251/// array member of a struct.
6252///
6253/// We avoid emitting out-of-bounds access warnings for such arrays as they are
6254/// commonly used to emulate flexible arrays in C89 code.
6255static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
6256 const NamedDecl *ND) {
6257 if (Size != 1 || !ND) return false;
6258
6259 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
6260 if (!FD) return false;
6261
6262 // Don't consider sizes resulting from macro expansions or template argument
6263 // substitution to form C89 tail-padded arrays.
Sean Callanand2cf3482012-05-04 18:22:53 +00006264
6265 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00006266 while (TInfo) {
6267 TypeLoc TL = TInfo->getTypeLoc();
6268 // Look through typedefs.
David Blaikie39e6ab42013-02-18 22:06:02 +00006269 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
6270 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00006271 TInfo = TDL->getTypeSourceInfo();
6272 continue;
6273 }
David Blaikie39e6ab42013-02-18 22:06:02 +00006274 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
6275 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier5e253012013-02-06 00:58:34 +00006276 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
6277 return false;
6278 }
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00006279 break;
Sean Callanand2cf3482012-05-04 18:22:53 +00006280 }
Chandler Carruthc2684342011-08-05 09:10:50 +00006281
6282 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00006283 if (!RD) return false;
6284 if (RD->isUnion()) return false;
6285 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
6286 if (!CRD->isStandardLayout()) return false;
6287 }
Chandler Carruthc2684342011-08-05 09:10:50 +00006288
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00006289 // See if this is the last field decl in the record.
6290 const Decl *D = FD;
6291 while ((D = D->getNextDeclInContext()))
6292 if (isa<FieldDecl>(D))
6293 return false;
6294 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00006295}
6296
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006297void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006298 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00006299 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman92b670e2012-02-27 21:21:40 +00006300 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006301 if (IndexExpr->isValueDependent())
6302 return;
6303
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00006304 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006305 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00006306 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006307 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00006308 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00006309 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00006310
Chandler Carruth34064582011-02-17 20:55:08 +00006311 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006312 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00006313 return;
Richard Smith25b009a2011-12-16 19:31:14 +00006314 if (IndexNegated)
6315 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00006316
Chandler Carruthba447122011-08-05 08:07:29 +00006317 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00006318 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6319 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00006320 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00006321 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00006322
Ted Kremenek9e060ca2011-02-23 23:06:04 +00006323 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00006324 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00006325 if (!size.isStrictlyPositive())
6326 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006327
6328 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00006329 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006330 // Make sure we're comparing apples to apples when comparing index to size
6331 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
6332 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00006333 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00006334 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006335 if (ptrarith_typesize != array_typesize) {
6336 // There's a cast to a different size type involved
6337 uint64_t ratio = array_typesize / ptrarith_typesize;
6338 // TODO: Be smarter about handling cases where array_typesize is not a
6339 // multiple of ptrarith_typesize
6340 if (ptrarith_typesize * ratio == array_typesize)
6341 size *= llvm::APInt(size.getBitWidth(), ratio);
6342 }
6343 }
6344
Chandler Carruth34064582011-02-17 20:55:08 +00006345 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00006346 index = index.zext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00006347 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00006348 size = size.zext(index.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00006349
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006350 // For array subscripting the index must be less than size, but for pointer
6351 // arithmetic also allow the index (offset) to be equal to size since
6352 // computing the next address after the end of the array is legal and
6353 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman92b670e2012-02-27 21:21:40 +00006354 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruthba447122011-08-05 08:07:29 +00006355 return;
6356
6357 // Also don't warn for arrays of size 1 which are members of some
6358 // structure. These are often used to approximate flexible arrays in C89
6359 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006360 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00006361 return;
Chandler Carruth34064582011-02-17 20:55:08 +00006362
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006363 // Suppress the warning if the subscript expression (as identified by the
6364 // ']' location) and the index expression are both from macro expansions
6365 // within a system header.
6366 if (ASE) {
6367 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
6368 ASE->getRBracketLoc());
6369 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
6370 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
6371 IndexExpr->getLocStart());
Eli Friedman24146972013-08-22 00:27:10 +00006372 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006373 return;
6374 }
6375 }
6376
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006377 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006378 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006379 DiagID = diag::warn_array_index_exceeds_bounds;
6380
6381 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6382 PDiag(DiagID) << index.toString(10, true)
6383 << size.toString(10, true)
6384 << (unsigned)size.getLimitedValue(~0U)
6385 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00006386 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006387 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006388 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006389 DiagID = diag::warn_ptr_arith_precedes_bounds;
6390 if (index.isNegative()) index = -index;
6391 }
6392
6393 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6394 PDiag(DiagID) << index.toString(10, true)
6395 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00006396 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00006397
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00006398 if (!ND) {
6399 // Try harder to find a NamedDecl to point at in the note.
6400 while (const ArraySubscriptExpr *ASE =
6401 dyn_cast<ArraySubscriptExpr>(BaseExpr))
6402 BaseExpr = ASE->getBase()->IgnoreParenCasts();
6403 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6404 ND = dyn_cast<NamedDecl>(DRE->getDecl());
6405 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
6406 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
6407 }
6408
Chandler Carruth35001ca2011-02-17 21:10:52 +00006409 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006410 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
6411 PDiag(diag::note_array_index_out_of_bounds)
6412 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00006413}
6414
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006415void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006416 int AllowOnePastEnd = 0;
6417 while (expr) {
6418 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006419 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006420 case Stmt::ArraySubscriptExprClass: {
6421 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006422 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006423 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006424 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006425 }
6426 case Stmt::UnaryOperatorClass: {
6427 // Only unwrap the * and & unary operators
6428 const UnaryOperator *UO = cast<UnaryOperator>(expr);
6429 expr = UO->getSubExpr();
6430 switch (UO->getOpcode()) {
6431 case UO_AddrOf:
6432 AllowOnePastEnd++;
6433 break;
6434 case UO_Deref:
6435 AllowOnePastEnd--;
6436 break;
6437 default:
6438 return;
6439 }
6440 break;
6441 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006442 case Stmt::ConditionalOperatorClass: {
6443 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
6444 if (const Expr *lhs = cond->getLHS())
6445 CheckArrayAccess(lhs);
6446 if (const Expr *rhs = cond->getRHS())
6447 CheckArrayAccess(rhs);
6448 return;
6449 }
6450 default:
6451 return;
6452 }
Peter Collingbournef111d932011-04-15 00:35:48 +00006453 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006454}
John McCallf85e1932011-06-15 23:02:42 +00006455
6456//===--- CHECK: Objective-C retain cycles ----------------------------------//
6457
6458namespace {
6459 struct RetainCycleOwner {
6460 RetainCycleOwner() : Variable(0), Indirect(false) {}
6461 VarDecl *Variable;
6462 SourceRange Range;
6463 SourceLocation Loc;
6464 bool Indirect;
6465
6466 void setLocsFrom(Expr *e) {
6467 Loc = e->getExprLoc();
6468 Range = e->getSourceRange();
6469 }
6470 };
6471}
6472
6473/// Consider whether capturing the given variable can possibly lead to
6474/// a retain cycle.
6475static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00006476 // In ARC, it's captured strongly iff the variable has __strong
John McCallf85e1932011-06-15 23:02:42 +00006477 // lifetime. In MRR, it's captured strongly if the variable is
6478 // __block and has an appropriate type.
6479 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6480 return false;
6481
6482 owner.Variable = var;
Jordan Rosee10f4d32012-09-15 02:48:31 +00006483 if (ref)
6484 owner.setLocsFrom(ref);
John McCallf85e1932011-06-15 23:02:42 +00006485 return true;
6486}
6487
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006488static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00006489 while (true) {
6490 e = e->IgnoreParens();
6491 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
6492 switch (cast->getCastKind()) {
6493 case CK_BitCast:
6494 case CK_LValueBitCast:
6495 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00006496 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00006497 e = cast->getSubExpr();
6498 continue;
6499
John McCallf85e1932011-06-15 23:02:42 +00006500 default:
6501 return false;
6502 }
6503 }
6504
6505 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
6506 ObjCIvarDecl *ivar = ref->getDecl();
6507 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6508 return false;
6509
6510 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006511 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00006512 return false;
6513
6514 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
6515 owner.Indirect = true;
6516 return true;
6517 }
6518
6519 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
6520 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
6521 if (!var) return false;
6522 return considerVariable(var, ref, owner);
6523 }
6524
John McCallf85e1932011-06-15 23:02:42 +00006525 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
6526 if (member->isArrow()) return false;
6527
6528 // Don't count this as an indirect ownership.
6529 e = member->getBase();
6530 continue;
6531 }
6532
John McCall4b9c2d22011-11-06 09:01:30 +00006533 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
6534 // Only pay attention to pseudo-objects on property references.
6535 ObjCPropertyRefExpr *pre
6536 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
6537 ->IgnoreParens());
6538 if (!pre) return false;
6539 if (pre->isImplicitProperty()) return false;
6540 ObjCPropertyDecl *property = pre->getExplicitProperty();
6541 if (!property->isRetaining() &&
6542 !(property->getPropertyIvarDecl() &&
6543 property->getPropertyIvarDecl()->getType()
6544 .getObjCLifetime() == Qualifiers::OCL_Strong))
6545 return false;
6546
6547 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006548 if (pre->isSuperReceiver()) {
6549 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
6550 if (!owner.Variable)
6551 return false;
6552 owner.Loc = pre->getLocation();
6553 owner.Range = pre->getSourceRange();
6554 return true;
6555 }
John McCall4b9c2d22011-11-06 09:01:30 +00006556 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
6557 ->getSourceExpr());
6558 continue;
6559 }
6560
John McCallf85e1932011-06-15 23:02:42 +00006561 // Array ivars?
6562
6563 return false;
6564 }
6565}
6566
6567namespace {
6568 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
6569 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
6570 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
6571 Variable(variable), Capturer(0) {}
6572
6573 VarDecl *Variable;
6574 Expr *Capturer;
6575
6576 void VisitDeclRefExpr(DeclRefExpr *ref) {
6577 if (ref->getDecl() == Variable && !Capturer)
6578 Capturer = ref;
6579 }
6580
John McCallf85e1932011-06-15 23:02:42 +00006581 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
6582 if (Capturer) return;
6583 Visit(ref->getBase());
6584 if (Capturer && ref->isFreeIvar())
6585 Capturer = ref;
6586 }
6587
6588 void VisitBlockExpr(BlockExpr *block) {
6589 // Look inside nested blocks
6590 if (block->getBlockDecl()->capturesVariable(Variable))
6591 Visit(block->getBlockDecl()->getBody());
6592 }
Fariborz Jahanian7e2e4c32012-08-31 20:04:47 +00006593
6594 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
6595 if (Capturer) return;
6596 if (OVE->getSourceExpr())
6597 Visit(OVE->getSourceExpr());
6598 }
John McCallf85e1932011-06-15 23:02:42 +00006599 };
6600}
6601
6602/// Check whether the given argument is a block which captures a
6603/// variable.
6604static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
6605 assert(owner.Variable && owner.Loc.isValid());
6606
6607 e = e->IgnoreParenCasts();
Jordan Rose1fac58a2012-09-17 17:54:30 +00006608
6609 // Look through [^{...} copy] and Block_copy(^{...}).
6610 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
6611 Selector Cmd = ME->getSelector();
6612 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
6613 e = ME->getInstanceReceiver();
6614 if (!e)
6615 return 0;
6616 e = e->IgnoreParenCasts();
6617 }
6618 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
6619 if (CE->getNumArgs() == 1) {
6620 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekd13eff62012-10-02 04:36:54 +00006621 if (Fn) {
6622 const IdentifierInfo *FnI = Fn->getIdentifier();
6623 if (FnI && FnI->isStr("_Block_copy")) {
6624 e = CE->getArg(0)->IgnoreParenCasts();
6625 }
6626 }
Jordan Rose1fac58a2012-09-17 17:54:30 +00006627 }
6628 }
6629
John McCallf85e1932011-06-15 23:02:42 +00006630 BlockExpr *block = dyn_cast<BlockExpr>(e);
6631 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
6632 return 0;
6633
6634 FindCaptureVisitor visitor(S.Context, owner.Variable);
6635 visitor.Visit(block->getBlockDecl()->getBody());
6636 return visitor.Capturer;
6637}
6638
6639static void diagnoseRetainCycle(Sema &S, Expr *capturer,
6640 RetainCycleOwner &owner) {
6641 assert(capturer);
6642 assert(owner.Variable && owner.Loc.isValid());
6643
6644 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
6645 << owner.Variable << capturer->getSourceRange();
6646 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
6647 << owner.Indirect << owner.Range;
6648}
6649
6650/// Check for a keyword selector that starts with the word 'add' or
6651/// 'set'.
6652static bool isSetterLikeSelector(Selector sel) {
6653 if (sel.isUnarySelector()) return false;
6654
Chris Lattner5f9e2722011-07-23 10:55:15 +00006655 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00006656 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00006657 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00006658 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00006659 else if (str.startswith("add")) {
6660 // Specially whitelist 'addOperationWithBlock:'.
6661 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
6662 return false;
6663 str = str.substr(3);
6664 }
John McCallf85e1932011-06-15 23:02:42 +00006665 else
6666 return false;
6667
6668 if (str.empty()) return true;
Jordan Rose3f6f51e2013-02-08 22:30:41 +00006669 return !isLowercase(str.front());
John McCallf85e1932011-06-15 23:02:42 +00006670}
6671
6672/// Check a message send to see if it's likely to cause a retain cycle.
6673void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
6674 // Only check instance methods whose selector looks like a setter.
6675 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
6676 return;
6677
6678 // Try to find a variable that the receiver is strongly owned by.
6679 RetainCycleOwner owner;
6680 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006681 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00006682 return;
6683 } else {
6684 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
6685 owner.Variable = getCurMethodDecl()->getSelfDecl();
6686 owner.Loc = msg->getSuperLoc();
6687 owner.Range = msg->getSuperLoc();
6688 }
6689
6690 // Check whether the receiver is captured by any of the arguments.
6691 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
6692 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
6693 return diagnoseRetainCycle(*this, capturer, owner);
6694}
6695
6696/// Check a property assign to see if it's likely to cause a retain cycle.
6697void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
6698 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006699 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00006700 return;
6701
6702 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
6703 diagnoseRetainCycle(*this, capturer, owner);
6704}
6705
Jordan Rosee10f4d32012-09-15 02:48:31 +00006706void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
6707 RetainCycleOwner Owner;
6708 if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
6709 return;
6710
6711 // Because we don't have an expression for the variable, we have to set the
6712 // location explicitly here.
6713 Owner.Loc = Var->getLocation();
6714 Owner.Range = Var->getSourceRange();
6715
6716 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
6717 diagnoseRetainCycle(*this, Capturer, Owner);
6718}
6719
Ted Kremenek9d084012012-12-21 08:04:28 +00006720static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
6721 Expr *RHS, bool isProperty) {
6722 // Check if RHS is an Objective-C object literal, which also can get
6723 // immediately zapped in a weak reference. Note that we explicitly
6724 // allow ObjCStringLiterals, since those are designed to never really die.
6725 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenekf530ff72012-12-21 21:59:39 +00006726
Ted Kremenekd3292c82012-12-21 22:46:35 +00006727 // This enum needs to match with the 'select' in
6728 // warn_objc_arc_literal_assign (off-by-1).
6729 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
6730 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
6731 return false;
Ted Kremenekf530ff72012-12-21 21:59:39 +00006732
6733 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenekd3292c82012-12-21 22:46:35 +00006734 << (unsigned) Kind
Ted Kremenek9d084012012-12-21 08:04:28 +00006735 << (isProperty ? 0 : 1)
6736 << RHS->getSourceRange();
Ted Kremenekf530ff72012-12-21 21:59:39 +00006737
6738 return true;
Ted Kremenek9d084012012-12-21 08:04:28 +00006739}
6740
Ted Kremenekb29b30f2012-12-21 19:45:30 +00006741static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
6742 Qualifiers::ObjCLifetime LT,
6743 Expr *RHS, bool isProperty) {
6744 // Strip off any implicit cast added to get to the one ARC-specific.
6745 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
6746 if (cast->getCastKind() == CK_ARCConsumeObject) {
6747 S.Diag(Loc, diag::warn_arc_retained_assign)
6748 << (LT == Qualifiers::OCL_ExplicitNone)
6749 << (isProperty ? 0 : 1)
6750 << RHS->getSourceRange();
6751 return true;
6752 }
6753 RHS = cast->getSubExpr();
6754 }
6755
6756 if (LT == Qualifiers::OCL_Weak &&
6757 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
6758 return true;
6759
6760 return false;
6761}
6762
Ted Kremenekb1ea5102012-12-21 08:04:20 +00006763bool Sema::checkUnsafeAssigns(SourceLocation Loc,
6764 QualType LHS, Expr *RHS) {
6765 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
6766
6767 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
6768 return false;
6769
6770 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
6771 return true;
6772
6773 return false;
6774}
6775
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006776void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
6777 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006778 QualType LHSType;
6779 // PropertyRef on LHS type need be directly obtained from
6780 // its declaration as it has a PsuedoType.
6781 ObjCPropertyRefExpr *PRE
6782 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
6783 if (PRE && !PRE->isImplicitProperty()) {
6784 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6785 if (PD)
6786 LHSType = PD->getType();
6787 }
6788
6789 if (LHSType.isNull())
6790 LHSType = LHS->getType();
Jordan Rose7a270482012-09-28 22:21:35 +00006791
6792 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
6793
6794 if (LT == Qualifiers::OCL_Weak) {
6795 DiagnosticsEngine::Level Level =
6796 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
6797 if (Level != DiagnosticsEngine::Ignored)
6798 getCurFunction()->markSafeWeakUse(LHS);
6799 }
6800
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006801 if (checkUnsafeAssigns(Loc, LHSType, RHS))
6802 return;
Jordan Rose7a270482012-09-28 22:21:35 +00006803
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006804 // FIXME. Check for other life times.
6805 if (LT != Qualifiers::OCL_None)
6806 return;
6807
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006808 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006809 if (PRE->isImplicitProperty())
6810 return;
6811 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6812 if (!PD)
6813 return;
6814
Bill Wendlingad017fa2012-12-20 19:22:21 +00006815 unsigned Attributes = PD->getPropertyAttributes();
6816 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006817 // when 'assign' attribute was not explicitly specified
6818 // by user, ignore it and rely on property type itself
6819 // for lifetime info.
6820 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
6821 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
6822 LHSType->isObjCRetainableType())
6823 return;
6824
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006825 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00006826 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006827 Diag(Loc, diag::warn_arc_retained_property_assign)
6828 << RHS->getSourceRange();
6829 return;
6830 }
6831 RHS = cast->getSubExpr();
6832 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006833 }
Bill Wendlingad017fa2012-12-20 19:22:21 +00006834 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb1ea5102012-12-21 08:04:20 +00006835 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
6836 return;
Fariborz Jahanianbd2e27e2012-07-06 21:09:27 +00006837 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006838 }
6839}
Dmitri Gribenko625bb562012-02-14 22:14:32 +00006840
6841//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
6842
6843namespace {
6844bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
6845 SourceLocation StmtLoc,
6846 const NullStmt *Body) {
6847 // Do not warn if the body is a macro that expands to nothing, e.g:
6848 //
6849 // #define CALL(x)
6850 // if (condition)
6851 // CALL(0);
6852 //
6853 if (Body->hasLeadingEmptyMacro())
6854 return false;
6855
6856 // Get line numbers of statement and body.
6857 bool StmtLineInvalid;
6858 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
6859 &StmtLineInvalid);
6860 if (StmtLineInvalid)
6861 return false;
6862
6863 bool BodyLineInvalid;
6864 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
6865 &BodyLineInvalid);
6866 if (BodyLineInvalid)
6867 return false;
6868
6869 // Warn if null statement and body are on the same line.
6870 if (StmtLine != BodyLine)
6871 return false;
6872
6873 return true;
6874}
6875} // Unnamed namespace
6876
6877void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
6878 const Stmt *Body,
6879 unsigned DiagID) {
6880 // Since this is a syntactic check, don't emit diagnostic for template
6881 // instantiations, this just adds noise.
6882 if (CurrentInstantiationScope)
6883 return;
6884
6885 // The body should be a null statement.
6886 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6887 if (!NBody)
6888 return;
6889
6890 // Do the usual checks.
6891 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6892 return;
6893
6894 Diag(NBody->getSemiLoc(), DiagID);
6895 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6896}
6897
6898void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
6899 const Stmt *PossibleBody) {
6900 assert(!CurrentInstantiationScope); // Ensured by caller
6901
6902 SourceLocation StmtLoc;
6903 const Stmt *Body;
6904 unsigned DiagID;
6905 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
6906 StmtLoc = FS->getRParenLoc();
6907 Body = FS->getBody();
6908 DiagID = diag::warn_empty_for_body;
6909 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
6910 StmtLoc = WS->getCond()->getSourceRange().getEnd();
6911 Body = WS->getBody();
6912 DiagID = diag::warn_empty_while_body;
6913 } else
6914 return; // Neither `for' nor `while'.
6915
6916 // The body should be a null statement.
6917 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6918 if (!NBody)
6919 return;
6920
6921 // Skip expensive checks if diagnostic is disabled.
6922 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
6923 DiagnosticsEngine::Ignored)
6924 return;
6925
6926 // Do the usual checks.
6927 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6928 return;
6929
6930 // `for(...);' and `while(...);' are popular idioms, so in order to keep
6931 // noise level low, emit diagnostics only if for/while is followed by a
6932 // CompoundStmt, e.g.:
6933 // for (int i = 0; i < n; i++);
6934 // {
6935 // a(i);
6936 // }
6937 // or if for/while is followed by a statement with more indentation
6938 // than for/while itself:
6939 // for (int i = 0; i < n; i++);
6940 // a(i);
6941 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
6942 if (!ProbableTypo) {
6943 bool BodyColInvalid;
6944 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
6945 PossibleBody->getLocStart(),
6946 &BodyColInvalid);
6947 if (BodyColInvalid)
6948 return;
6949
6950 bool StmtColInvalid;
6951 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
6952 S->getLocStart(),
6953 &StmtColInvalid);
6954 if (StmtColInvalid)
6955 return;
6956
6957 if (BodyCol > StmtCol)
6958 ProbableTypo = true;
6959 }
6960
6961 if (ProbableTypo) {
6962 Diag(NBody->getSemiLoc(), DiagID);
6963 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6964 }
6965}
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00006966
6967//===--- Layout compatibility ----------------------------------------------//
6968
6969namespace {
6970
6971bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
6972
6973/// \brief Check if two enumeration types are layout-compatible.
6974bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
6975 // C++11 [dcl.enum] p8:
6976 // Two enumeration types are layout-compatible if they have the same
6977 // underlying type.
6978 return ED1->isComplete() && ED2->isComplete() &&
6979 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
6980}
6981
6982/// \brief Check if two fields are layout-compatible.
6983bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
6984 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
6985 return false;
6986
6987 if (Field1->isBitField() != Field2->isBitField())
6988 return false;
6989
6990 if (Field1->isBitField()) {
6991 // Make sure that the bit-fields are the same length.
6992 unsigned Bits1 = Field1->getBitWidthValue(C);
6993 unsigned Bits2 = Field2->getBitWidthValue(C);
6994
6995 if (Bits1 != Bits2)
6996 return false;
6997 }
6998
6999 return true;
7000}
7001
7002/// \brief Check if two standard-layout structs are layout-compatible.
7003/// (C++11 [class.mem] p17)
7004bool isLayoutCompatibleStruct(ASTContext &C,
7005 RecordDecl *RD1,
7006 RecordDecl *RD2) {
7007 // If both records are C++ classes, check that base classes match.
7008 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
7009 // If one of records is a CXXRecordDecl we are in C++ mode,
7010 // thus the other one is a CXXRecordDecl, too.
7011 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
7012 // Check number of base classes.
7013 if (D1CXX->getNumBases() != D2CXX->getNumBases())
7014 return false;
7015
7016 // Check the base classes.
7017 for (CXXRecordDecl::base_class_const_iterator
7018 Base1 = D1CXX->bases_begin(),
7019 BaseEnd1 = D1CXX->bases_end(),
7020 Base2 = D2CXX->bases_begin();
7021 Base1 != BaseEnd1;
7022 ++Base1, ++Base2) {
7023 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
7024 return false;
7025 }
7026 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
7027 // If only RD2 is a C++ class, it should have zero base classes.
7028 if (D2CXX->getNumBases() > 0)
7029 return false;
7030 }
7031
7032 // Check the fields.
7033 RecordDecl::field_iterator Field2 = RD2->field_begin(),
7034 Field2End = RD2->field_end(),
7035 Field1 = RD1->field_begin(),
7036 Field1End = RD1->field_end();
7037 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
7038 if (!isLayoutCompatible(C, *Field1, *Field2))
7039 return false;
7040 }
7041 if (Field1 != Field1End || Field2 != Field2End)
7042 return false;
7043
7044 return true;
7045}
7046
7047/// \brief Check if two standard-layout unions are layout-compatible.
7048/// (C++11 [class.mem] p18)
7049bool isLayoutCompatibleUnion(ASTContext &C,
7050 RecordDecl *RD1,
7051 RecordDecl *RD2) {
7052 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
7053 for (RecordDecl::field_iterator Field2 = RD2->field_begin(),
7054 Field2End = RD2->field_end();
7055 Field2 != Field2End; ++Field2) {
7056 UnmatchedFields.insert(*Field2);
7057 }
7058
7059 for (RecordDecl::field_iterator Field1 = RD1->field_begin(),
7060 Field1End = RD1->field_end();
7061 Field1 != Field1End; ++Field1) {
7062 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
7063 I = UnmatchedFields.begin(),
7064 E = UnmatchedFields.end();
7065
7066 for ( ; I != E; ++I) {
7067 if (isLayoutCompatible(C, *Field1, *I)) {
7068 bool Result = UnmatchedFields.erase(*I);
7069 (void) Result;
7070 assert(Result);
7071 break;
7072 }
7073 }
7074 if (I == E)
7075 return false;
7076 }
7077
7078 return UnmatchedFields.empty();
7079}
7080
7081bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
7082 if (RD1->isUnion() != RD2->isUnion())
7083 return false;
7084
7085 if (RD1->isUnion())
7086 return isLayoutCompatibleUnion(C, RD1, RD2);
7087 else
7088 return isLayoutCompatibleStruct(C, RD1, RD2);
7089}
7090
7091/// \brief Check if two types are layout-compatible in C++11 sense.
7092bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
7093 if (T1.isNull() || T2.isNull())
7094 return false;
7095
7096 // C++11 [basic.types] p11:
7097 // If two types T1 and T2 are the same type, then T1 and T2 are
7098 // layout-compatible types.
7099 if (C.hasSameType(T1, T2))
7100 return true;
7101
7102 T1 = T1.getCanonicalType().getUnqualifiedType();
7103 T2 = T2.getCanonicalType().getUnqualifiedType();
7104
7105 const Type::TypeClass TC1 = T1->getTypeClass();
7106 const Type::TypeClass TC2 = T2->getTypeClass();
7107
7108 if (TC1 != TC2)
7109 return false;
7110
7111 if (TC1 == Type::Enum) {
7112 return isLayoutCompatible(C,
7113 cast<EnumType>(T1)->getDecl(),
7114 cast<EnumType>(T2)->getDecl());
7115 } else if (TC1 == Type::Record) {
7116 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
7117 return false;
7118
7119 return isLayoutCompatible(C,
7120 cast<RecordType>(T1)->getDecl(),
7121 cast<RecordType>(T2)->getDecl());
7122 }
7123
7124 return false;
7125}
7126}
7127
7128//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
7129
7130namespace {
7131/// \brief Given a type tag expression find the type tag itself.
7132///
7133/// \param TypeExpr Type tag expression, as it appears in user's code.
7134///
7135/// \param VD Declaration of an identifier that appears in a type tag.
7136///
7137/// \param MagicValue Type tag magic value.
7138bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
7139 const ValueDecl **VD, uint64_t *MagicValue) {
7140 while(true) {
7141 if (!TypeExpr)
7142 return false;
7143
7144 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
7145
7146 switch (TypeExpr->getStmtClass()) {
7147 case Stmt::UnaryOperatorClass: {
7148 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
7149 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
7150 TypeExpr = UO->getSubExpr();
7151 continue;
7152 }
7153 return false;
7154 }
7155
7156 case Stmt::DeclRefExprClass: {
7157 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
7158 *VD = DRE->getDecl();
7159 return true;
7160 }
7161
7162 case Stmt::IntegerLiteralClass: {
7163 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
7164 llvm::APInt MagicValueAPInt = IL->getValue();
7165 if (MagicValueAPInt.getActiveBits() <= 64) {
7166 *MagicValue = MagicValueAPInt.getZExtValue();
7167 return true;
7168 } else
7169 return false;
7170 }
7171
7172 case Stmt::BinaryConditionalOperatorClass:
7173 case Stmt::ConditionalOperatorClass: {
7174 const AbstractConditionalOperator *ACO =
7175 cast<AbstractConditionalOperator>(TypeExpr);
7176 bool Result;
7177 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
7178 if (Result)
7179 TypeExpr = ACO->getTrueExpr();
7180 else
7181 TypeExpr = ACO->getFalseExpr();
7182 continue;
7183 }
7184 return false;
7185 }
7186
7187 case Stmt::BinaryOperatorClass: {
7188 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
7189 if (BO->getOpcode() == BO_Comma) {
7190 TypeExpr = BO->getRHS();
7191 continue;
7192 }
7193 return false;
7194 }
7195
7196 default:
7197 return false;
7198 }
7199 }
7200}
7201
7202/// \brief Retrieve the C type corresponding to type tag TypeExpr.
7203///
7204/// \param TypeExpr Expression that specifies a type tag.
7205///
7206/// \param MagicValues Registered magic values.
7207///
7208/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
7209/// kind.
7210///
7211/// \param TypeInfo Information about the corresponding C type.
7212///
7213/// \returns true if the corresponding C type was found.
7214bool GetMatchingCType(
7215 const IdentifierInfo *ArgumentKind,
7216 const Expr *TypeExpr, const ASTContext &Ctx,
7217 const llvm::DenseMap<Sema::TypeTagMagicValue,
7218 Sema::TypeTagData> *MagicValues,
7219 bool &FoundWrongKind,
7220 Sema::TypeTagData &TypeInfo) {
7221 FoundWrongKind = false;
7222
7223 // Variable declaration that has type_tag_for_datatype attribute.
7224 const ValueDecl *VD = NULL;
7225
7226 uint64_t MagicValue;
7227
7228 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
7229 return false;
7230
7231 if (VD) {
7232 for (specific_attr_iterator<TypeTagForDatatypeAttr>
7233 I = VD->specific_attr_begin<TypeTagForDatatypeAttr>(),
7234 E = VD->specific_attr_end<TypeTagForDatatypeAttr>();
7235 I != E; ++I) {
7236 if (I->getArgumentKind() != ArgumentKind) {
7237 FoundWrongKind = true;
7238 return false;
7239 }
7240 TypeInfo.Type = I->getMatchingCType();
7241 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
7242 TypeInfo.MustBeNull = I->getMustBeNull();
7243 return true;
7244 }
7245 return false;
7246 }
7247
7248 if (!MagicValues)
7249 return false;
7250
7251 llvm::DenseMap<Sema::TypeTagMagicValue,
7252 Sema::TypeTagData>::const_iterator I =
7253 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
7254 if (I == MagicValues->end())
7255 return false;
7256
7257 TypeInfo = I->second;
7258 return true;
7259}
7260} // unnamed namespace
7261
7262void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
7263 uint64_t MagicValue, QualType Type,
7264 bool LayoutCompatible,
7265 bool MustBeNull) {
7266 if (!TypeTagForDatatypeMagicValues)
7267 TypeTagForDatatypeMagicValues.reset(
7268 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
7269
7270 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
7271 (*TypeTagForDatatypeMagicValues)[Magic] =
7272 TypeTagData(Type, LayoutCompatible, MustBeNull);
7273}
7274
7275namespace {
7276bool IsSameCharType(QualType T1, QualType T2) {
7277 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
7278 if (!BT1)
7279 return false;
7280
7281 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
7282 if (!BT2)
7283 return false;
7284
7285 BuiltinType::Kind T1Kind = BT1->getKind();
7286 BuiltinType::Kind T2Kind = BT2->getKind();
7287
7288 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
7289 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
7290 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
7291 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
7292}
7293} // unnamed namespace
7294
7295void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
7296 const Expr * const *ExprArgs) {
7297 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
7298 bool IsPointerAttr = Attr->getIsPointer();
7299
7300 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
7301 bool FoundWrongKind;
7302 TypeTagData TypeInfo;
7303 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
7304 TypeTagForDatatypeMagicValues.get(),
7305 FoundWrongKind, TypeInfo)) {
7306 if (FoundWrongKind)
7307 Diag(TypeTagExpr->getExprLoc(),
7308 diag::warn_type_tag_for_datatype_wrong_kind)
7309 << TypeTagExpr->getSourceRange();
7310 return;
7311 }
7312
7313 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
7314 if (IsPointerAttr) {
7315 // Skip implicit cast of pointer to `void *' (as a function argument).
7316 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5a249802012-11-03 16:07:49 +00007317 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkob57ce4e2012-11-03 22:10:18 +00007318 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00007319 ArgumentExpr = ICE->getSubExpr();
7320 }
7321 QualType ArgumentType = ArgumentExpr->getType();
7322
7323 // Passing a `void*' pointer shouldn't trigger a warning.
7324 if (IsPointerAttr && ArgumentType->isVoidPointerType())
7325 return;
7326
7327 if (TypeInfo.MustBeNull) {
7328 // Type tag with matching void type requires a null pointer.
7329 if (!ArgumentExpr->isNullPointerConstant(Context,
7330 Expr::NPC_ValueDependentIsNotNull)) {
7331 Diag(ArgumentExpr->getExprLoc(),
7332 diag::warn_type_safety_null_pointer_required)
7333 << ArgumentKind->getName()
7334 << ArgumentExpr->getSourceRange()
7335 << TypeTagExpr->getSourceRange();
7336 }
7337 return;
7338 }
7339
7340 QualType RequiredType = TypeInfo.Type;
7341 if (IsPointerAttr)
7342 RequiredType = Context.getPointerType(RequiredType);
7343
7344 bool mismatch = false;
7345 if (!TypeInfo.LayoutCompatible) {
7346 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
7347
7348 // C++11 [basic.fundamental] p1:
7349 // Plain char, signed char, and unsigned char are three distinct types.
7350 //
7351 // But we treat plain `char' as equivalent to `signed char' or `unsigned
7352 // char' depending on the current char signedness mode.
7353 if (mismatch)
7354 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
7355 RequiredType->getPointeeType())) ||
7356 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
7357 mismatch = false;
7358 } else
7359 if (IsPointerAttr)
7360 mismatch = !isLayoutCompatible(Context,
7361 ArgumentType->getPointeeType(),
7362 RequiredType->getPointeeType());
7363 else
7364 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
7365
7366 if (mismatch)
7367 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
7368 << ArgumentType << ArgumentKind->getName()
7369 << TypeInfo.LayoutCompatible << RequiredType
7370 << ArgumentExpr->getSourceRange()
7371 << TypeTagExpr->getSourceRange();
7372}