blob: 27cc8a37a5b1e83d678e95d43034f2b9c5814f97 [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"
Stephen Hines651f13c2014-04-23 16:59:28 -070035#include "llvm/ADT/STLExtras.h"
Richard Smith0e218972013-08-05 18:49:43 +000036#include "llvm/ADT/SmallBitVector.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000037#include "llvm/ADT/SmallString.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:
Stephen Hines651f13c2014-04-23 16:59:28 -0700145 case Builtin::BI__va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000146 if (SemaBuiltinVAStart(TheCall))
147 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000148 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000149 case Builtin::BI__builtin_isgreater:
150 case Builtin::BI__builtin_isgreaterequal:
151 case Builtin::BI__builtin_isless:
152 case Builtin::BI__builtin_islessequal:
153 case Builtin::BI__builtin_islessgreater:
154 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000155 if (SemaBuiltinUnorderedCompare(TheCall))
156 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000157 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000158 case Builtin::BI__builtin_fpclassify:
159 if (SemaBuiltinFPClassification(TheCall, 6))
160 return ExprError();
161 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000162 case Builtin::BI__builtin_isfinite:
163 case Builtin::BI__builtin_isinf:
164 case Builtin::BI__builtin_isinf_sign:
165 case Builtin::BI__builtin_isnan:
166 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000167 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000168 return ExprError();
169 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000170 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000171 return SemaBuiltinShuffleVector(TheCall);
172 // TheCall will be freed by the smart pointer here, but that's fine, since
173 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000174 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000175 if (SemaBuiltinPrefetch(TheCall))
176 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000177 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000178 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000179 if (SemaBuiltinObjectSize(TheCall))
180 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000181 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000182 case Builtin::BI__builtin_longjmp:
183 if (SemaBuiltinLongjmp(TheCall))
184 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000185 break;
John McCall8e10f3b2011-02-26 05:39:39 +0000186
187 case Builtin::BI__builtin_classify_type:
188 if (checkArgCount(*this, TheCall, 1)) return true;
189 TheCall->setType(Context.IntTy);
190 break;
Chris Lattner75c29a02010-10-12 17:47:42 +0000191 case Builtin::BI__builtin_constant_p:
John McCall8e10f3b2011-02-26 05:39:39 +0000192 if (checkArgCount(*this, TheCall, 1)) return true;
193 TheCall->setType(Context.IntTy);
Chris Lattner75c29a02010-10-12 17:47:42 +0000194 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000195 case Builtin::BI__sync_fetch_and_add:
Douglas Gregora9766412011-11-28 16:30:08 +0000196 case Builtin::BI__sync_fetch_and_add_1:
197 case Builtin::BI__sync_fetch_and_add_2:
198 case Builtin::BI__sync_fetch_and_add_4:
199 case Builtin::BI__sync_fetch_and_add_8:
200 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000201 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregora9766412011-11-28 16:30:08 +0000202 case Builtin::BI__sync_fetch_and_sub_1:
203 case Builtin::BI__sync_fetch_and_sub_2:
204 case Builtin::BI__sync_fetch_and_sub_4:
205 case Builtin::BI__sync_fetch_and_sub_8:
206 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000207 case Builtin::BI__sync_fetch_and_or:
Douglas Gregora9766412011-11-28 16:30:08 +0000208 case Builtin::BI__sync_fetch_and_or_1:
209 case Builtin::BI__sync_fetch_and_or_2:
210 case Builtin::BI__sync_fetch_and_or_4:
211 case Builtin::BI__sync_fetch_and_or_8:
212 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000213 case Builtin::BI__sync_fetch_and_and:
Douglas Gregora9766412011-11-28 16:30:08 +0000214 case Builtin::BI__sync_fetch_and_and_1:
215 case Builtin::BI__sync_fetch_and_and_2:
216 case Builtin::BI__sync_fetch_and_and_4:
217 case Builtin::BI__sync_fetch_and_and_8:
218 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000219 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregora9766412011-11-28 16:30:08 +0000220 case Builtin::BI__sync_fetch_and_xor_1:
221 case Builtin::BI__sync_fetch_and_xor_2:
222 case Builtin::BI__sync_fetch_and_xor_4:
223 case Builtin::BI__sync_fetch_and_xor_8:
224 case Builtin::BI__sync_fetch_and_xor_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000225 case Builtin::BI__sync_add_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000226 case Builtin::BI__sync_add_and_fetch_1:
227 case Builtin::BI__sync_add_and_fetch_2:
228 case Builtin::BI__sync_add_and_fetch_4:
229 case Builtin::BI__sync_add_and_fetch_8:
230 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000231 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000232 case Builtin::BI__sync_sub_and_fetch_1:
233 case Builtin::BI__sync_sub_and_fetch_2:
234 case Builtin::BI__sync_sub_and_fetch_4:
235 case Builtin::BI__sync_sub_and_fetch_8:
236 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000237 case Builtin::BI__sync_and_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000238 case Builtin::BI__sync_and_and_fetch_1:
239 case Builtin::BI__sync_and_and_fetch_2:
240 case Builtin::BI__sync_and_and_fetch_4:
241 case Builtin::BI__sync_and_and_fetch_8:
242 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000243 case Builtin::BI__sync_or_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000244 case Builtin::BI__sync_or_and_fetch_1:
245 case Builtin::BI__sync_or_and_fetch_2:
246 case Builtin::BI__sync_or_and_fetch_4:
247 case Builtin::BI__sync_or_and_fetch_8:
248 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000249 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000250 case Builtin::BI__sync_xor_and_fetch_1:
251 case Builtin::BI__sync_xor_and_fetch_2:
252 case Builtin::BI__sync_xor_and_fetch_4:
253 case Builtin::BI__sync_xor_and_fetch_8:
254 case Builtin::BI__sync_xor_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000255 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000256 case Builtin::BI__sync_val_compare_and_swap_1:
257 case Builtin::BI__sync_val_compare_and_swap_2:
258 case Builtin::BI__sync_val_compare_and_swap_4:
259 case Builtin::BI__sync_val_compare_and_swap_8:
260 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000261 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000262 case Builtin::BI__sync_bool_compare_and_swap_1:
263 case Builtin::BI__sync_bool_compare_and_swap_2:
264 case Builtin::BI__sync_bool_compare_and_swap_4:
265 case Builtin::BI__sync_bool_compare_and_swap_8:
266 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000267 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregora9766412011-11-28 16:30:08 +0000268 case Builtin::BI__sync_lock_test_and_set_1:
269 case Builtin::BI__sync_lock_test_and_set_2:
270 case Builtin::BI__sync_lock_test_and_set_4:
271 case Builtin::BI__sync_lock_test_and_set_8:
272 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000273 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +0000274 case Builtin::BI__sync_lock_release_1:
275 case Builtin::BI__sync_lock_release_2:
276 case Builtin::BI__sync_lock_release_4:
277 case Builtin::BI__sync_lock_release_8:
278 case Builtin::BI__sync_lock_release_16:
Chris Lattner23aa9c82011-04-09 03:57:26 +0000279 case Builtin::BI__sync_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000280 case Builtin::BI__sync_swap_1:
281 case Builtin::BI__sync_swap_2:
282 case Builtin::BI__sync_swap_4:
283 case Builtin::BI__sync_swap_8:
284 case Builtin::BI__sync_swap_16:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000285 return SemaBuiltinAtomicOverloaded(TheCallResult);
Richard Smithff34d402012-04-12 05:08:17 +0000286#define BUILTIN(ID, TYPE, ATTRS)
287#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
288 case Builtin::BI##ID: \
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000289 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithff34d402012-04-12 05:08:17 +0000290#include "clang/Basic/Builtins.def"
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000291 case Builtin::BI__builtin_annotation:
Julien Lerougee5939212012-04-28 17:39:16 +0000292 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000293 return ExprError();
294 break;
Richard Smith5154dce2013-07-11 02:27:57 +0000295 case Builtin::BI__builtin_addressof:
296 if (SemaBuiltinAddressof(*this, TheCall))
297 return ExprError();
298 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000299 }
300
301 // Since the target specific builtins for each arch overlap, only check those
302 // of the arch we are compiling for.
303 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000304 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman26a31422010-06-08 02:47:44 +0000305 case llvm::Triple::arm:
Stephen Hines651f13c2014-04-23 16:59:28 -0700306 case llvm::Triple::armeb:
Nate Begeman26a31422010-06-08 02:47:44 +0000307 case llvm::Triple::thumb:
Stephen Hines651f13c2014-04-23 16:59:28 -0700308 case llvm::Triple::thumbeb:
Nate Begeman26a31422010-06-08 02:47:44 +0000309 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
310 return ExprError();
311 break;
Stephen Hines651f13c2014-04-23 16:59:28 -0700312 case llvm::Triple::arm64:
313 if (CheckARM64BuiltinFunctionCall(BuiltinID, TheCall))
314 return ExprError();
315 break;
Tim Northoverb793f0d2013-08-01 09:23:19 +0000316 case llvm::Triple::aarch64:
Stephen Hines651f13c2014-04-23 16:59:28 -0700317 case llvm::Triple::aarch64_be:
Tim Northoverb793f0d2013-08-01 09:23:19 +0000318 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
319 return ExprError();
320 break;
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000321 case llvm::Triple::mips:
322 case llvm::Triple::mipsel:
323 case llvm::Triple::mips64:
324 case llvm::Triple::mips64el:
325 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
326 return ExprError();
327 break;
Stephen Hines651f13c2014-04-23 16:59:28 -0700328 case llvm::Triple::x86:
329 case llvm::Triple::x86_64:
330 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
331 return ExprError();
332 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000333 default:
334 break;
335 }
336 }
337
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000338 return TheCallResult;
Nate Begeman26a31422010-06-08 02:47:44 +0000339}
340
Nate Begeman61eecf52010-06-14 05:21:25 +0000341// Get the valid immediate range for the specified NEON type code.
Stephen Hines651f13c2014-04-23 16:59:28 -0700342static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilsonda95f732011-11-08 01:16:11 +0000343 NeonTypeFlags Type(t);
Stephen Hines651f13c2014-04-23 16:59:28 -0700344 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilsonda95f732011-11-08 01:16:11 +0000345 switch (Type.getEltType()) {
346 case NeonTypeFlags::Int8:
347 case NeonTypeFlags::Poly8:
348 return shift ? 7 : (8 << IsQuad) - 1;
349 case NeonTypeFlags::Int16:
350 case NeonTypeFlags::Poly16:
351 return shift ? 15 : (4 << IsQuad) - 1;
352 case NeonTypeFlags::Int32:
353 return shift ? 31 : (2 << IsQuad) - 1;
354 case NeonTypeFlags::Int64:
Kevin Qin624bb5e2013-11-14 03:29:16 +0000355 case NeonTypeFlags::Poly64:
Bob Wilsonda95f732011-11-08 01:16:11 +0000356 return shift ? 63 : (1 << IsQuad) - 1;
Stephen Hines651f13c2014-04-23 16:59:28 -0700357 case NeonTypeFlags::Poly128:
358 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilsonda95f732011-11-08 01:16:11 +0000359 case NeonTypeFlags::Float16:
360 assert(!shift && "cannot shift float types!");
361 return (4 << IsQuad) - 1;
362 case NeonTypeFlags::Float32:
363 assert(!shift && "cannot shift float types!");
364 return (2 << IsQuad) - 1;
Tim Northoverb793f0d2013-08-01 09:23:19 +0000365 case NeonTypeFlags::Float64:
366 assert(!shift && "cannot shift float types!");
367 return (1 << IsQuad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000368 }
David Blaikie7530c032012-01-17 06:56:22 +0000369 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman61eecf52010-06-14 05:21:25 +0000370}
371
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000372/// getNeonEltType - Return the QualType corresponding to the elements of
373/// the vector type specified by the NeonTypeFlags. This is used to check
374/// the pointer arguments for Neon load/store intrinsics.
Kevin Qin624bb5e2013-11-14 03:29:16 +0000375static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Stephen Hines651f13c2014-04-23 16:59:28 -0700376 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000377 switch (Flags.getEltType()) {
378 case NeonTypeFlags::Int8:
379 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
380 case NeonTypeFlags::Int16:
381 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
382 case NeonTypeFlags::Int32:
383 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
384 case NeonTypeFlags::Int64:
Stephen Hines651f13c2014-04-23 16:59:28 -0700385 if (IsInt64Long)
386 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
387 else
388 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
389 : Context.LongLongTy;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000390 case NeonTypeFlags::Poly8:
Stephen Hines651f13c2014-04-23 16:59:28 -0700391 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000392 case NeonTypeFlags::Poly16:
Stephen Hines651f13c2014-04-23 16:59:28 -0700393 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qin624bb5e2013-11-14 03:29:16 +0000394 case NeonTypeFlags::Poly64:
Stephen Hines651f13c2014-04-23 16:59:28 -0700395 return Context.UnsignedLongTy;
396 case NeonTypeFlags::Poly128:
397 break;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000398 case NeonTypeFlags::Float16:
Kevin Qin624bb5e2013-11-14 03:29:16 +0000399 return Context.HalfTy;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000400 case NeonTypeFlags::Float32:
401 return Context.FloatTy;
Tim Northoverb793f0d2013-08-01 09:23:19 +0000402 case NeonTypeFlags::Float64:
403 return Context.DoubleTy;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000404 }
David Blaikie7530c032012-01-17 06:56:22 +0000405 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000406}
407
Stephen Hines651f13c2014-04-23 16:59:28 -0700408bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northoverb793f0d2013-08-01 09:23:19 +0000409 llvm::APSInt Result;
Tim Northoverb793f0d2013-08-01 09:23:19 +0000410 uint64_t mask = 0;
411 unsigned TV = 0;
412 int PtrArgNum = -1;
413 bool HasConstPtr = false;
414 switch (BuiltinID) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700415#define GET_NEON_OVERLOAD_CHECK
Tim Northoverb793f0d2013-08-01 09:23:19 +0000416#include "clang/Basic/arm_neon.inc"
Stephen Hines651f13c2014-04-23 16:59:28 -0700417#undef GET_NEON_OVERLOAD_CHECK
Tim Northoverb793f0d2013-08-01 09:23:19 +0000418 }
419
420 // For NEON intrinsics which are overloaded on vector element type, validate
421 // the immediate which specifies which variant to emit.
Stephen Hines651f13c2014-04-23 16:59:28 -0700422 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northoverb793f0d2013-08-01 09:23:19 +0000423 if (mask) {
424 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
425 return true;
426
427 TV = Result.getLimitedValue(64);
428 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
429 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Stephen Hines651f13c2014-04-23 16:59:28 -0700430 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northoverb793f0d2013-08-01 09:23:19 +0000431 }
432
433 if (PtrArgNum >= 0) {
434 // Check that pointer arguments have the specified type.
435 Expr *Arg = TheCall->getArg(PtrArgNum);
436 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
437 Arg = ICE->getSubExpr();
438 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
439 QualType RHSTy = RHS.get()->getType();
Stephen Hines651f13c2014-04-23 16:59:28 -0700440
441 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
442 bool IsPolyUnsigned =
443 Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::arm64;
444 bool IsInt64Long =
445 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
446 QualType EltTy =
447 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northoverb793f0d2013-08-01 09:23:19 +0000448 if (HasConstPtr)
449 EltTy = EltTy.withConst();
450 QualType LHSTy = Context.getPointerType(EltTy);
451 AssignConvertType ConvTy;
452 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
453 if (RHS.isInvalid())
454 return true;
455 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
456 RHS.get(), AA_Assigning))
457 return true;
458 }
459
460 // For NEON intrinsics which take an immediate value as part of the
461 // instruction, range check them here.
462 unsigned i = 0, l = 0, u = 0;
463 switch (BuiltinID) {
464 default:
465 return false;
Stephen Hines651f13c2014-04-23 16:59:28 -0700466#define GET_NEON_IMMEDIATE_CHECK
Tim Northoverb793f0d2013-08-01 09:23:19 +0000467#include "clang/Basic/arm_neon.inc"
Stephen Hines651f13c2014-04-23 16:59:28 -0700468#undef GET_NEON_IMMEDIATE_CHECK
Tim Northoverb793f0d2013-08-01 09:23:19 +0000469 }
470 ;
471
472 // We can't check the value of a dependent argument.
473 if (TheCall->getArg(i)->isTypeDependent() ||
474 TheCall->getArg(i)->isValueDependent())
475 return false;
476
477 // Check that the immediate argument is actually a constant.
478 if (SemaBuiltinConstantArg(TheCall, i, Result))
479 return true;
480
481 // Range check against the upper/lower values for this isntruction.
482 unsigned Val = Result.getZExtValue();
483 if (Val < l || Val > (u + l))
484 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
485 << l << u + l << TheCall->getArg(i)->getSourceRange();
486
487 return false;
488}
489
Stephen Hines651f13c2014-04-23 16:59:28 -0700490bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
491 CallExpr *TheCall) {
492 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
493 return true;
494
495 return false;
496}
497
498bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
499 unsigned MaxWidth) {
Tim Northover09df2b02013-07-16 09:47:53 +0000500 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Stephen Hines651f13c2014-04-23 16:59:28 -0700501 BuiltinID == ARM::BI__builtin_arm_strex ||
502 BuiltinID == ARM64::BI__builtin_arm_ldrex ||
503 BuiltinID == ARM64::BI__builtin_arm_strex) &&
Tim Northover09df2b02013-07-16 09:47:53 +0000504 "unexpected ARM builtin");
Stephen Hines651f13c2014-04-23 16:59:28 -0700505 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
506 BuiltinID == ARM64::BI__builtin_arm_ldrex;
Tim Northover09df2b02013-07-16 09:47:53 +0000507
508 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
509
510 // Ensure that we have the proper number of arguments.
511 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
512 return true;
513
514 // Inspect the pointer argument of the atomic builtin. This should always be
515 // a pointer type, whose element is an integral scalar or pointer type.
516 // Because it is a pointer type, we don't have to worry about any implicit
517 // casts here.
518 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
519 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
520 if (PointerArgRes.isInvalid())
521 return true;
522 PointerArg = PointerArgRes.take();
523
524 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
525 if (!pointerType) {
526 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
527 << PointerArg->getType() << PointerArg->getSourceRange();
528 return true;
529 }
530
531 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
532 // task is to insert the appropriate casts into the AST. First work out just
533 // what the appropriate type is.
534 QualType ValType = pointerType->getPointeeType();
535 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
536 if (IsLdrex)
537 AddrType.addConst();
538
539 // Issue a warning if the cast is dodgy.
540 CastKind CastNeeded = CK_NoOp;
541 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
542 CastNeeded = CK_BitCast;
543 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
544 << PointerArg->getType()
545 << Context.getPointerType(AddrType)
546 << AA_Passing << PointerArg->getSourceRange();
547 }
548
549 // Finally, do the cast and replace the argument with the corrected version.
550 AddrType = Context.getPointerType(AddrType);
551 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
552 if (PointerArgRes.isInvalid())
553 return true;
554 PointerArg = PointerArgRes.take();
555
556 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
557
558 // In general, we allow ints, floats and pointers to be loaded and stored.
559 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
560 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
561 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
562 << PointerArg->getType() << PointerArg->getSourceRange();
563 return true;
564 }
565
566 // But ARM doesn't have instructions to deal with 128-bit versions.
Stephen Hines651f13c2014-04-23 16:59:28 -0700567 if (Context.getTypeSize(ValType) > MaxWidth) {
568 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover09df2b02013-07-16 09:47:53 +0000569 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
570 << PointerArg->getType() << PointerArg->getSourceRange();
571 return true;
572 }
573
574 switch (ValType.getObjCLifetime()) {
575 case Qualifiers::OCL_None:
576 case Qualifiers::OCL_ExplicitNone:
577 // okay
578 break;
579
580 case Qualifiers::OCL_Weak:
581 case Qualifiers::OCL_Strong:
582 case Qualifiers::OCL_Autoreleasing:
583 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
584 << ValType << PointerArg->getSourceRange();
585 return true;
586 }
587
588
589 if (IsLdrex) {
590 TheCall->setType(ValType);
591 return false;
592 }
593
594 // Initialize the argument to be stored.
595 ExprResult ValArg = TheCall->getArg(0);
596 InitializedEntity Entity = InitializedEntity::InitializeParameter(
597 Context, ValType, /*consume*/ false);
598 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
599 if (ValArg.isInvalid())
600 return true;
Tim Northover09df2b02013-07-16 09:47:53 +0000601 TheCall->setArg(0, ValArg.get());
Tim Northovera6306fc2013-10-29 12:32:58 +0000602
603 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
604 // but the custom checker bypasses all default analysis.
605 TheCall->setType(Context.IntTy);
Tim Northover09df2b02013-07-16 09:47:53 +0000606 return false;
607}
608
Nate Begeman26a31422010-06-08 02:47:44 +0000609bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000610 llvm::APSInt Result;
611
Tim Northover09df2b02013-07-16 09:47:53 +0000612 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
613 BuiltinID == ARM::BI__builtin_arm_strex) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700614 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover09df2b02013-07-16 09:47:53 +0000615 }
616
Stephen Hines651f13c2014-04-23 16:59:28 -0700617 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
618 return true;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000619
Stephen Hines651f13c2014-04-23 16:59:28 -0700620 // For NEON intrinsics which take an immediate value as part of the
Nate Begeman0d15c532010-06-13 04:47:52 +0000621 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000622 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000623 switch (BuiltinID) {
624 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000625 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
626 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000627 case ARM::BI__builtin_arm_vcvtr_f:
628 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao186b26d2013-11-12 21:42:50 +0000629 case ARM::BI__builtin_arm_dmb:
630 case ARM::BI__builtin_arm_dsb: l = 0; u = 15; break;
Nate Begeman0d15c532010-06-13 04:47:52 +0000631 };
632
Douglas Gregor592a4232012-06-29 01:05:22 +0000633 // We can't check the value of a dependent argument.
634 if (TheCall->getArg(i)->isTypeDependent() ||
635 TheCall->getArg(i)->isValueDependent())
636 return false;
637
Nate Begeman61eecf52010-06-14 05:21:25 +0000638 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000639 if (SemaBuiltinConstantArg(TheCall, i, Result))
640 return true;
641
Nate Begeman61eecf52010-06-14 05:21:25 +0000642 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000643 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000644 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000645 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000646 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000647
Nate Begeman99c40bb2010-08-03 21:32:34 +0000648 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000649 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000650}
Daniel Dunbarde454282008-10-02 18:44:07 +0000651
Stephen Hines651f13c2014-04-23 16:59:28 -0700652bool Sema::CheckARM64BuiltinFunctionCall(unsigned BuiltinID,
653 CallExpr *TheCall) {
654 llvm::APSInt Result;
655
656 if (BuiltinID == ARM64::BI__builtin_arm_ldrex ||
657 BuiltinID == ARM64::BI__builtin_arm_strex) {
658 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
659 }
660
661 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
662 return true;
663
664 return false;
665}
666
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000667bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
668 unsigned i = 0, l = 0, u = 0;
669 switch (BuiltinID) {
670 default: return false;
671 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
672 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyanbe22cb82012-08-27 12:29:20 +0000673 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
674 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
675 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
676 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
677 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000678 };
679
680 // We can't check the value of a dependent argument.
681 if (TheCall->getArg(i)->isTypeDependent() ||
682 TheCall->getArg(i)->isValueDependent())
683 return false;
684
685 // Check that the immediate argument is actually a constant.
686 llvm::APSInt Result;
687 if (SemaBuiltinConstantArg(TheCall, i, Result))
688 return true;
689
690 // Range check against the upper/lower values for this instruction.
691 unsigned Val = Result.getZExtValue();
692 if (Val < l || Val > u)
693 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
694 << l << u << TheCall->getArg(i)->getSourceRange();
695
696 return false;
697}
698
Stephen Hines651f13c2014-04-23 16:59:28 -0700699bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
700 switch (BuiltinID) {
701 case X86::BI_mm_prefetch:
702 return SemaBuiltinMMPrefetch(TheCall);
703 }
704 return false;
705}
706
Richard Smith831421f2012-06-25 20:30:08 +0000707/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
708/// parameter with the FormatAttr's correct format_idx and firstDataArg.
709/// Returns true when the format fits the function and the FormatStringInfo has
710/// been populated.
711bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
712 FormatStringInfo *FSI) {
713 FSI->HasVAListArg = Format->getFirstArg() == 0;
714 FSI->FormatIdx = Format->getFormatIdx() - 1;
715 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssond406bf02009-08-16 01:56:34 +0000716
Richard Smith831421f2012-06-25 20:30:08 +0000717 // The way the format attribute works in GCC, the implicit this argument
718 // of member functions is counted. However, it doesn't appear in our own
719 // lists, so decrement format_idx in that case.
720 if (IsCXXMember) {
721 if(FSI->FormatIdx == 0)
722 return false;
723 --FSI->FormatIdx;
724 if (FSI->FirstDataArg != 0)
725 --FSI->FirstDataArg;
726 }
727 return true;
728}
Mike Stump1eb44332009-09-09 15:08:12 +0000729
Stephen Hines651f13c2014-04-23 16:59:28 -0700730/// Checks if a the given expression evaluates to null.
731///
732/// \brief Returns true if the value evaluates to null.
733static bool CheckNonNullExpr(Sema &S,
734 const Expr *Expr) {
735 // As a special case, transparent unions initialized with zero are
736 // considered null for the purposes of the nonnull attribute.
737 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
738 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
739 if (const CompoundLiteralExpr *CLE =
740 dyn_cast<CompoundLiteralExpr>(Expr))
741 if (const InitListExpr *ILE =
742 dyn_cast<InitListExpr>(CLE->getInitializer()))
743 Expr = ILE->getInit(0);
744 }
745
746 bool Result;
747 return (!Expr->isValueDependent() &&
748 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
749 !Result);
750}
751
752static void CheckNonNullArgument(Sema &S,
753 const Expr *ArgExpr,
754 SourceLocation CallSiteLoc) {
755 if (CheckNonNullExpr(S, ArgExpr))
756 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
757}
758
759static void CheckNonNullArguments(Sema &S,
760 const NamedDecl *FDecl,
761 const Expr * const *ExprArgs,
762 SourceLocation CallSiteLoc) {
763 // Check the attributes attached to the method/function itself.
764 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
765 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
766 e = NonNull->args_end();
767 i != e; ++i) {
768 CheckNonNullArgument(S, ExprArgs[*i], CallSiteLoc);
769 }
770 }
771
772 // Check the attributes on the parameters.
773 ArrayRef<ParmVarDecl*> parms;
774 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
775 parms = FD->parameters();
776 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
777 parms = MD->parameters();
778
779 unsigned argIndex = 0;
780 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
781 I != E; ++I, ++argIndex) {
782 const ParmVarDecl *PVD = *I;
783 if (PVD->hasAttr<NonNullAttr>())
784 CheckNonNullArgument(S, ExprArgs[argIndex], CallSiteLoc);
785 }
786}
787
Richard Smith831421f2012-06-25 20:30:08 +0000788/// Handles the checks for format strings, non-POD arguments to vararg
789/// functions, and NULL arguments passed to non-NULL parameters.
Stephen Hines651f13c2014-04-23 16:59:28 -0700790void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
791 unsigned NumParams, bool IsMemberFunction,
792 SourceLocation Loc, SourceRange Range,
Richard Smith831421f2012-06-25 20:30:08 +0000793 VariadicCallType CallType) {
Richard Smith0e218972013-08-05 18:49:43 +0000794 // FIXME: We should check as much as we can in the template definition.
Jordan Rose66360e22012-10-02 01:49:54 +0000795 if (CurContext->isDependentContext())
796 return;
Daniel Dunbarde454282008-10-02 18:44:07 +0000797
Ted Kremenekc82faca2010-09-09 04:33:05 +0000798 // Printf and scanf checking.
Richard Smith0e218972013-08-05 18:49:43 +0000799 llvm::SmallBitVector CheckedVarArgs;
800 if (FDecl) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700801 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer541a28f2013-08-09 09:39:17 +0000802 // Only create vector if there are format attributes.
803 CheckedVarArgs.resize(Args.size());
804
Stephen Hines651f13c2014-04-23 16:59:28 -0700805 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramer47abb252013-08-08 11:08:26 +0000806 CheckedVarArgs);
Benjamin Kramer541a28f2013-08-09 09:39:17 +0000807 }
Richard Smith0e218972013-08-05 18:49:43 +0000808 }
Richard Smith831421f2012-06-25 20:30:08 +0000809
810 // Refuse POD arguments that weren't caught by the format string
811 // checks above.
Richard Smith0e218972013-08-05 18:49:43 +0000812 if (CallType != VariadicDoesNotApply) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700813 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek0234bfa2012-10-11 19:06:43 +0000814 // Args[ArgIdx] can be null in malformed code.
Richard Smith0e218972013-08-05 18:49:43 +0000815 if (const Expr *Arg = Args[ArgIdx]) {
816 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
817 checkVariadicArgument(Arg, CallType);
818 }
Ted Kremenek0234bfa2012-10-11 19:06:43 +0000819 }
Richard Smith0e218972013-08-05 18:49:43 +0000820 }
Mike Stump1eb44332009-09-09 15:08:12 +0000821
Richard Trieu0538f0e2013-06-22 00:20:41 +0000822 if (FDecl) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700823 CheckNonNullArguments(*this, FDecl, Args.data(), Loc);
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +0000824
Richard Trieu0538f0e2013-06-22 00:20:41 +0000825 // Type safety checking.
Stephen Hines651f13c2014-04-23 16:59:28 -0700826 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
827 CheckArgumentWithTypeTag(I, Args.data());
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +0000828 }
Richard Smith831421f2012-06-25 20:30:08 +0000829}
830
831/// CheckConstructorCall - Check a constructor call for correctness and safety
832/// properties not enforced by the C type system.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000833void Sema::CheckConstructorCall(FunctionDecl *FDecl,
834 ArrayRef<const Expr *> Args,
Richard Smith831421f2012-06-25 20:30:08 +0000835 const FunctionProtoType *Proto,
836 SourceLocation Loc) {
837 VariadicCallType CallType =
838 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Stephen Hines651f13c2014-04-23 16:59:28 -0700839 checkCall(FDecl, Args, Proto->getNumParams(),
Richard Smith831421f2012-06-25 20:30:08 +0000840 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
841}
842
843/// CheckFunctionCall - Check a direct function call for various correctness
844/// and safety properties not strictly enforced by the C type system.
845bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
846 const FunctionProtoType *Proto) {
Eli Friedman2edcde82012-10-11 00:30:58 +0000847 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
848 isa<CXXMethodDecl>(FDecl);
849 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
850 IsMemberOperatorCall;
Richard Smith831421f2012-06-25 20:30:08 +0000851 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
852 TheCall->getCallee());
Stephen Hines651f13c2014-04-23 16:59:28 -0700853 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Eli Friedman2edcde82012-10-11 00:30:58 +0000854 Expr** Args = TheCall->getArgs();
855 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmandf75b0c2012-10-11 00:34:15 +0000856 if (IsMemberOperatorCall) {
Eli Friedman2edcde82012-10-11 00:30:58 +0000857 // If this is a call to a member operator, hide the first argument
858 // from checkCall.
859 // FIXME: Our choice of AST representation here is less than ideal.
860 ++Args;
861 --NumArgs;
862 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700863 checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs), NumParams,
Richard Smith831421f2012-06-25 20:30:08 +0000864 IsMemberFunction, TheCall->getRParenLoc(),
865 TheCall->getCallee()->getSourceRange(), CallType);
866
867 IdentifierInfo *FnInfo = FDecl->getIdentifier();
868 // None of the checks below are needed for functions that don't have
869 // simple names (e.g., C++ conversion functions).
870 if (!FnInfo)
871 return false;
Sebastian Redl0eb23302009-01-19 00:08:26 +0000872
Stephen Hines651f13c2014-04-23 16:59:28 -0700873 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
874
Anna Zaks0a151a12012-01-17 00:37:07 +0000875 unsigned CMId = FDecl->getMemoryFunctionKind();
876 if (CMId == 0)
Anna Zaksd9b859a2012-01-13 21:52:01 +0000877 return false;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000878
Anna Zaksd9b859a2012-01-13 21:52:01 +0000879 // Handle memory setting and copying functions.
Anna Zaks0a151a12012-01-17 00:37:07 +0000880 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000881 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaksc36bedc2012-02-01 19:08:57 +0000882 else if (CMId == Builtin::BIstrncat)
883 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaksd9b859a2012-01-13 21:52:01 +0000884 else
Anna Zaks0a151a12012-01-17 00:37:07 +0000885 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000886
Anders Carlssond406bf02009-08-16 01:56:34 +0000887 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000888}
889
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000890bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko287f24d2013-05-05 19:42:09 +0000891 ArrayRef<const Expr *> Args) {
Richard Smith831421f2012-06-25 20:30:08 +0000892 VariadicCallType CallType =
893 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000894
Dmitri Gribenko287f24d2013-05-05 19:42:09 +0000895 checkCall(Method, Args, Method->param_size(),
Richard Smith831421f2012-06-25 20:30:08 +0000896 /*IsMemberFunction=*/false,
897 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000898
899 return false;
900}
901
Richard Trieuf462b012013-06-20 21:03:13 +0000902bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
903 const FunctionProtoType *Proto) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000904 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
905 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000906 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000907
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000908 QualType Ty = V->getType();
Richard Trieuf462b012013-06-20 21:03:13 +0000909 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000910 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000911
Richard Trieuf462b012013-06-20 21:03:13 +0000912 VariadicCallType CallType;
Richard Trieua4993772013-06-20 23:21:54 +0000913 if (!Proto || !Proto->isVariadic()) {
Richard Trieuf462b012013-06-20 21:03:13 +0000914 CallType = VariadicDoesNotApply;
915 } else if (Ty->isBlockPointerType()) {
916 CallType = VariadicBlock;
917 } else { // Ty->isFunctionPointerType()
918 CallType = VariadicFunction;
919 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700920 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Anders Carlssond406bf02009-08-16 01:56:34 +0000921
Stephen Hines651f13c2014-04-23 16:59:28 -0700922 checkCall(NDecl, llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
923 TheCall->getNumArgs()),
924 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith831421f2012-06-25 20:30:08 +0000925 TheCall->getCallee()->getSourceRange(), CallType);
Stephen Hines651f13c2014-04-23 16:59:28 -0700926
Anders Carlssond406bf02009-08-16 01:56:34 +0000927 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000928}
929
Richard Trieu0538f0e2013-06-22 00:20:41 +0000930/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
931/// such as function pointers returned from functions.
932bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
933 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/0, Proto,
934 TheCall->getCallee());
Stephen Hines651f13c2014-04-23 16:59:28 -0700935 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Richard Trieu0538f0e2013-06-22 00:20:41 +0000936
Stephen Hines651f13c2014-04-23 16:59:28 -0700937 checkCall(/*FDecl=*/0, llvm::makeArrayRef<const Expr *>(
938 TheCall->getArgs(), TheCall->getNumArgs()),
939 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu0538f0e2013-06-22 00:20:41 +0000940 TheCall->getCallee()->getSourceRange(), CallType);
941
942 return false;
943}
944
Stephen Hines651f13c2014-04-23 16:59:28 -0700945static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
946 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
947 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
948 return false;
949
950 switch (Op) {
951 case AtomicExpr::AO__c11_atomic_init:
952 llvm_unreachable("There is no ordering argument for an init");
953
954 case AtomicExpr::AO__c11_atomic_load:
955 case AtomicExpr::AO__atomic_load_n:
956 case AtomicExpr::AO__atomic_load:
957 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
958 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
959
960 case AtomicExpr::AO__c11_atomic_store:
961 case AtomicExpr::AO__atomic_store:
962 case AtomicExpr::AO__atomic_store_n:
963 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
964 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
965 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
966
967 default:
968 return true;
969 }
970}
971
Richard Smithff34d402012-04-12 05:08:17 +0000972ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
973 AtomicExpr::AtomicOp Op) {
Eli Friedman276b0612011-10-11 02:20:01 +0000974 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
975 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000976
Richard Smithff34d402012-04-12 05:08:17 +0000977 // All these operations take one of the following forms:
978 enum {
979 // C __c11_atomic_init(A *, C)
980 Init,
981 // C __c11_atomic_load(A *, int)
982 Load,
983 // void __atomic_load(A *, CP, int)
984 Copy,
985 // C __c11_atomic_add(A *, M, int)
986 Arithmetic,
987 // C __atomic_exchange_n(A *, CP, int)
988 Xchg,
989 // void __atomic_exchange(A *, C *, CP, int)
990 GNUXchg,
991 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
992 C11CmpXchg,
993 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
994 GNUCmpXchg
995 } Form = Init;
996 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
997 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
998 // where:
999 // C is an appropriate type,
1000 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1001 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1002 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1003 // the int parameters are for orderings.
Eli Friedman276b0612011-10-11 02:20:01 +00001004
Richard Smithff34d402012-04-12 05:08:17 +00001005 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1006 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
1007 && "need to update code for modified C11 atomics");
1008 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1009 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1010 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1011 Op == AtomicExpr::AO__atomic_store_n ||
1012 Op == AtomicExpr::AO__atomic_exchange_n ||
1013 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1014 bool IsAddSub = false;
1015
1016 switch (Op) {
1017 case AtomicExpr::AO__c11_atomic_init:
1018 Form = Init;
1019 break;
1020
1021 case AtomicExpr::AO__c11_atomic_load:
1022 case AtomicExpr::AO__atomic_load_n:
1023 Form = Load;
1024 break;
1025
1026 case AtomicExpr::AO__c11_atomic_store:
1027 case AtomicExpr::AO__atomic_load:
1028 case AtomicExpr::AO__atomic_store:
1029 case AtomicExpr::AO__atomic_store_n:
1030 Form = Copy;
1031 break;
1032
1033 case AtomicExpr::AO__c11_atomic_fetch_add:
1034 case AtomicExpr::AO__c11_atomic_fetch_sub:
1035 case AtomicExpr::AO__atomic_fetch_add:
1036 case AtomicExpr::AO__atomic_fetch_sub:
1037 case AtomicExpr::AO__atomic_add_fetch:
1038 case AtomicExpr::AO__atomic_sub_fetch:
1039 IsAddSub = true;
1040 // Fall through.
1041 case AtomicExpr::AO__c11_atomic_fetch_and:
1042 case AtomicExpr::AO__c11_atomic_fetch_or:
1043 case AtomicExpr::AO__c11_atomic_fetch_xor:
1044 case AtomicExpr::AO__atomic_fetch_and:
1045 case AtomicExpr::AO__atomic_fetch_or:
1046 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smith51b92402012-04-13 06:31:38 +00001047 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithff34d402012-04-12 05:08:17 +00001048 case AtomicExpr::AO__atomic_and_fetch:
1049 case AtomicExpr::AO__atomic_or_fetch:
1050 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smith51b92402012-04-13 06:31:38 +00001051 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithff34d402012-04-12 05:08:17 +00001052 Form = Arithmetic;
1053 break;
1054
1055 case AtomicExpr::AO__c11_atomic_exchange:
1056 case AtomicExpr::AO__atomic_exchange_n:
1057 Form = Xchg;
1058 break;
1059
1060 case AtomicExpr::AO__atomic_exchange:
1061 Form = GNUXchg;
1062 break;
1063
1064 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1065 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1066 Form = C11CmpXchg;
1067 break;
1068
1069 case AtomicExpr::AO__atomic_compare_exchange:
1070 case AtomicExpr::AO__atomic_compare_exchange_n:
1071 Form = GNUCmpXchg;
1072 break;
1073 }
1074
1075 // Check we have the right number of arguments.
1076 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedman276b0612011-10-11 02:20:01 +00001077 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithff34d402012-04-12 05:08:17 +00001078 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +00001079 << TheCall->getCallee()->getSourceRange();
1080 return ExprError();
Richard Smithff34d402012-04-12 05:08:17 +00001081 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1082 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedman276b0612011-10-11 02:20:01 +00001083 diag::err_typecheck_call_too_many_args)
Richard Smithff34d402012-04-12 05:08:17 +00001084 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +00001085 << TheCall->getCallee()->getSourceRange();
1086 return ExprError();
1087 }
1088
Richard Smithff34d402012-04-12 05:08:17 +00001089 // Inspect the first argument of the atomic operation.
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001090 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +00001091 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1092 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1093 if (!pointerType) {
Richard Smithff34d402012-04-12 05:08:17 +00001094 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedman276b0612011-10-11 02:20:01 +00001095 << Ptr->getType() << Ptr->getSourceRange();
1096 return ExprError();
1097 }
1098
Richard Smithff34d402012-04-12 05:08:17 +00001099 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1100 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1101 QualType ValType = AtomTy; // 'C'
1102 if (IsC11) {
1103 if (!AtomTy->isAtomicType()) {
1104 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1105 << Ptr->getType() << Ptr->getSourceRange();
1106 return ExprError();
1107 }
Richard Smithbc57b102012-09-15 06:09:58 +00001108 if (AtomTy.isConstQualified()) {
1109 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1110 << Ptr->getType() << Ptr->getSourceRange();
1111 return ExprError();
1112 }
Richard Smithff34d402012-04-12 05:08:17 +00001113 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedman276b0612011-10-11 02:20:01 +00001114 }
Eli Friedman276b0612011-10-11 02:20:01 +00001115
Richard Smithff34d402012-04-12 05:08:17 +00001116 // For an arithmetic operation, the implied arithmetic must be well-formed.
1117 if (Form == Arithmetic) {
1118 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1119 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1120 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1121 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1122 return ExprError();
1123 }
1124 if (!IsAddSub && !ValType->isIntegerType()) {
1125 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1126 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1127 return ExprError();
1128 }
1129 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1130 // For __atomic_*_n operations, the value type must be a scalar integral or
1131 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedman276b0612011-10-11 02:20:01 +00001132 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithff34d402012-04-12 05:08:17 +00001133 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1134 return ExprError();
1135 }
1136
Eli Friedmana3d727b2013-09-11 03:49:34 +00001137 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1138 !AtomTy->isScalarType()) {
Richard Smithff34d402012-04-12 05:08:17 +00001139 // For GNU atomics, require a trivially-copyable type. This is not part of
1140 // the GNU atomics specification, but we enforce it for sanity.
1141 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedman276b0612011-10-11 02:20:01 +00001142 << Ptr->getType() << Ptr->getSourceRange();
1143 return ExprError();
1144 }
1145
Richard Smithff34d402012-04-12 05:08:17 +00001146 // FIXME: For any builtin other than a load, the ValType must not be
1147 // const-qualified.
Eli Friedman276b0612011-10-11 02:20:01 +00001148
1149 switch (ValType.getObjCLifetime()) {
1150 case Qualifiers::OCL_None:
1151 case Qualifiers::OCL_ExplicitNone:
1152 // okay
1153 break;
1154
1155 case Qualifiers::OCL_Weak:
1156 case Qualifiers::OCL_Strong:
1157 case Qualifiers::OCL_Autoreleasing:
Richard Smithff34d402012-04-12 05:08:17 +00001158 // FIXME: Can this happen? By this point, ValType should be known
1159 // to be trivially copyable.
Eli Friedman276b0612011-10-11 02:20:01 +00001160 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1161 << ValType << Ptr->getSourceRange();
1162 return ExprError();
1163 }
1164
1165 QualType ResultType = ValType;
Richard Smithff34d402012-04-12 05:08:17 +00001166 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedman276b0612011-10-11 02:20:01 +00001167 ResultType = Context.VoidTy;
Richard Smithff34d402012-04-12 05:08:17 +00001168 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedman276b0612011-10-11 02:20:01 +00001169 ResultType = Context.BoolTy;
1170
Richard Smithff34d402012-04-12 05:08:17 +00001171 // The type of a parameter passed 'by value'. In the GNU atomics, such
1172 // arguments are actually passed as pointers.
1173 QualType ByValType = ValType; // 'CP'
1174 if (!IsC11 && !IsN)
1175 ByValType = Ptr->getType();
1176
Eli Friedman276b0612011-10-11 02:20:01 +00001177 // The first argument --- the pointer --- has a fixed type; we
1178 // deduce the types of the rest of the arguments accordingly. Walk
1179 // the remaining arguments, converting them to the deduced value type.
Richard Smithff34d402012-04-12 05:08:17 +00001180 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedman276b0612011-10-11 02:20:01 +00001181 QualType Ty;
Richard Smithff34d402012-04-12 05:08:17 +00001182 if (i < NumVals[Form] + 1) {
1183 switch (i) {
1184 case 1:
1185 // The second argument is the non-atomic operand. For arithmetic, this
1186 // is always passed by value, and for a compare_exchange it is always
1187 // passed by address. For the rest, GNU uses by-address and C11 uses
1188 // by-value.
1189 assert(Form != Load);
1190 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1191 Ty = ValType;
1192 else if (Form == Copy || Form == Xchg)
1193 Ty = ByValType;
1194 else if (Form == Arithmetic)
1195 Ty = Context.getPointerDiffType();
1196 else
1197 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1198 break;
1199 case 2:
1200 // The third argument to compare_exchange / GNU exchange is a
1201 // (pointer to a) desired value.
1202 Ty = ByValType;
1203 break;
1204 case 3:
1205 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1206 Ty = Context.BoolTy;
1207 break;
1208 }
Eli Friedman276b0612011-10-11 02:20:01 +00001209 } else {
1210 // The order(s) are always converted to int.
1211 Ty = Context.IntTy;
1212 }
Richard Smithff34d402012-04-12 05:08:17 +00001213
Eli Friedman276b0612011-10-11 02:20:01 +00001214 InitializedEntity Entity =
1215 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithff34d402012-04-12 05:08:17 +00001216 ExprResult Arg = TheCall->getArg(i);
Eli Friedman276b0612011-10-11 02:20:01 +00001217 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1218 if (Arg.isInvalid())
1219 return true;
1220 TheCall->setArg(i, Arg.get());
1221 }
1222
Richard Smithff34d402012-04-12 05:08:17 +00001223 // Permute the arguments into a 'consistent' order.
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001224 SmallVector<Expr*, 5> SubExprs;
1225 SubExprs.push_back(Ptr);
Richard Smithff34d402012-04-12 05:08:17 +00001226 switch (Form) {
1227 case Init:
1228 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnall7a7ee302012-01-16 17:27:18 +00001229 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +00001230 break;
1231 case Load:
1232 SubExprs.push_back(TheCall->getArg(1)); // Order
1233 break;
1234 case Copy:
1235 case Arithmetic:
1236 case Xchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001237 SubExprs.push_back(TheCall->getArg(2)); // Order
1238 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +00001239 break;
1240 case GNUXchg:
1241 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1242 SubExprs.push_back(TheCall->getArg(3)); // Order
1243 SubExprs.push_back(TheCall->getArg(1)); // Val1
1244 SubExprs.push_back(TheCall->getArg(2)); // Val2
1245 break;
1246 case C11CmpXchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001247 SubExprs.push_back(TheCall->getArg(3)); // Order
1248 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001249 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall2ebb98a2012-03-29 17:58:59 +00001250 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithff34d402012-04-12 05:08:17 +00001251 break;
1252 case GNUCmpXchg:
1253 SubExprs.push_back(TheCall->getArg(4)); // Order
1254 SubExprs.push_back(TheCall->getArg(1)); // Val1
1255 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1256 SubExprs.push_back(TheCall->getArg(2)); // Val2
1257 SubExprs.push_back(TheCall->getArg(3)); // Weak
1258 break;
Eli Friedman276b0612011-10-11 02:20:01 +00001259 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001260
1261 if (SubExprs.size() >= 2 && Form != Init) {
1262 llvm::APSInt Result(32);
1263 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1264 !isValidOrderingForOp(Result.getSExtValue(), Op))
1265 Diag(SubExprs[1]->getLocStart(),
1266 diag::warn_atomic_op_has_invalid_memory_order)
1267 << SubExprs[1]->getSourceRange();
1268 }
1269
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00001270 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1271 SubExprs, ResultType, Op,
1272 TheCall->getRParenLoc());
1273
1274 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1275 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1276 Context.AtomicUsesUnsupportedLibcall(AE))
1277 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1278 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001279
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00001280 return Owned(AE);
Eli Friedman276b0612011-10-11 02:20:01 +00001281}
1282
1283
John McCall5f8d6042011-08-27 01:09:30 +00001284/// checkBuiltinArgument - Given a call to a builtin function, perform
1285/// normal type-checking on the given argument, updating the call in
1286/// place. This is useful when a builtin function requires custom
1287/// type-checking for some of its arguments but not necessarily all of
1288/// them.
1289///
1290/// Returns true on error.
1291static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1292 FunctionDecl *Fn = E->getDirectCallee();
1293 assert(Fn && "builtin call without direct callee!");
1294
1295 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1296 InitializedEntity Entity =
1297 InitializedEntity::InitializeParameter(S.Context, Param);
1298
1299 ExprResult Arg = E->getArg(0);
1300 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1301 if (Arg.isInvalid())
1302 return true;
1303
1304 E->setArg(ArgIndex, Arg.take());
1305 return false;
1306}
1307
Chris Lattner5caa3702009-05-08 06:58:22 +00001308/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1309/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1310/// type of its first argument. The main ActOnCallExpr routines have already
1311/// promoted the types of arguments because all of these calls are prototyped as
1312/// void(...).
1313///
1314/// This function goes through and does final semantic checking for these
1315/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +00001316ExprResult
1317Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +00001318 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +00001319 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1320 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1321
1322 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +00001323 if (TheCall->getNumArgs() < 1) {
1324 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1325 << 0 << 1 << TheCall->getNumArgs()
1326 << TheCall->getCallee()->getSourceRange();
1327 return ExprError();
1328 }
Mike Stump1eb44332009-09-09 15:08:12 +00001329
Chris Lattner5caa3702009-05-08 06:58:22 +00001330 // Inspect the first argument of the atomic builtin. This should always be
1331 // a pointer type, whose element is an integral scalar or pointer type.
1332 // Because it is a pointer type, we don't have to worry about any implicit
1333 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +00001334 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +00001335 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman8c382062012-01-23 02:35:22 +00001336 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1337 if (FirstArgResult.isInvalid())
1338 return ExprError();
1339 FirstArg = FirstArgResult.take();
1340 TheCall->setArg(0, FirstArg);
1341
John McCallf85e1932011-06-15 23:02:42 +00001342 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1343 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +00001344 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1345 << FirstArg->getType() << FirstArg->getSourceRange();
1346 return ExprError();
1347 }
Mike Stump1eb44332009-09-09 15:08:12 +00001348
John McCallf85e1932011-06-15 23:02:42 +00001349 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +00001350 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +00001351 !ValType->isBlockPointerType()) {
1352 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1353 << FirstArg->getType() << FirstArg->getSourceRange();
1354 return ExprError();
1355 }
Chris Lattner5caa3702009-05-08 06:58:22 +00001356
John McCallf85e1932011-06-15 23:02:42 +00001357 switch (ValType.getObjCLifetime()) {
1358 case Qualifiers::OCL_None:
1359 case Qualifiers::OCL_ExplicitNone:
1360 // okay
1361 break;
1362
1363 case Qualifiers::OCL_Weak:
1364 case Qualifiers::OCL_Strong:
1365 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001366 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001367 << ValType << FirstArg->getSourceRange();
1368 return ExprError();
1369 }
1370
John McCallb45ae252011-10-05 07:41:44 +00001371 // Strip any qualifiers off ValType.
1372 ValType = ValType.getUnqualifiedType();
1373
Chandler Carruth8d13d222010-07-18 20:54:12 +00001374 // The majority of builtins return a value, but a few have special return
1375 // types, so allow them to override appropriately below.
1376 QualType ResultType = ValType;
1377
Chris Lattner5caa3702009-05-08 06:58:22 +00001378 // We need to figure out which concrete builtin this maps onto. For example,
1379 // __sync_fetch_and_add with a 2 byte object turns into
1380 // __sync_fetch_and_add_2.
1381#define BUILTIN_ROW(x) \
1382 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1383 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +00001384
Chris Lattner5caa3702009-05-08 06:58:22 +00001385 static const unsigned BuiltinIndices[][5] = {
1386 BUILTIN_ROW(__sync_fetch_and_add),
1387 BUILTIN_ROW(__sync_fetch_and_sub),
1388 BUILTIN_ROW(__sync_fetch_and_or),
1389 BUILTIN_ROW(__sync_fetch_and_and),
1390 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +00001391
Chris Lattner5caa3702009-05-08 06:58:22 +00001392 BUILTIN_ROW(__sync_add_and_fetch),
1393 BUILTIN_ROW(__sync_sub_and_fetch),
1394 BUILTIN_ROW(__sync_and_and_fetch),
1395 BUILTIN_ROW(__sync_or_and_fetch),
1396 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +00001397
Chris Lattner5caa3702009-05-08 06:58:22 +00001398 BUILTIN_ROW(__sync_val_compare_and_swap),
1399 BUILTIN_ROW(__sync_bool_compare_and_swap),
1400 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +00001401 BUILTIN_ROW(__sync_lock_release),
1402 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +00001403 };
Mike Stump1eb44332009-09-09 15:08:12 +00001404#undef BUILTIN_ROW
1405
Chris Lattner5caa3702009-05-08 06:58:22 +00001406 // Determine the index of the size.
1407 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +00001408 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +00001409 case 1: SizeIndex = 0; break;
1410 case 2: SizeIndex = 1; break;
1411 case 4: SizeIndex = 2; break;
1412 case 8: SizeIndex = 3; break;
1413 case 16: SizeIndex = 4; break;
1414 default:
Chandler Carruthd2014572010-07-09 18:59:35 +00001415 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1416 << FirstArg->getType() << FirstArg->getSourceRange();
1417 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +00001418 }
Mike Stump1eb44332009-09-09 15:08:12 +00001419
Chris Lattner5caa3702009-05-08 06:58:22 +00001420 // Each of these builtins has one pointer argument, followed by some number of
1421 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1422 // that we ignore. Find out which row of BuiltinIndices to read from as well
1423 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00001424 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +00001425 unsigned BuiltinIndex, NumFixed = 1;
1426 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001427 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +00001428 case Builtin::BI__sync_fetch_and_add:
1429 case Builtin::BI__sync_fetch_and_add_1:
1430 case Builtin::BI__sync_fetch_and_add_2:
1431 case Builtin::BI__sync_fetch_and_add_4:
1432 case Builtin::BI__sync_fetch_and_add_8:
1433 case Builtin::BI__sync_fetch_and_add_16:
1434 BuiltinIndex = 0;
1435 break;
1436
1437 case Builtin::BI__sync_fetch_and_sub:
1438 case Builtin::BI__sync_fetch_and_sub_1:
1439 case Builtin::BI__sync_fetch_and_sub_2:
1440 case Builtin::BI__sync_fetch_and_sub_4:
1441 case Builtin::BI__sync_fetch_and_sub_8:
1442 case Builtin::BI__sync_fetch_and_sub_16:
1443 BuiltinIndex = 1;
1444 break;
1445
1446 case Builtin::BI__sync_fetch_and_or:
1447 case Builtin::BI__sync_fetch_and_or_1:
1448 case Builtin::BI__sync_fetch_and_or_2:
1449 case Builtin::BI__sync_fetch_and_or_4:
1450 case Builtin::BI__sync_fetch_and_or_8:
1451 case Builtin::BI__sync_fetch_and_or_16:
1452 BuiltinIndex = 2;
1453 break;
1454
1455 case Builtin::BI__sync_fetch_and_and:
1456 case Builtin::BI__sync_fetch_and_and_1:
1457 case Builtin::BI__sync_fetch_and_and_2:
1458 case Builtin::BI__sync_fetch_and_and_4:
1459 case Builtin::BI__sync_fetch_and_and_8:
1460 case Builtin::BI__sync_fetch_and_and_16:
1461 BuiltinIndex = 3;
1462 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001463
Douglas Gregora9766412011-11-28 16:30:08 +00001464 case Builtin::BI__sync_fetch_and_xor:
1465 case Builtin::BI__sync_fetch_and_xor_1:
1466 case Builtin::BI__sync_fetch_and_xor_2:
1467 case Builtin::BI__sync_fetch_and_xor_4:
1468 case Builtin::BI__sync_fetch_and_xor_8:
1469 case Builtin::BI__sync_fetch_and_xor_16:
1470 BuiltinIndex = 4;
1471 break;
1472
1473 case Builtin::BI__sync_add_and_fetch:
1474 case Builtin::BI__sync_add_and_fetch_1:
1475 case Builtin::BI__sync_add_and_fetch_2:
1476 case Builtin::BI__sync_add_and_fetch_4:
1477 case Builtin::BI__sync_add_and_fetch_8:
1478 case Builtin::BI__sync_add_and_fetch_16:
1479 BuiltinIndex = 5;
1480 break;
1481
1482 case Builtin::BI__sync_sub_and_fetch:
1483 case Builtin::BI__sync_sub_and_fetch_1:
1484 case Builtin::BI__sync_sub_and_fetch_2:
1485 case Builtin::BI__sync_sub_and_fetch_4:
1486 case Builtin::BI__sync_sub_and_fetch_8:
1487 case Builtin::BI__sync_sub_and_fetch_16:
1488 BuiltinIndex = 6;
1489 break;
1490
1491 case Builtin::BI__sync_and_and_fetch:
1492 case Builtin::BI__sync_and_and_fetch_1:
1493 case Builtin::BI__sync_and_and_fetch_2:
1494 case Builtin::BI__sync_and_and_fetch_4:
1495 case Builtin::BI__sync_and_and_fetch_8:
1496 case Builtin::BI__sync_and_and_fetch_16:
1497 BuiltinIndex = 7;
1498 break;
1499
1500 case Builtin::BI__sync_or_and_fetch:
1501 case Builtin::BI__sync_or_and_fetch_1:
1502 case Builtin::BI__sync_or_and_fetch_2:
1503 case Builtin::BI__sync_or_and_fetch_4:
1504 case Builtin::BI__sync_or_and_fetch_8:
1505 case Builtin::BI__sync_or_and_fetch_16:
1506 BuiltinIndex = 8;
1507 break;
1508
1509 case Builtin::BI__sync_xor_and_fetch:
1510 case Builtin::BI__sync_xor_and_fetch_1:
1511 case Builtin::BI__sync_xor_and_fetch_2:
1512 case Builtin::BI__sync_xor_and_fetch_4:
1513 case Builtin::BI__sync_xor_and_fetch_8:
1514 case Builtin::BI__sync_xor_and_fetch_16:
1515 BuiltinIndex = 9;
1516 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001517
Chris Lattner5caa3702009-05-08 06:58:22 +00001518 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001519 case Builtin::BI__sync_val_compare_and_swap_1:
1520 case Builtin::BI__sync_val_compare_and_swap_2:
1521 case Builtin::BI__sync_val_compare_and_swap_4:
1522 case Builtin::BI__sync_val_compare_and_swap_8:
1523 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001524 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +00001525 NumFixed = 2;
1526 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001527
Chris Lattner5caa3702009-05-08 06:58:22 +00001528 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001529 case Builtin::BI__sync_bool_compare_and_swap_1:
1530 case Builtin::BI__sync_bool_compare_and_swap_2:
1531 case Builtin::BI__sync_bool_compare_and_swap_4:
1532 case Builtin::BI__sync_bool_compare_and_swap_8:
1533 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001534 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +00001535 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001536 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001537 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001538
1539 case Builtin::BI__sync_lock_test_and_set:
1540 case Builtin::BI__sync_lock_test_and_set_1:
1541 case Builtin::BI__sync_lock_test_and_set_2:
1542 case Builtin::BI__sync_lock_test_and_set_4:
1543 case Builtin::BI__sync_lock_test_and_set_8:
1544 case Builtin::BI__sync_lock_test_and_set_16:
1545 BuiltinIndex = 12;
1546 break;
1547
Chris Lattner5caa3702009-05-08 06:58:22 +00001548 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +00001549 case Builtin::BI__sync_lock_release_1:
1550 case Builtin::BI__sync_lock_release_2:
1551 case Builtin::BI__sync_lock_release_4:
1552 case Builtin::BI__sync_lock_release_8:
1553 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001554 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +00001555 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001556 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001557 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001558
1559 case Builtin::BI__sync_swap:
1560 case Builtin::BI__sync_swap_1:
1561 case Builtin::BI__sync_swap_2:
1562 case Builtin::BI__sync_swap_4:
1563 case Builtin::BI__sync_swap_8:
1564 case Builtin::BI__sync_swap_16:
1565 BuiltinIndex = 14;
1566 break;
Chris Lattner5caa3702009-05-08 06:58:22 +00001567 }
Mike Stump1eb44332009-09-09 15:08:12 +00001568
Chris Lattner5caa3702009-05-08 06:58:22 +00001569 // Now that we know how many fixed arguments we expect, first check that we
1570 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +00001571 if (TheCall->getNumArgs() < 1+NumFixed) {
1572 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1573 << 0 << 1+NumFixed << TheCall->getNumArgs()
1574 << TheCall->getCallee()->getSourceRange();
1575 return ExprError();
1576 }
Mike Stump1eb44332009-09-09 15:08:12 +00001577
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001578 // Get the decl for the concrete builtin from this, we can tell what the
1579 // concrete integer type we should convert to is.
1580 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1581 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara2ad11cd2012-09-22 09:05:22 +00001582 FunctionDecl *NewBuiltinDecl;
1583 if (NewBuiltinID == BuiltinID)
1584 NewBuiltinDecl = FDecl;
1585 else {
1586 // Perform builtin lookup to avoid redeclaring it.
1587 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1588 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1589 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1590 assert(Res.getFoundDecl());
1591 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1592 if (NewBuiltinDecl == 0)
1593 return ExprError();
1594 }
Chandler Carruthd2014572010-07-09 18:59:35 +00001595
John McCallf871d0c2010-08-07 06:22:56 +00001596 // The first argument --- the pointer --- has a fixed type; we
1597 // deduce the types of the rest of the arguments accordingly. Walk
1598 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +00001599 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +00001600 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +00001601
Chris Lattner5caa3702009-05-08 06:58:22 +00001602 // GCC does an implicit conversion to the pointer or integer ValType. This
1603 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +00001604 // Initialize the argument.
1605 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1606 ValType, /*consume*/ false);
1607 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +00001608 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +00001609 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001610
Chris Lattner5caa3702009-05-08 06:58:22 +00001611 // Okay, we have something that *can* be converted to the right type. Check
1612 // to see if there is a potentially weird extension going on here. This can
1613 // happen when you do an atomic operation on something like an char* and
1614 // pass in 42. The 42 gets converted to char. This is even more strange
1615 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +00001616 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +00001617 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +00001618 }
Mike Stump1eb44332009-09-09 15:08:12 +00001619
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001620 ASTContext& Context = this->getASTContext();
1621
1622 // Create a new DeclRefExpr to refer to the new decl.
1623 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1624 Context,
1625 DRE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001626 SourceLocation(),
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001627 NewBuiltinDecl,
John McCallf4b88a42012-03-10 09:33:50 +00001628 /*enclosing*/ false,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001629 DRE->getLocation(),
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001630 Context.BuiltinFnTy,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001631 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +00001632
Chris Lattner5caa3702009-05-08 06:58:22 +00001633 // Set the callee in the CallExpr.
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001634 // FIXME: This loses syntactic information.
1635 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1636 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1637 CK_BuiltinFnToFnPtr);
John Wiegley429bb272011-04-08 18:41:53 +00001638 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001639
Chandler Carruthdb4325b2010-07-18 07:23:17 +00001640 // Change the result type of the call to match the original value type. This
1641 // is arbitrary, but the codegen for these builtins ins design to handle it
1642 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +00001643 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001644
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001645 return TheCallResult;
Chris Lattner5caa3702009-05-08 06:58:22 +00001646}
1647
Chris Lattner69039812009-02-18 06:01:06 +00001648/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00001649/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00001650/// Note: It might also make sense to do the UTF-16 conversion here (would
1651/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00001652bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00001653 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00001654 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1655
Douglas Gregor5cee1192011-07-27 05:40:30 +00001656 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001657 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1658 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001659 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001660 }
Mike Stump1eb44332009-09-09 15:08:12 +00001661
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001662 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001663 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001664 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001665 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divacky31ba6132012-09-06 15:59:27 +00001666 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001667 UTF16 *ToPtr = &ToBuf[0];
1668
1669 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1670 &ToPtr, ToPtr + NumBytes,
1671 strictConversion);
1672 // Check for conversion failure.
1673 if (Result != conversionOK)
1674 Diag(Arg->getLocStart(),
1675 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1676 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001677 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00001678}
1679
Chris Lattnerc27c6652007-12-20 00:05:45 +00001680/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1681/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00001682bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1683 Expr *Fn = TheCall->getCallee();
1684 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001685 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001686 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001687 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1688 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00001689 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001690 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00001691 return true;
1692 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00001693
1694 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00001695 return Diag(TheCall->getLocEnd(),
1696 diag::err_typecheck_call_too_few_args_at_least)
1697 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00001698 }
1699
John McCall5f8d6042011-08-27 01:09:30 +00001700 // Type-check the first argument normally.
1701 if (checkBuiltinArgument(*this, TheCall, 0))
1702 return true;
1703
Chris Lattnerc27c6652007-12-20 00:05:45 +00001704 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001705 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00001706 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001707 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00001708 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00001709 else if (FunctionDecl *FD = getCurFunctionDecl())
1710 isVariadic = FD->isVariadic();
1711 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001712 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00001713
Chris Lattnerc27c6652007-12-20 00:05:45 +00001714 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001715 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1716 return true;
1717 }
Mike Stump1eb44332009-09-09 15:08:12 +00001718
Chris Lattner30ce3442007-12-19 23:59:04 +00001719 // Verify that the second argument to the builtin is the last argument of the
1720 // current function or method.
1721 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00001722 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001723
Nico Weberb07d4482013-05-24 23:31:57 +00001724 // These are valid if SecondArgIsLastNamedArgument is false after the next
1725 // block.
1726 QualType Type;
1727 SourceLocation ParamLoc;
1728
Anders Carlsson88cf2262008-02-11 04:20:54 +00001729 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1730 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001731 // FIXME: This isn't correct for methods (results in bogus warning).
1732 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00001733 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001734 if (CurBlock)
1735 LastArg = *(CurBlock->TheDecl->param_end()-1);
1736 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00001737 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001738 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001739 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001740 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weberb07d4482013-05-24 23:31:57 +00001741
1742 Type = PV->getType();
1743 ParamLoc = PV->getLocation();
Chris Lattner30ce3442007-12-19 23:59:04 +00001744 }
1745 }
Mike Stump1eb44332009-09-09 15:08:12 +00001746
Chris Lattner30ce3442007-12-19 23:59:04 +00001747 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001748 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00001749 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weberb07d4482013-05-24 23:31:57 +00001750 else if (Type->isReferenceType()) {
1751 Diag(Arg->getLocStart(),
1752 diag::warn_va_start_of_reference_type_is_undefined);
1753 Diag(ParamLoc, diag::note_parameter_type) << Type;
1754 }
1755
Enea Zaffanella54de9bb2013-11-07 08:14:26 +00001756 TheCall->setType(Context.VoidTy);
Chris Lattner30ce3442007-12-19 23:59:04 +00001757 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00001758}
Chris Lattner30ce3442007-12-19 23:59:04 +00001759
Chris Lattner1b9a0792007-12-20 00:26:33 +00001760/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1761/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00001762bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1763 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001764 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001765 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001766 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001767 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001768 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001769 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001770 << SourceRange(TheCall->getArg(2)->getLocStart(),
1771 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001772
John Wiegley429bb272011-04-08 18:41:53 +00001773 ExprResult OrigArg0 = TheCall->getArg(0);
1774 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001775
Chris Lattner1b9a0792007-12-20 00:26:33 +00001776 // Do standard promotions between the two arguments, returning their common
1777 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001778 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001779 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1780 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001781
1782 // Make sure any conversions are pushed back into the call; this is
1783 // type safe since unordered compare builtins are declared as "_Bool
1784 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001785 TheCall->setArg(0, OrigArg0.get());
1786 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001787
John Wiegley429bb272011-04-08 18:41:53 +00001788 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001789 return false;
1790
Chris Lattner1b9a0792007-12-20 00:26:33 +00001791 // If the common type isn't a real floating type, then the arguments were
1792 // invalid for this operation.
Eli Friedman860a3192012-06-16 02:19:17 +00001793 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001794 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001795 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001796 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1797 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001798
Chris Lattner1b9a0792007-12-20 00:26:33 +00001799 return false;
1800}
1801
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001802/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1803/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001804/// to check everything. We expect the last argument to be a floating point
1805/// value.
1806bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1807 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001808 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001809 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001810 if (TheCall->getNumArgs() > NumArgs)
1811 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001812 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001813 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001814 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001815 (*(TheCall->arg_end()-1))->getLocEnd());
1816
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001817 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001818
Eli Friedman9ac6f622009-08-31 20:06:00 +00001819 if (OrigArg->isTypeDependent())
1820 return false;
1821
Chris Lattner81368fb2010-05-06 05:50:07 +00001822 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001823 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001824 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001825 diag::err_typecheck_call_invalid_unary_fp)
1826 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001827
Chris Lattner81368fb2010-05-06 05:50:07 +00001828 // If this is an implicit conversion from float -> double, remove it.
1829 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1830 Expr *CastArg = Cast->getSubExpr();
1831 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1832 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1833 "promotion from float to double is the only expected cast here");
1834 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001835 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner81368fb2010-05-06 05:50:07 +00001836 }
1837 }
1838
Eli Friedman9ac6f622009-08-31 20:06:00 +00001839 return false;
1840}
1841
Eli Friedmand38617c2008-05-14 19:38:39 +00001842/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1843// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001844ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001845 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001846 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001847 diag::err_typecheck_call_too_few_args_at_least)
Craig Topperb44545a2013-07-28 21:50:10 +00001848 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1849 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001850
Nate Begeman37b6a572010-06-08 00:16:34 +00001851 // Determine which of the following types of shufflevector we're checking:
1852 // 1) unary, vector mask: (lhs, mask)
1853 // 2) binary, vector mask: (lhs, rhs, mask)
1854 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1855 QualType resType = TheCall->getArg(0)->getType();
1856 unsigned numElements = 0;
Craig Toppere3fbbe92013-07-19 04:46:31 +00001857
Douglas Gregorcde01732009-05-19 22:10:17 +00001858 if (!TheCall->getArg(0)->isTypeDependent() &&
1859 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001860 QualType LHSType = TheCall->getArg(0)->getType();
1861 QualType RHSType = TheCall->getArg(1)->getType();
Craig Toppere3fbbe92013-07-19 04:46:31 +00001862
Craig Topperbbe759c2013-07-29 06:47:04 +00001863 if (!LHSType->isVectorType() || !RHSType->isVectorType())
1864 return ExprError(Diag(TheCall->getLocStart(),
1865 diag::err_shufflevector_non_vector)
1866 << SourceRange(TheCall->getArg(0)->getLocStart(),
1867 TheCall->getArg(1)->getLocEnd()));
Craig Toppere3fbbe92013-07-19 04:46:31 +00001868
Nate Begeman37b6a572010-06-08 00:16:34 +00001869 numElements = LHSType->getAs<VectorType>()->getNumElements();
1870 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001871
Nate Begeman37b6a572010-06-08 00:16:34 +00001872 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1873 // with mask. If so, verify that RHS is an integer vector type with the
1874 // same number of elts as lhs.
1875 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru4cb3d902013-07-06 08:00:09 +00001876 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001877 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbbe759c2013-07-29 06:47:04 +00001878 return ExprError(Diag(TheCall->getLocStart(),
1879 diag::err_shufflevector_incompatible_vector)
1880 << SourceRange(TheCall->getArg(1)->getLocStart(),
1881 TheCall->getArg(1)->getLocEnd()));
Craig Toppere3fbbe92013-07-19 04:46:31 +00001882 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbbe759c2013-07-29 06:47:04 +00001883 return ExprError(Diag(TheCall->getLocStart(),
1884 diag::err_shufflevector_incompatible_vector)
1885 << SourceRange(TheCall->getArg(0)->getLocStart(),
1886 TheCall->getArg(1)->getLocEnd()));
Nate Begeman37b6a572010-06-08 00:16:34 +00001887 } else if (numElements != numResElements) {
1888 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001889 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001890 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001891 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001892 }
1893
1894 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001895 if (TheCall->getArg(i)->isTypeDependent() ||
1896 TheCall->getArg(i)->isValueDependent())
1897 continue;
1898
Nate Begeman37b6a572010-06-08 00:16:34 +00001899 llvm::APSInt Result(32);
1900 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1901 return ExprError(Diag(TheCall->getLocStart(),
Craig Topperb44545a2013-07-28 21:50:10 +00001902 diag::err_shufflevector_nonconstant_argument)
1903 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001904
Craig Topper6f4f8082013-08-03 17:40:38 +00001905 // Allow -1 which will be translated to undef in the IR.
1906 if (Result.isSigned() && Result.isAllOnesValue())
1907 continue;
1908
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001909 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001910 return ExprError(Diag(TheCall->getLocStart(),
Craig Topperb44545a2013-07-28 21:50:10 +00001911 diag::err_shufflevector_argument_too_large)
1912 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001913 }
1914
Chris Lattner5f9e2722011-07-23 10:55:15 +00001915 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001916
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001917 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001918 exprs.push_back(TheCall->getArg(i));
1919 TheCall->setArg(i, 0);
1920 }
1921
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001922 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001923 TheCall->getCallee()->getLocStart(),
1924 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001925}
Chris Lattner30ce3442007-12-19 23:59:04 +00001926
Hal Finkel414a1bd2013-09-18 03:29:45 +00001927/// SemaConvertVectorExpr - Handle __builtin_convertvector
1928ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
1929 SourceLocation BuiltinLoc,
1930 SourceLocation RParenLoc) {
1931 ExprValueKind VK = VK_RValue;
1932 ExprObjectKind OK = OK_Ordinary;
1933 QualType DstTy = TInfo->getType();
1934 QualType SrcTy = E->getType();
1935
1936 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
1937 return ExprError(Diag(BuiltinLoc,
1938 diag::err_convertvector_non_vector)
1939 << E->getSourceRange());
1940 if (!DstTy->isVectorType() && !DstTy->isDependentType())
1941 return ExprError(Diag(BuiltinLoc,
1942 diag::err_convertvector_non_vector_type));
1943
1944 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
1945 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
1946 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
1947 if (SrcElts != DstElts)
1948 return ExprError(Diag(BuiltinLoc,
1949 diag::err_convertvector_incompatible_vector)
1950 << E->getSourceRange());
1951 }
1952
1953 return Owned(new (Context) ConvertVectorExpr(E, TInfo, DstTy, VK, OK,
1954 BuiltinLoc, RParenLoc));
1955
1956}
1957
Daniel Dunbar4493f792008-07-21 22:59:13 +00001958/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1959// This is declared to take (const void*, ...) and can take two
1960// optional constant int args.
1961bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001962 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001963
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001964 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001965 return Diag(TheCall->getLocEnd(),
1966 diag::err_typecheck_call_too_many_args_at_most)
1967 << 0 /*function call*/ << 3 << NumArgs
1968 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001969
1970 // Argument 0 is checked for us and the remaining arguments must be
1971 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001972 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001973 Expr *Arg = TheCall->getArg(i);
Douglas Gregor592a4232012-06-29 01:05:22 +00001974
1975 // We can't check the value of a dependent argument.
1976 if (Arg->isTypeDependent() || Arg->isValueDependent())
1977 continue;
1978
Eli Friedman9aef7262009-12-04 00:30:06 +00001979 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001980 if (SemaBuiltinConstantArg(TheCall, i, Result))
1981 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001982
Daniel Dunbar4493f792008-07-21 22:59:13 +00001983 // FIXME: gcc issues a warning and rewrites these to 0. These
1984 // seems especially odd for the third argument since the default
1985 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001986 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001987 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001988 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001989 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001990 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001991 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001992 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001993 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001994 }
1995 }
1996
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001997 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001998}
1999
Stephen Hines651f13c2014-04-23 16:59:28 -07002000/// SemaBuiltinMMPrefetch - Handle _mm_prefetch.
2001// This is declared to take (const char*, int)
2002bool Sema::SemaBuiltinMMPrefetch(CallExpr *TheCall) {
2003 Expr *Arg = TheCall->getArg(1);
2004
2005 // We can't check the value of a dependent argument.
2006 if (Arg->isTypeDependent() || Arg->isValueDependent())
2007 return false;
2008
2009 llvm::APSInt Result;
2010 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2011 return true;
2012
2013 if (Result.getLimitedValue() > 3)
2014 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
2015 << "0" << "3" << Arg->getSourceRange();
2016
2017 return false;
2018}
2019
Eric Christopher691ebc32010-04-17 02:26:23 +00002020/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2021/// TheCall is a constant expression.
2022bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
2023 llvm::APSInt &Result) {
2024 Expr *Arg = TheCall->getArg(ArgNum);
2025 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2026 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2027
2028 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2029
2030 if (!Arg->isIntegerConstantExpr(Result, Context))
2031 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00002032 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00002033
Chris Lattner21fb98e2009-09-23 06:06:36 +00002034 return false;
2035}
2036
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00002037/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
2038/// int type). This simply type checks that type is one of the defined
2039/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00002040// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00002041bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00002042 llvm::APSInt Result;
Douglas Gregor592a4232012-06-29 01:05:22 +00002043
2044 // We can't check the value of a dependent argument.
2045 if (TheCall->getArg(1)->isTypeDependent() ||
2046 TheCall->getArg(1)->isValueDependent())
2047 return false;
2048
Eric Christopher691ebc32010-04-17 02:26:23 +00002049 // Check constant-ness first.
2050 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2051 return true;
2052
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00002053 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00002054 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002055 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
2056 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00002057 }
2058
2059 return false;
2060}
2061
Eli Friedman586d6a82009-05-03 06:04:26 +00002062/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00002063/// This checks that val is a constant 1.
2064bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
2065 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00002066 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00002067
Eric Christopher691ebc32010-04-17 02:26:23 +00002068 // TODO: This is less than ideal. Overload this to take a value.
2069 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2070 return true;
2071
2072 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00002073 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2074 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2075
2076 return false;
2077}
2078
Richard Smith0e218972013-08-05 18:49:43 +00002079namespace {
2080enum StringLiteralCheckType {
2081 SLCT_NotALiteral,
2082 SLCT_UncheckedLiteral,
2083 SLCT_CheckedLiteral
2084};
2085}
2086
Richard Smith831421f2012-06-25 20:30:08 +00002087// Determine if an expression is a string literal or constant string.
2088// If this function returns false on the arguments to a function expecting a
2089// format string, we will usually need to emit a warning.
2090// True string literals are then checked by CheckFormatString.
Richard Smith0e218972013-08-05 18:49:43 +00002091static StringLiteralCheckType
2092checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2093 bool HasVAListArg, unsigned format_idx,
2094 unsigned firstDataArg, Sema::FormatStringType Type,
2095 Sema::VariadicCallType CallType, bool InFunctionCall,
2096 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00002097 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00002098 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith831421f2012-06-25 20:30:08 +00002099 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002100
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002101 E = E->IgnoreParenCasts();
Peter Collingbournef111d932011-04-15 00:35:48 +00002102
Richard Smith0e218972013-08-05 18:49:43 +00002103 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikiea73cdcb2012-02-10 21:07:25 +00002104 // Technically -Wformat-nonliteral does not warn about this case.
2105 // The behavior of printf and friends in this case is implementation
2106 // dependent. Ideally if the format string cannot be null then
2107 // it should have a 'nonnull' attribute in the function prototype.
Richard Smith0e218972013-08-05 18:49:43 +00002108 return SLCT_UncheckedLiteral;
David Blaikiea73cdcb2012-02-10 21:07:25 +00002109
Ted Kremenekd30ef872009-01-12 23:09:09 +00002110 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00002111 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00002112 case Stmt::ConditionalOperatorClass: {
Richard Smith831421f2012-06-25 20:30:08 +00002113 // The expression is a literal if both sub-expressions were, and it was
2114 // completely checked only if both sub-expressions were checked.
2115 const AbstractConditionalOperator *C =
2116 cast<AbstractConditionalOperator>(E);
2117 StringLiteralCheckType Left =
Richard Smith0e218972013-08-05 18:49:43 +00002118 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00002119 HasVAListArg, format_idx, firstDataArg,
Richard Smith0e218972013-08-05 18:49:43 +00002120 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002121 if (Left == SLCT_NotALiteral)
2122 return SLCT_NotALiteral;
2123 StringLiteralCheckType Right =
Richard Smith0e218972013-08-05 18:49:43 +00002124 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00002125 HasVAListArg, format_idx, firstDataArg,
Richard Smith0e218972013-08-05 18:49:43 +00002126 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002127 return Left < Right ? Left : Right;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002128 }
2129
2130 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00002131 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2132 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002133 }
2134
John McCall56ca35d2011-02-17 10:25:35 +00002135 case Stmt::OpaqueValueExprClass:
2136 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2137 E = src;
2138 goto tryAgain;
2139 }
Richard Smith831421f2012-06-25 20:30:08 +00002140 return SLCT_NotALiteral;
John McCall56ca35d2011-02-17 10:25:35 +00002141
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00002142 case Stmt::PredefinedExprClass:
2143 // While __func__, etc., are technically not string literals, they
2144 // cannot contain format specifiers and thus are not a security
2145 // liability.
Richard Smith831421f2012-06-25 20:30:08 +00002146 return SLCT_UncheckedLiteral;
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00002147
Ted Kremenek082d9362009-03-20 21:35:28 +00002148 case Stmt::DeclRefExprClass: {
2149 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002150
Ted Kremenek082d9362009-03-20 21:35:28 +00002151 // As an exception, do not flag errors for variables binding to
2152 // const string literals.
2153 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2154 bool isConstant = false;
2155 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00002156
Richard Smith0e218972013-08-05 18:49:43 +00002157 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2158 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002159 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smith0e218972013-08-05 18:49:43 +00002160 isConstant = T.isConstant(S.Context) &&
2161 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupase98e5b52012-01-25 10:35:33 +00002162 } else if (T->isObjCObjectPointerType()) {
2163 // In ObjC, there is usually no "const ObjectPointer" type,
2164 // so don't check if the pointee type is constant.
Richard Smith0e218972013-08-05 18:49:43 +00002165 isConstant = T.isConstant(S.Context);
Ted Kremenek082d9362009-03-20 21:35:28 +00002166 }
Mike Stump1eb44332009-09-09 15:08:12 +00002167
Ted Kremenek082d9362009-03-20 21:35:28 +00002168 if (isConstant) {
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00002169 if (const Expr *Init = VD->getAnyInitializer()) {
2170 // Look through initializers like const char c[] = { "foo" }
2171 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2172 if (InitList->isStringLiteralInit())
2173 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2174 }
Richard Smith0e218972013-08-05 18:49:43 +00002175 return checkFormatStringExpr(S, Init, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002176 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002177 firstDataArg, Type, CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002178 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00002179 }
Ted Kremenek082d9362009-03-20 21:35:28 +00002180 }
Mike Stump1eb44332009-09-09 15:08:12 +00002181
Anders Carlssond966a552009-06-28 19:55:58 +00002182 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2183 // special check to see if the format string is a function parameter
2184 // of the function calling the printf function. If the function
2185 // has an attribute indicating it is a printf-like function, then we
2186 // should suppress warnings concerning non-literals being used in a call
2187 // to a vprintf function. For example:
2188 //
2189 // void
2190 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2191 // va_list ap;
2192 // va_start(ap, fmt);
2193 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2194 // ...
Richard Smith0e218972013-08-05 18:49:43 +00002195 // }
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00002196 if (HasVAListArg) {
2197 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2198 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2199 int PVIndex = PV->getFunctionScopeIndex() + 1;
Stephen Hines651f13c2014-04-23 16:59:28 -07002200 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00002201 // adjust for implicit parameter
2202 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2203 if (MD->isInstance())
2204 ++PVIndex;
2205 // We also check if the formats are compatible.
2206 // We can't pass a 'scanf' string to a 'printf' function.
2207 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smith0e218972013-08-05 18:49:43 +00002208 Type == S.GetFormatStringType(PVFormat))
Richard Smith831421f2012-06-25 20:30:08 +00002209 return SLCT_UncheckedLiteral;
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00002210 }
2211 }
2212 }
2213 }
Ted Kremenek082d9362009-03-20 21:35:28 +00002214 }
Mike Stump1eb44332009-09-09 15:08:12 +00002215
Richard Smith831421f2012-06-25 20:30:08 +00002216 return SLCT_NotALiteral;
Ted Kremenek082d9362009-03-20 21:35:28 +00002217 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00002218
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00002219 case Stmt::CallExprClass:
2220 case Stmt::CXXMemberCallExprClass: {
Anders Carlsson8f031b32009-06-27 04:05:33 +00002221 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00002222 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2223 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2224 unsigned ArgIndex = FA->getFormatIdx();
2225 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2226 if (MD->isInstance())
2227 --ArgIndex;
2228 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00002229
Richard Smith0e218972013-08-05 18:49:43 +00002230 return checkFormatStringExpr(S, Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002231 HasVAListArg, format_idx, firstDataArg,
Richard Smith0e218972013-08-05 18:49:43 +00002232 Type, CallType, InFunctionCall,
2233 CheckedVarArgs);
Jordan Rose50687312012-06-04 23:52:23 +00002234 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2235 unsigned BuiltinID = FD->getBuiltinID();
2236 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2237 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2238 const Expr *Arg = CE->getArg(0);
Richard Smith0e218972013-08-05 18:49:43 +00002239 return checkFormatStringExpr(S, Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002240 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002241 firstDataArg, Type, CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002242 InFunctionCall, CheckedVarArgs);
Jordan Rose50687312012-06-04 23:52:23 +00002243 }
Anders Carlsson8f031b32009-06-27 04:05:33 +00002244 }
2245 }
Mike Stump1eb44332009-09-09 15:08:12 +00002246
Richard Smith831421f2012-06-25 20:30:08 +00002247 return SLCT_NotALiteral;
Anders Carlsson8f031b32009-06-27 04:05:33 +00002248 }
Ted Kremenek082d9362009-03-20 21:35:28 +00002249 case Stmt::ObjCStringLiteralClass:
2250 case Stmt::StringLiteralClass: {
2251 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00002252
Ted Kremenek082d9362009-03-20 21:35:28 +00002253 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00002254 StrE = ObjCFExpr->getString();
2255 else
Ted Kremenek082d9362009-03-20 21:35:28 +00002256 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002257
Ted Kremenekd30ef872009-01-12 23:09:09 +00002258 if (StrE) {
Richard Smith0e218972013-08-05 18:49:43 +00002259 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2260 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002261 return SLCT_CheckedLiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002262 }
Mike Stump1eb44332009-09-09 15:08:12 +00002263
Richard Smith831421f2012-06-25 20:30:08 +00002264 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002265 }
Mike Stump1eb44332009-09-09 15:08:12 +00002266
Ted Kremenek082d9362009-03-20 21:35:28 +00002267 default:
Richard Smith831421f2012-06-25 20:30:08 +00002268 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002269 }
2270}
2271
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002272Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmancaa5ab22013-09-03 21:02:22 +00002273 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002274 .Case("scanf", FST_Scanf)
2275 .Cases("printf", "printf0", FST_Printf)
2276 .Cases("NSString", "CFString", FST_NSString)
2277 .Case("strftime", FST_Strftime)
2278 .Case("strfmon", FST_Strfmon)
2279 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2280 .Default(FST_Unknown);
2281}
2282
Jordan Roseddcfbc92012-07-19 18:10:23 +00002283/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek826a3452010-07-16 02:11:22 +00002284/// functions) for correct use of format strings.
Richard Smith831421f2012-06-25 20:30:08 +00002285/// Returns true if a format string has been fully checked.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002286bool Sema::CheckFormatArguments(const FormatAttr *Format,
2287 ArrayRef<const Expr *> Args,
2288 bool IsCXXMember,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002289 VariadicCallType CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002290 SourceLocation Loc, SourceRange Range,
2291 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith831421f2012-06-25 20:30:08 +00002292 FormatStringInfo FSI;
2293 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002294 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith831421f2012-06-25 20:30:08 +00002295 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smith0e218972013-08-05 18:49:43 +00002296 CallType, Loc, Range, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002297 return false;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002298}
Sebastian Redl4a2614e2009-11-17 18:02:24 +00002299
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002300bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002301 bool HasVAListArg, unsigned format_idx,
2302 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002303 VariadicCallType CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002304 SourceLocation Loc, SourceRange Range,
2305 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002306 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002307 if (format_idx >= Args.size()) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002308 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith831421f2012-06-25 20:30:08 +00002309 return false;
Ted Kremenek71895b92007-08-14 17:39:48 +00002310 }
Mike Stump1eb44332009-09-09 15:08:12 +00002311
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002312 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00002313
Chris Lattner59907c42007-08-10 20:18:51 +00002314 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00002315 //
Ted Kremenek71895b92007-08-14 17:39:48 +00002316 // Dynamically generated format strings are difficult to
2317 // automatically vet at compile time. Requiring that format strings
2318 // are string literals: (1) permits the checking of format strings by
2319 // the compiler and thereby (2) can practically remove the source of
2320 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002321
Mike Stump1eb44332009-09-09 15:08:12 +00002322 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002323 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00002324 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002325 // the same format string checking logic for both ObjC and C strings.
Richard Smith831421f2012-06-25 20:30:08 +00002326 StringLiteralCheckType CT =
Richard Smith0e218972013-08-05 18:49:43 +00002327 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2328 format_idx, firstDataArg, Type, CallType,
2329 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002330 if (CT != SLCT_NotALiteral)
2331 // Literal format string found, check done!
2332 return CT == SLCT_CheckedLiteral;
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002333
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00002334 // Strftime is particular as it always uses a single 'time' argument,
2335 // so it is safe to pass a non-literal string.
2336 if (Type == FST_Strftime)
Richard Smith831421f2012-06-25 20:30:08 +00002337 return false;
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00002338
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00002339 // Do not emit diag when the string param is a macro expansion and the
2340 // format is either NSString or CFString. This is a hack to prevent
2341 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2342 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupasdc170202012-05-04 21:08:08 +00002343 if (Type == FST_NSString &&
2344 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith831421f2012-06-25 20:30:08 +00002345 return false;
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00002346
Chris Lattner655f1412009-04-29 04:59:47 +00002347 // If there are no arguments specified, warn with -Wformat-security, otherwise
2348 // warn only with -Wformat-nonliteral.
Eli Friedman2243e782013-06-18 18:10:01 +00002349 if (Args.size() == firstDataArg)
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002350 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00002351 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00002352 << OrigFormatExpr->getSourceRange();
2353 else
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002354 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00002355 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00002356 << OrigFormatExpr->getSourceRange();
Richard Smith831421f2012-06-25 20:30:08 +00002357 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002358}
Ted Kremenek71895b92007-08-14 17:39:48 +00002359
Ted Kremeneke0e53132010-01-28 23:39:18 +00002360namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00002361class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2362protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00002363 Sema &S;
2364 const StringLiteral *FExpr;
2365 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00002366 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00002367 const unsigned NumDataArgs;
Ted Kremeneke0e53132010-01-28 23:39:18 +00002368 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00002369 const bool HasVAListArg;
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002370 ArrayRef<const Expr *> Args;
Ted Kremenek0d277352010-01-29 01:06:55 +00002371 unsigned FormatIdx;
Richard Smith0e218972013-08-05 18:49:43 +00002372 llvm::SmallBitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00002373 bool usesPositionalArgs;
2374 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00002375 bool inFunctionCall;
Jordan Roseddcfbc92012-07-19 18:10:23 +00002376 Sema::VariadicCallType CallType;
Richard Smith0e218972013-08-05 18:49:43 +00002377 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002378public:
Ted Kremenek826a3452010-07-16 02:11:22 +00002379 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00002380 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002381 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002382 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002383 unsigned formatIdx, bool inFunctionCall,
Richard Smith0e218972013-08-05 18:49:43 +00002384 Sema::VariadicCallType callType,
2385 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremeneke0e53132010-01-28 23:39:18 +00002386 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose50687312012-06-04 23:52:23 +00002387 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2388 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002389 Args(Args), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00002390 usesPositionalArgs(false), atFirstArg(true),
Richard Smith0e218972013-08-05 18:49:43 +00002391 inFunctionCall(inFunctionCall), CallType(callType),
2392 CheckedVarArgs(CheckedVarArgs) {
2393 CoveredArgs.resize(numDataArgs);
2394 CoveredArgs.reset();
2395 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002396
Ted Kremenek07d161f2010-01-29 01:50:07 +00002397 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002398
Ted Kremenek826a3452010-07-16 02:11:22 +00002399 void HandleIncompleteSpecifier(const char *startSpecifier,
Stephen Hines651f13c2014-04-23 16:59:28 -07002400 unsigned specifierLen) override;
Hans Wennborg76517422012-02-22 10:17:01 +00002401
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002402 void HandleInvalidLengthModifier(
Stephen Hines651f13c2014-04-23 16:59:28 -07002403 const analyze_format_string::FormatSpecifier &FS,
2404 const analyze_format_string::ConversionSpecifier &CS,
2405 const char *startSpecifier, unsigned specifierLen,
2406 unsigned DiagID);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002407
Hans Wennborg76517422012-02-22 10:17:01 +00002408 void HandleNonStandardLengthModifier(
Stephen Hines651f13c2014-04-23 16:59:28 -07002409 const analyze_format_string::FormatSpecifier &FS,
2410 const char *startSpecifier, unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00002411
2412 void HandleNonStandardConversionSpecifier(
Stephen Hines651f13c2014-04-23 16:59:28 -07002413 const analyze_format_string::ConversionSpecifier &CS,
2414 const char *startSpecifier, unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00002415
Stephen Hines651f13c2014-04-23 16:59:28 -07002416 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgf8562642012-03-09 10:10:54 +00002417
Stephen Hines651f13c2014-04-23 16:59:28 -07002418 void HandleInvalidPosition(const char *startSpecifier,
2419 unsigned specifierLen,
2420 analyze_format_string::PositionContext p) override;
Ted Kremenekefaff192010-02-27 01:41:03 +00002421
Stephen Hines651f13c2014-04-23 16:59:28 -07002422 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekefaff192010-02-27 01:41:03 +00002423
Stephen Hines651f13c2014-04-23 16:59:28 -07002424 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002425
Richard Trieu55733de2011-10-28 00:41:25 +00002426 template <typename Range>
2427 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2428 const Expr *ArgumentExpr,
2429 PartialDiagnostic PDiag,
2430 SourceLocation StringLoc,
2431 bool IsStringLocation, Range StringRange,
Dmitri Gribenko55431692013-05-05 00:41:58 +00002432 ArrayRef<FixItHint> Fixit = None);
Richard Trieu55733de2011-10-28 00:41:25 +00002433
Ted Kremenek826a3452010-07-16 02:11:22 +00002434protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002435 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2436 const char *startSpec,
2437 unsigned specifierLen,
2438 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00002439
2440 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2441 const char *startSpec,
2442 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002443
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002444 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00002445 CharSourceRange getSpecifierRange(const char *startSpecifier,
2446 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002447 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002448
Ted Kremenek0d277352010-01-29 01:06:55 +00002449 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00002450
2451 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2452 const analyze_format_string::ConversionSpecifier &CS,
2453 const char *startSpecifier, unsigned specifierLen,
2454 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00002455
2456 template <typename Range>
2457 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2458 bool IsStringLocation, Range StringRange,
Dmitri Gribenko55431692013-05-05 00:41:58 +00002459 ArrayRef<FixItHint> Fixit = None);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002460};
2461}
2462
Ted Kremenek826a3452010-07-16 02:11:22 +00002463SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00002464 return OrigFormatExpr->getSourceRange();
2465}
2466
Ted Kremenek826a3452010-07-16 02:11:22 +00002467CharSourceRange CheckFormatHandler::
2468getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002469 SourceLocation Start = getLocationOfByte(startSpecifier);
2470 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2471
2472 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002473 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00002474
2475 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002476}
2477
Ted Kremenek826a3452010-07-16 02:11:22 +00002478SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002479 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002480}
2481
Ted Kremenek826a3452010-07-16 02:11:22 +00002482void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2483 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00002484 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2485 getLocationOfByte(startSpecifier),
2486 /*IsStringLocation*/true,
2487 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00002488}
2489
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002490void CheckFormatHandler::HandleInvalidLengthModifier(
2491 const analyze_format_string::FormatSpecifier &FS,
2492 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00002493 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002494 using namespace analyze_format_string;
2495
2496 const LengthModifier &LM = FS.getLengthModifier();
2497 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2498
2499 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002500 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002501 if (FixedLM) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002502 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002503 getLocationOfByte(LM.getStart()),
2504 /*IsStringLocation*/true,
2505 getSpecifierRange(startSpecifier, specifierLen));
2506
2507 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2508 << FixedLM->toString()
2509 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2510
2511 } else {
Jordan Rose8be066e2012-09-08 04:00:12 +00002512 FixItHint Hint;
2513 if (DiagID == diag::warn_format_nonsensical_length)
2514 Hint = FixItHint::CreateRemoval(LMRange);
2515
2516 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002517 getLocationOfByte(LM.getStart()),
2518 /*IsStringLocation*/true,
2519 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose8be066e2012-09-08 04:00:12 +00002520 Hint);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002521 }
2522}
2523
Hans Wennborg76517422012-02-22 10:17:01 +00002524void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00002525 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00002526 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002527 using namespace analyze_format_string;
2528
2529 const LengthModifier &LM = FS.getLengthModifier();
2530 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2531
2532 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002533 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose8be066e2012-09-08 04:00:12 +00002534 if (FixedLM) {
2535 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2536 << LM.toString() << 0,
2537 getLocationOfByte(LM.getStart()),
2538 /*IsStringLocation*/true,
2539 getSpecifierRange(startSpecifier, specifierLen));
2540
2541 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2542 << FixedLM->toString()
2543 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2544
2545 } else {
2546 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2547 << LM.toString() << 0,
2548 getLocationOfByte(LM.getStart()),
2549 /*IsStringLocation*/true,
2550 getSpecifierRange(startSpecifier, specifierLen));
2551 }
Hans Wennborg76517422012-02-22 10:17:01 +00002552}
2553
2554void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2555 const analyze_format_string::ConversionSpecifier &CS,
2556 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose670941c2012-09-13 02:11:15 +00002557 using namespace analyze_format_string;
2558
2559 // See if we know how to fix this conversion specifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002560 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose670941c2012-09-13 02:11:15 +00002561 if (FixedCS) {
2562 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2563 << CS.toString() << /*conversion specifier*/1,
2564 getLocationOfByte(CS.getStart()),
2565 /*IsStringLocation*/true,
2566 getSpecifierRange(startSpecifier, specifierLen));
2567
2568 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2569 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2570 << FixedCS->toString()
2571 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2572 } else {
2573 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2574 << CS.toString() << /*conversion specifier*/1,
2575 getLocationOfByte(CS.getStart()),
2576 /*IsStringLocation*/true,
2577 getSpecifierRange(startSpecifier, specifierLen));
2578 }
Hans Wennborg76517422012-02-22 10:17:01 +00002579}
2580
Hans Wennborgf8562642012-03-09 10:10:54 +00002581void CheckFormatHandler::HandlePosition(const char *startPos,
2582 unsigned posLen) {
2583 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2584 getLocationOfByte(startPos),
2585 /*IsStringLocation*/true,
2586 getSpecifierRange(startPos, posLen));
2587}
2588
Ted Kremenekefaff192010-02-27 01:41:03 +00002589void
Ted Kremenek826a3452010-07-16 02:11:22 +00002590CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2591 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00002592 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2593 << (unsigned) p,
2594 getLocationOfByte(startPos), /*IsStringLocation*/true,
2595 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002596}
2597
Ted Kremenek826a3452010-07-16 02:11:22 +00002598void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00002599 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00002600 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2601 getLocationOfByte(startPos),
2602 /*IsStringLocation*/true,
2603 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002604}
2605
Ted Kremenek826a3452010-07-16 02:11:22 +00002606void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose50687312012-06-04 23:52:23 +00002607 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0c069442011-03-15 21:18:48 +00002608 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00002609 EmitFormatDiagnostic(
2610 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2611 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2612 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00002613 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002614}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002615
Jordan Rose48716662012-07-19 18:10:08 +00002616// Note that this may return NULL if there was an error parsing or building
2617// one of the argument expressions.
Ted Kremenek826a3452010-07-16 02:11:22 +00002618const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002619 return Args[FirstDataArg + i];
Ted Kremenek826a3452010-07-16 02:11:22 +00002620}
2621
2622void CheckFormatHandler::DoneProcessing() {
2623 // Does the number of data arguments exceed the number of
2624 // format conversions in the format string?
2625 if (!HasVAListArg) {
2626 // Find any arguments that weren't covered.
2627 CoveredArgs.flip();
2628 signed notCoveredArg = CoveredArgs.find_first();
2629 if (notCoveredArg >= 0) {
2630 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose48716662012-07-19 18:10:08 +00002631 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2632 SourceLocation Loc = E->getLocStart();
2633 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2634 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2635 Loc, /*IsStringLocation*/false,
2636 getFormatStringRange());
2637 }
Bob Wilsonc03f2df2012-05-03 19:47:19 +00002638 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002639 }
2640 }
2641}
2642
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002643bool
2644CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2645 SourceLocation Loc,
2646 const char *startSpec,
2647 unsigned specifierLen,
2648 const char *csStart,
2649 unsigned csLen) {
2650
2651 bool keepGoing = true;
2652 if (argIndex < NumDataArgs) {
2653 // Consider the argument coverered, even though the specifier doesn't
2654 // make sense.
2655 CoveredArgs.set(argIndex);
2656 }
2657 else {
2658 // If argIndex exceeds the number of data arguments we
2659 // don't issue a warning because that is just a cascade of warnings (and
2660 // they may have intended '%%' anyway). We don't want to continue processing
2661 // the format string after this point, however, as we will like just get
2662 // gibberish when trying to match arguments.
2663 keepGoing = false;
2664 }
2665
Richard Trieu55733de2011-10-28 00:41:25 +00002666 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2667 << StringRef(csStart, csLen),
2668 Loc, /*IsStringLocation*/true,
2669 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002670
2671 return keepGoing;
2672}
2673
Richard Trieu55733de2011-10-28 00:41:25 +00002674void
2675CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2676 const char *startSpec,
2677 unsigned specifierLen) {
2678 EmitFormatDiagnostic(
2679 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2680 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2681}
2682
Ted Kremenek666a1972010-07-26 19:45:42 +00002683bool
2684CheckFormatHandler::CheckNumArgs(
2685 const analyze_format_string::FormatSpecifier &FS,
2686 const analyze_format_string::ConversionSpecifier &CS,
2687 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2688
2689 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002690 PartialDiagnostic PDiag = FS.usesPositionalArg()
2691 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2692 << (argIndex+1) << NumDataArgs)
2693 : S.PDiag(diag::warn_printf_insufficient_data_args);
2694 EmitFormatDiagnostic(
2695 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2696 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00002697 return false;
2698 }
2699 return true;
2700}
2701
Richard Trieu55733de2011-10-28 00:41:25 +00002702template<typename Range>
2703void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2704 SourceLocation Loc,
2705 bool IsStringLocation,
2706 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002707 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002708 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu55733de2011-10-28 00:41:25 +00002709 Loc, IsStringLocation, StringRange, FixIt);
2710}
2711
2712/// \brief If the format string is not within the funcion call, emit a note
2713/// so that the function call and string are in diagnostic messages.
2714///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002715/// \param InFunctionCall if true, the format string is within the function
Richard Trieu55733de2011-10-28 00:41:25 +00002716/// call and only one diagnostic message will be produced. Otherwise, an
2717/// extra note will be emitted pointing to location of the format string.
2718///
2719/// \param ArgumentExpr the expression that is passed as the format string
2720/// argument in the function call. Used for getting locations when two
2721/// diagnostics are emitted.
2722///
2723/// \param PDiag the callee should already have provided any strings for the
2724/// diagnostic message. This function only adds locations and fixits
2725/// to diagnostics.
2726///
2727/// \param Loc primary location for diagnostic. If two diagnostics are
2728/// required, one will be at Loc and a new SourceLocation will be created for
2729/// the other one.
2730///
2731/// \param IsStringLocation if true, Loc points to the format string should be
2732/// used for the note. Otherwise, Loc points to the argument list and will
2733/// be used with PDiag.
2734///
2735/// \param StringRange some or all of the string to highlight. This is
2736/// templated so it can accept either a CharSourceRange or a SourceRange.
2737///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002738/// \param FixIt optional fix it hint for the format string.
Richard Trieu55733de2011-10-28 00:41:25 +00002739template<typename Range>
2740void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2741 const Expr *ArgumentExpr,
2742 PartialDiagnostic PDiag,
2743 SourceLocation Loc,
2744 bool IsStringLocation,
2745 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002746 ArrayRef<FixItHint> FixIt) {
2747 if (InFunctionCall) {
2748 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2749 D << StringRange;
2750 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2751 I != E; ++I) {
2752 D << *I;
2753 }
2754 } else {
Richard Trieu55733de2011-10-28 00:41:25 +00002755 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2756 << ArgumentExpr->getSourceRange();
Jordan Roseec087352012-09-05 22:56:26 +00002757
2758 const Sema::SemaDiagnosticBuilder &Note =
2759 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2760 diag::note_format_string_defined);
2761
2762 Note << StringRange;
2763 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2764 I != E; ++I) {
2765 Note << *I;
2766 }
Richard Trieu55733de2011-10-28 00:41:25 +00002767 }
2768}
2769
Ted Kremenek826a3452010-07-16 02:11:22 +00002770//===--- CHECK: Printf format string checking ------------------------------===//
2771
2772namespace {
2773class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose50687312012-06-04 23:52:23 +00002774 bool ObjCContext;
Ted Kremenek826a3452010-07-16 02:11:22 +00002775public:
2776 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2777 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002778 unsigned numDataArgs, bool isObjC,
Ted Kremenek826a3452010-07-16 02:11:22 +00002779 const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002780 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002781 unsigned formatIdx, bool inFunctionCall,
Richard Smith0e218972013-08-05 18:49:43 +00002782 Sema::VariadicCallType CallType,
2783 llvm::SmallBitVector &CheckedVarArgs)
2784 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2785 numDataArgs, beg, hasVAListArg, Args,
2786 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
2787 ObjCContext(isObjC)
Jordan Roseddcfbc92012-07-19 18:10:23 +00002788 {}
2789
Stephen Hines651f13c2014-04-23 16:59:28 -07002790
Ted Kremenek826a3452010-07-16 02:11:22 +00002791 bool HandleInvalidPrintfConversionSpecifier(
2792 const analyze_printf::PrintfSpecifier &FS,
2793 const char *startSpecifier,
Stephen Hines651f13c2014-04-23 16:59:28 -07002794 unsigned specifierLen) override;
2795
Ted Kremenek826a3452010-07-16 02:11:22 +00002796 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2797 const char *startSpecifier,
Stephen Hines651f13c2014-04-23 16:59:28 -07002798 unsigned specifierLen) override;
Richard Smith831421f2012-06-25 20:30:08 +00002799 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2800 const char *StartSpecifier,
2801 unsigned SpecifierLen,
2802 const Expr *E);
2803
Ted Kremenek826a3452010-07-16 02:11:22 +00002804 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2805 const char *startSpecifier, unsigned specifierLen);
2806 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2807 const analyze_printf::OptionalAmount &Amt,
2808 unsigned type,
2809 const char *startSpecifier, unsigned specifierLen);
2810 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2811 const analyze_printf::OptionalFlag &flag,
2812 const char *startSpecifier, unsigned specifierLen);
2813 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2814 const analyze_printf::OptionalFlag &ignoredFlag,
2815 const analyze_printf::OptionalFlag &flag,
2816 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgf3749f42012-08-07 08:11:26 +00002817 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Stephen Hines651f13c2014-04-23 16:59:28 -07002818 const Expr *E);
Richard Smith831421f2012-06-25 20:30:08 +00002819
Ted Kremenek826a3452010-07-16 02:11:22 +00002820};
2821}
2822
2823bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2824 const analyze_printf::PrintfSpecifier &FS,
2825 const char *startSpecifier,
2826 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002827 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002828 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002829
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002830 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2831 getLocationOfByte(CS.getStart()),
2832 startSpecifier, specifierLen,
2833 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00002834}
2835
Ted Kremenek826a3452010-07-16 02:11:22 +00002836bool CheckPrintfHandler::HandleAmount(
2837 const analyze_format_string::OptionalAmount &Amt,
2838 unsigned k, const char *startSpecifier,
2839 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002840
2841 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002842 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002843 unsigned argIndex = Amt.getArgIndex();
2844 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002845 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2846 << k,
2847 getLocationOfByte(Amt.getStart()),
2848 /*IsStringLocation*/true,
2849 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002850 // Don't do any more checking. We will just emit
2851 // spurious errors.
2852 return false;
2853 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002854
Ted Kremenek0d277352010-01-29 01:06:55 +00002855 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00002856 // Although not in conformance with C99, we also allow the argument to be
2857 // an 'unsigned int' as that is a reasonably safe case. GCC also
2858 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002859 CoveredArgs.set(argIndex);
2860 const Expr *Arg = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00002861 if (!Arg)
2862 return false;
2863
Ted Kremenek0d277352010-01-29 01:06:55 +00002864 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002865
Hans Wennborgf3749f42012-08-07 08:11:26 +00002866 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2867 assert(AT.isValid());
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002868
Hans Wennborgf3749f42012-08-07 08:11:26 +00002869 if (!AT.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00002870 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgf3749f42012-08-07 08:11:26 +00002871 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00002872 << T << Arg->getSourceRange(),
2873 getLocationOfByte(Amt.getStart()),
2874 /*IsStringLocation*/true,
2875 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002876 // Don't do any more checking. We will just emit
2877 // spurious errors.
2878 return false;
2879 }
2880 }
2881 }
2882 return true;
2883}
Ted Kremenek0d277352010-01-29 01:06:55 +00002884
Tom Caree4ee9662010-06-17 19:00:27 +00002885void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00002886 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002887 const analyze_printf::OptionalAmount &Amt,
2888 unsigned type,
2889 const char *startSpecifier,
2890 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002891 const analyze_printf::PrintfConversionSpecifier &CS =
2892 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00002893
Richard Trieu55733de2011-10-28 00:41:25 +00002894 FixItHint fixit =
2895 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2896 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2897 Amt.getConstantLength()))
2898 : FixItHint();
2899
2900 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2901 << type << CS.toString(),
2902 getLocationOfByte(Amt.getStart()),
2903 /*IsStringLocation*/true,
2904 getSpecifierRange(startSpecifier, specifierLen),
2905 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00002906}
2907
Ted Kremenek826a3452010-07-16 02:11:22 +00002908void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002909 const analyze_printf::OptionalFlag &flag,
2910 const char *startSpecifier,
2911 unsigned specifierLen) {
2912 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002913 const analyze_printf::PrintfConversionSpecifier &CS =
2914 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00002915 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2916 << flag.toString() << CS.toString(),
2917 getLocationOfByte(flag.getPosition()),
2918 /*IsStringLocation*/true,
2919 getSpecifierRange(startSpecifier, specifierLen),
2920 FixItHint::CreateRemoval(
2921 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002922}
2923
2924void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00002925 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002926 const analyze_printf::OptionalFlag &ignoredFlag,
2927 const analyze_printf::OptionalFlag &flag,
2928 const char *startSpecifier,
2929 unsigned specifierLen) {
2930 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00002931 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2932 << ignoredFlag.toString() << flag.toString(),
2933 getLocationOfByte(ignoredFlag.getPosition()),
2934 /*IsStringLocation*/true,
2935 getSpecifierRange(startSpecifier, specifierLen),
2936 FixItHint::CreateRemoval(
2937 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002938}
2939
Richard Smith831421f2012-06-25 20:30:08 +00002940// Determines if the specified is a C++ class or struct containing
2941// a member with the specified name and kind (e.g. a CXXMethodDecl named
2942// "c_str()").
2943template<typename MemberKind>
2944static llvm::SmallPtrSet<MemberKind*, 1>
2945CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2946 const RecordType *RT = Ty->getAs<RecordType>();
2947 llvm::SmallPtrSet<MemberKind*, 1> Results;
2948
2949 if (!RT)
2950 return Results;
2951 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Stephen Hines651f13c2014-04-23 16:59:28 -07002952 if (!RD || !RD->getDefinition())
Richard Smith831421f2012-06-25 20:30:08 +00002953 return Results;
2954
2955 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2956 Sema::LookupMemberName);
Stephen Hines651f13c2014-04-23 16:59:28 -07002957 R.suppressDiagnostics();
Richard Smith831421f2012-06-25 20:30:08 +00002958
2959 // We just need to include all members of the right kind turned up by the
2960 // filter, at this point.
2961 if (S.LookupQualifiedName(R, RT->getDecl()))
2962 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2963 NamedDecl *decl = (*I)->getUnderlyingDecl();
2964 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2965 Results.insert(FK);
2966 }
2967 return Results;
2968}
2969
Stephen Hines651f13c2014-04-23 16:59:28 -07002970/// Check if we could call '.c_str()' on an object.
2971///
2972/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
2973/// allow the call, or if it would be ambiguous).
2974bool Sema::hasCStrMethod(const Expr *E) {
2975 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2976 MethodSet Results =
2977 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
2978 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2979 MI != ME; ++MI)
2980 if ((*MI)->getMinRequiredArguments() == 0)
2981 return true;
2982 return false;
2983}
2984
Richard Smith831421f2012-06-25 20:30:08 +00002985// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgf3749f42012-08-07 08:11:26 +00002986// better diagnostic if so. AT is assumed to be valid.
Richard Smith831421f2012-06-25 20:30:08 +00002987// Returns true when a c_str() conversion method is found.
2988bool CheckPrintfHandler::checkForCStrMembers(
Stephen Hines651f13c2014-04-23 16:59:28 -07002989 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith831421f2012-06-25 20:30:08 +00002990 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2991
2992 MethodSet Results =
2993 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2994
2995 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2996 MI != ME; ++MI) {
2997 const CXXMethodDecl *Method = *MI;
Stephen Hines651f13c2014-04-23 16:59:28 -07002998 if (Method->getMinRequiredArguments() == 0 &&
2999 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith831421f2012-06-25 20:30:08 +00003000 // FIXME: Suggest parens if the expression needs them.
3001 SourceLocation EndLoc =
3002 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
3003 S.Diag(E->getLocStart(), diag::note_printf_c_str)
3004 << "c_str()"
3005 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
3006 return true;
3007 }
3008 }
3009
3010 return false;
3011}
3012
Ted Kremeneke0e53132010-01-28 23:39:18 +00003013bool
Ted Kremenek826a3452010-07-16 02:11:22 +00003014CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00003015 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00003016 const char *startSpecifier,
3017 unsigned specifierLen) {
3018
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003019 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00003020 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003021 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00003022
Ted Kremenekbaa40062010-07-19 22:01:06 +00003023 if (FS.consumesDataArgument()) {
3024 if (atFirstArg) {
3025 atFirstArg = false;
3026 usesPositionalArgs = FS.usesPositionalArg();
3027 }
3028 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003029 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3030 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00003031 return false;
3032 }
Ted Kremenek0d277352010-01-29 01:06:55 +00003033 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003034
Ted Kremenekefaff192010-02-27 01:41:03 +00003035 // First check if the field width, precision, and conversion specifier
3036 // have matching data arguments.
3037 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
3038 startSpecifier, specifierLen)) {
3039 return false;
3040 }
3041
3042 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
3043 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00003044 return false;
3045 }
3046
Ted Kremenekf88c8e02010-01-29 20:55:36 +00003047 if (!CS.consumesDataArgument()) {
3048 // FIXME: Technically specifying a precision or field width here
3049 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00003050 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00003051 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003052
Ted Kremenek7f70dc82010-02-26 19:18:41 +00003053 // Consume the argument.
3054 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00003055 if (argIndex < NumDataArgs) {
3056 // The check to see if the argIndex is valid will come later.
3057 // We set the bit here because we may exit early from this
3058 // function if we encounter some other error.
3059 CoveredArgs.set(argIndex);
3060 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00003061
3062 // Check for using an Objective-C specific conversion specifier
3063 // in a non-ObjC literal.
Jordan Rose50687312012-06-04 23:52:23 +00003064 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003065 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3066 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00003067 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003068
Tom Caree4ee9662010-06-17 19:00:27 +00003069 // Check for invalid use of field width
3070 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00003071 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00003072 startSpecifier, specifierLen);
3073 }
3074
3075 // Check for invalid use of precision
3076 if (!FS.hasValidPrecision()) {
3077 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3078 startSpecifier, specifierLen);
3079 }
3080
3081 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00003082 if (!FS.hasValidThousandsGroupingPrefix())
3083 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00003084 if (!FS.hasValidLeadingZeros())
3085 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3086 if (!FS.hasValidPlusPrefix())
3087 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00003088 if (!FS.hasValidSpacePrefix())
3089 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00003090 if (!FS.hasValidAlternativeForm())
3091 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3092 if (!FS.hasValidLeftJustified())
3093 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3094
3095 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00003096 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3097 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3098 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00003099 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3100 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3101 startSpecifier, specifierLen);
3102
3103 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003104 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00003105 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3106 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003107 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00003108 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003109 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00003110 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3111 diag::warn_format_non_standard_conversion_spec);
Tom Caree4ee9662010-06-17 19:00:27 +00003112
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003113 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3114 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3115
Ted Kremenekda51f0d2010-01-29 01:43:31 +00003116 // The remaining checks depend on the data arguments.
3117 if (HasVAListArg)
3118 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003119
Ted Kremenek666a1972010-07-26 19:45:42 +00003120 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00003121 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003122
Jordan Rose48716662012-07-19 18:10:08 +00003123 const Expr *Arg = getDataArg(argIndex);
3124 if (!Arg)
3125 return true;
3126
3127 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith831421f2012-06-25 20:30:08 +00003128}
3129
Jordan Roseec087352012-09-05 22:56:26 +00003130static bool requiresParensToAddCast(const Expr *E) {
3131 // FIXME: We should have a general way to reason about operator
3132 // precedence and whether parens are actually needed here.
3133 // Take care of a few common cases where they aren't.
3134 const Expr *Inside = E->IgnoreImpCasts();
3135 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3136 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3137
3138 switch (Inside->getStmtClass()) {
3139 case Stmt::ArraySubscriptExprClass:
3140 case Stmt::CallExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003141 case Stmt::CharacterLiteralClass:
3142 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00003143 case Stmt::DeclRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003144 case Stmt::FloatingLiteralClass:
3145 case Stmt::IntegerLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00003146 case Stmt::MemberExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003147 case Stmt::ObjCArrayLiteralClass:
3148 case Stmt::ObjCBoolLiteralExprClass:
3149 case Stmt::ObjCBoxedExprClass:
3150 case Stmt::ObjCDictionaryLiteralClass:
3151 case Stmt::ObjCEncodeExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00003152 case Stmt::ObjCIvarRefExprClass:
3153 case Stmt::ObjCMessageExprClass:
3154 case Stmt::ObjCPropertyRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003155 case Stmt::ObjCStringLiteralClass:
3156 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00003157 case Stmt::ParenExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003158 case Stmt::StringLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00003159 case Stmt::UnaryOperatorClass:
3160 return false;
3161 default:
3162 return true;
3163 }
3164}
3165
Richard Smith831421f2012-06-25 20:30:08 +00003166bool
3167CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3168 const char *StartSpecifier,
3169 unsigned SpecifierLen,
3170 const Expr *E) {
3171 using namespace analyze_format_string;
3172 using namespace analyze_printf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003173 // Now type check the data expression that matches the
3174 // format specifier.
Hans Wennborgf3749f42012-08-07 08:11:26 +00003175 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3176 ObjCContext);
Jordan Rose614a8652012-09-05 22:56:19 +00003177 if (!AT.isValid())
3178 return true;
Jordan Roseec087352012-09-05 22:56:26 +00003179
Jordan Rose448ac3e2012-12-05 18:44:40 +00003180 QualType ExprTy = E->getType();
Ted Kremenek02be9682013-04-10 06:26:26 +00003181 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3182 ExprTy = TET->getUnderlyingExpr()->getType();
3183 }
3184
Jordan Rose448ac3e2012-12-05 18:44:40 +00003185 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00003186 return true;
Jordan Roseee0259d2012-06-04 22:48:57 +00003187
Jordan Rose614a8652012-09-05 22:56:19 +00003188 // Look through argument promotions for our error message's reported type.
3189 // This includes the integral and floating promotions, but excludes array
3190 // and function pointer decay; seeing that an argument intended to be a
3191 // string has type 'char [6]' is probably more confusing than 'char *'.
3192 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3193 if (ICE->getCastKind() == CK_IntegralCast ||
3194 ICE->getCastKind() == CK_FloatingCast) {
3195 E = ICE->getSubExpr();
Jordan Rose448ac3e2012-12-05 18:44:40 +00003196 ExprTy = E->getType();
Jordan Rose614a8652012-09-05 22:56:19 +00003197
3198 // Check if we didn't match because of an implicit cast from a 'char'
3199 // or 'short' to an 'int'. This is done because printf is a varargs
3200 // function.
3201 if (ICE->getType() == S.Context.IntTy ||
3202 ICE->getType() == S.Context.UnsignedIntTy) {
3203 // All further checking is done on the subexpression.
Jordan Rose448ac3e2012-12-05 18:44:40 +00003204 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00003205 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00003206 }
Jordan Roseee0259d2012-06-04 22:48:57 +00003207 }
Jordan Rose448ac3e2012-12-05 18:44:40 +00003208 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3209 // Special case for 'a', which has type 'int' in C.
3210 // Note, however, that we do /not/ want to treat multibyte constants like
3211 // 'MooV' as characters! This form is deprecated but still exists.
3212 if (ExprTy == S.Context.IntTy)
3213 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3214 ExprTy = S.Context.CharTy;
Jordan Rose614a8652012-09-05 22:56:19 +00003215 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003216
Jordan Rose2cd34402012-12-05 18:44:49 +00003217 // %C in an Objective-C context prints a unichar, not a wchar_t.
3218 // If the argument is an integer of some kind, believe the %C and suggest
3219 // a cast instead of changing the conversion specifier.
Jordan Rose448ac3e2012-12-05 18:44:40 +00003220 QualType IntendedTy = ExprTy;
Jordan Rose2cd34402012-12-05 18:44:49 +00003221 if (ObjCContext &&
3222 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3223 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3224 !ExprTy->isCharType()) {
3225 // 'unichar' is defined as a typedef of unsigned short, but we should
3226 // prefer using the typedef if it is visible.
3227 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenek656465d2013-10-15 05:25:17 +00003228
3229 // While we are here, check if the value is an IntegerLiteral that happens
3230 // to be within the valid range.
3231 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3232 const llvm::APInt &V = IL->getValue();
3233 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3234 return true;
3235 }
3236
Jordan Rose2cd34402012-12-05 18:44:49 +00003237 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3238 Sema::LookupOrdinaryName);
3239 if (S.LookupName(Result, S.getCurScope())) {
3240 NamedDecl *ND = Result.getFoundDecl();
3241 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3242 if (TD->getUnderlyingType() == IntendedTy)
3243 IntendedTy = S.Context.getTypedefType(TD);
3244 }
3245 }
3246 }
3247
3248 // Special-case some of Darwin's platform-independence types by suggesting
3249 // casts to primitive types that are known to be large enough.
3250 bool ShouldNotPrintDirectly = false;
Jordan Roseec087352012-09-05 22:56:26 +00003251 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Ted Kremenek6edb0292013-03-25 22:28:37 +00003252 // Use a 'while' to peel off layers of typedefs.
3253 QualType TyTy = IntendedTy;
3254 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
Jordan Roseec087352012-09-05 22:56:26 +00003255 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose2cd34402012-12-05 18:44:49 +00003256 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseec087352012-09-05 22:56:26 +00003257 .Case("NSInteger", S.Context.LongTy)
3258 .Case("NSUInteger", S.Context.UnsignedLongTy)
3259 .Case("SInt32", S.Context.IntTy)
3260 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose2cd34402012-12-05 18:44:49 +00003261 .Default(QualType());
3262
3263 if (!CastTy.isNull()) {
3264 ShouldNotPrintDirectly = true;
3265 IntendedTy = CastTy;
Ted Kremenek6edb0292013-03-25 22:28:37 +00003266 break;
Jordan Rose2cd34402012-12-05 18:44:49 +00003267 }
Ted Kremenek6edb0292013-03-25 22:28:37 +00003268 TyTy = UserTy->desugar();
Jordan Roseec087352012-09-05 22:56:26 +00003269 }
3270 }
3271
Jordan Rose614a8652012-09-05 22:56:19 +00003272 // We may be able to offer a FixItHint if it is a supported type.
3273 PrintfSpecifier fixedFS = FS;
Jordan Roseec087352012-09-05 22:56:26 +00003274 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose614a8652012-09-05 22:56:19 +00003275 S.Context, ObjCContext);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003276
Jordan Rose614a8652012-09-05 22:56:19 +00003277 if (success) {
3278 // Get the fix string from the fixed format specifier
3279 SmallString<16> buf;
3280 llvm::raw_svector_ostream os(buf);
3281 fixedFS.toString(os);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003282
Jordan Roseec087352012-09-05 22:56:26 +00003283 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3284
Jordan Rose2cd34402012-12-05 18:44:49 +00003285 if (IntendedTy == ExprTy) {
3286 // In this case, the specifier is wrong and should be changed to match
3287 // the argument.
3288 EmitFormatDiagnostic(
3289 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3290 << AT.getRepresentativeTypeName(S.Context) << IntendedTy
3291 << E->getSourceRange(),
3292 E->getLocStart(),
3293 /*IsStringLocation*/false,
3294 SpecRange,
3295 FixItHint::CreateReplacement(SpecRange, os.str()));
3296
3297 } else {
Jordan Roseec087352012-09-05 22:56:26 +00003298 // The canonical type for formatting this value is different from the
3299 // actual type of the expression. (This occurs, for example, with Darwin's
3300 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3301 // should be printed as 'long' for 64-bit compatibility.)
3302 // Rather than emitting a normal format/argument mismatch, we want to
3303 // add a cast to the recommended type (and correct the format string
3304 // if necessary).
3305 SmallString<16> CastBuf;
3306 llvm::raw_svector_ostream CastFix(CastBuf);
3307 CastFix << "(";
3308 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3309 CastFix << ")";
3310
3311 SmallVector<FixItHint,4> Hints;
3312 if (!AT.matchesType(S.Context, IntendedTy))
3313 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3314
3315 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3316 // If there's already a cast present, just replace it.
3317 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3318 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3319
3320 } else if (!requiresParensToAddCast(E)) {
3321 // If the expression has high enough precedence,
3322 // just write the C-style cast.
3323 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3324 CastFix.str()));
3325 } else {
3326 // Otherwise, add parens around the expression as well as the cast.
3327 CastFix << "(";
3328 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3329 CastFix.str()));
3330
3331 SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
3332 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3333 }
3334
Jordan Rose2cd34402012-12-05 18:44:49 +00003335 if (ShouldNotPrintDirectly) {
3336 // The expression has a type that should not be printed directly.
3337 // We extract the name from the typedef because we don't want to show
3338 // the underlying type in the diagnostic.
3339 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseec087352012-09-05 22:56:26 +00003340
Jordan Rose2cd34402012-12-05 18:44:49 +00003341 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
3342 << Name << IntendedTy
3343 << E->getSourceRange(),
3344 E->getLocStart(), /*IsStringLocation=*/false,
3345 SpecRange, Hints);
3346 } else {
3347 // In this case, the expression could be printed using a different
3348 // specifier, but we've decided that the specifier is probably correct
3349 // and we should cast instead. Just use the normal warning message.
3350 EmitFormatDiagnostic(
3351 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3352 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3353 << E->getSourceRange(),
3354 E->getLocStart(), /*IsStringLocation*/false,
3355 SpecRange, Hints);
3356 }
Jordan Roseec087352012-09-05 22:56:26 +00003357 }
Jordan Rose614a8652012-09-05 22:56:19 +00003358 } else {
3359 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3360 SpecifierLen);
3361 // Since the warning for passing non-POD types to variadic functions
3362 // was deferred until now, we emit a warning for non-POD
3363 // arguments here.
Richard Smith0e218972013-08-05 18:49:43 +00003364 switch (S.isValidVarArgType(ExprTy)) {
3365 case Sema::VAK_Valid:
3366 case Sema::VAK_ValidInCXX11:
Jordan Rose614a8652012-09-05 22:56:19 +00003367 EmitFormatDiagnostic(
Richard Smith0e218972013-08-05 18:49:43 +00003368 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3369 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3370 << CSR
3371 << E->getSourceRange(),
3372 E->getLocStart(), /*IsStringLocation*/false, CSR);
3373 break;
3374
3375 case Sema::VAK_Undefined:
3376 EmitFormatDiagnostic(
3377 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith80ad52f2013-01-02 11:42:31 +00003378 << S.getLangOpts().CPlusPlus11
Jordan Rose448ac3e2012-12-05 18:44:40 +00003379 << ExprTy
Jordan Rose614a8652012-09-05 22:56:19 +00003380 << CallType
3381 << AT.getRepresentativeTypeName(S.Context)
3382 << CSR
3383 << E->getSourceRange(),
3384 E->getLocStart(), /*IsStringLocation*/false, CSR);
Stephen Hines651f13c2014-04-23 16:59:28 -07003385 checkForCStrMembers(AT, E);
Richard Smith0e218972013-08-05 18:49:43 +00003386 break;
3387
3388 case Sema::VAK_Invalid:
3389 if (ExprTy->isObjCObjectType())
3390 EmitFormatDiagnostic(
3391 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3392 << S.getLangOpts().CPlusPlus11
3393 << ExprTy
3394 << CallType
3395 << AT.getRepresentativeTypeName(S.Context)
3396 << CSR
3397 << E->getSourceRange(),
3398 E->getLocStart(), /*IsStringLocation*/false, CSR);
3399 else
3400 // FIXME: If this is an initializer list, suggest removing the braces
3401 // or inserting a cast to the target type.
3402 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3403 << isa<InitListExpr>(E) << ExprTy << CallType
3404 << AT.getRepresentativeTypeName(S.Context)
3405 << E->getSourceRange();
3406 break;
3407 }
3408
3409 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3410 "format string specifier index out of range");
3411 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003412 }
3413
Ted Kremeneke0e53132010-01-28 23:39:18 +00003414 return true;
3415}
3416
Ted Kremenek826a3452010-07-16 02:11:22 +00003417//===--- CHECK: Scanf format string checking ------------------------------===//
3418
3419namespace {
3420class CheckScanfHandler : public CheckFormatHandler {
3421public:
3422 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3423 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003424 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003425 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003426 unsigned formatIdx, bool inFunctionCall,
Richard Smith0e218972013-08-05 18:49:43 +00003427 Sema::VariadicCallType CallType,
3428 llvm::SmallBitVector &CheckedVarArgs)
3429 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3430 numDataArgs, beg, hasVAListArg,
3431 Args, formatIdx, inFunctionCall, CallType,
3432 CheckedVarArgs)
Jordan Roseddcfbc92012-07-19 18:10:23 +00003433 {}
Ted Kremenek826a3452010-07-16 02:11:22 +00003434
3435 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3436 const char *startSpecifier,
Stephen Hines651f13c2014-04-23 16:59:28 -07003437 unsigned specifierLen) override;
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003438
3439 bool HandleInvalidScanfConversionSpecifier(
3440 const analyze_scanf::ScanfSpecifier &FS,
3441 const char *startSpecifier,
Stephen Hines651f13c2014-04-23 16:59:28 -07003442 unsigned specifierLen) override;
Ted Kremenekb7c21012010-07-16 18:28:03 +00003443
Stephen Hines651f13c2014-04-23 16:59:28 -07003444 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek826a3452010-07-16 02:11:22 +00003445};
Ted Kremenek07d161f2010-01-29 01:50:07 +00003446}
Ted Kremeneke0e53132010-01-28 23:39:18 +00003447
Ted Kremenekb7c21012010-07-16 18:28:03 +00003448void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3449 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00003450 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3451 getLocationOfByte(end), /*IsStringLocation*/true,
3452 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00003453}
3454
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003455bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3456 const analyze_scanf::ScanfSpecifier &FS,
3457 const char *startSpecifier,
3458 unsigned specifierLen) {
3459
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003460 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003461 FS.getConversionSpecifier();
3462
3463 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3464 getLocationOfByte(CS.getStart()),
3465 startSpecifier, specifierLen,
3466 CS.getStart(), CS.getLength());
3467}
3468
Ted Kremenek826a3452010-07-16 02:11:22 +00003469bool CheckScanfHandler::HandleScanfSpecifier(
3470 const analyze_scanf::ScanfSpecifier &FS,
3471 const char *startSpecifier,
3472 unsigned specifierLen) {
3473
3474 using namespace analyze_scanf;
3475 using namespace analyze_format_string;
3476
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003477 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00003478
Ted Kremenekbaa40062010-07-19 22:01:06 +00003479 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3480 // be used to decide if we are using positional arguments consistently.
3481 if (FS.consumesDataArgument()) {
3482 if (atFirstArg) {
3483 atFirstArg = false;
3484 usesPositionalArgs = FS.usesPositionalArg();
3485 }
3486 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003487 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3488 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00003489 return false;
3490 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003491 }
3492
3493 // Check if the field with is non-zero.
3494 const OptionalAmount &Amt = FS.getFieldWidth();
3495 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3496 if (Amt.getConstantAmount() == 0) {
3497 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3498 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00003499 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3500 getLocationOfByte(Amt.getStart()),
3501 /*IsStringLocation*/true, R,
3502 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00003503 }
3504 }
3505
3506 if (!FS.consumesDataArgument()) {
3507 // FIXME: Technically specifying a precision or field width here
3508 // makes no sense. Worth issuing a warning at some point.
3509 return true;
3510 }
3511
3512 // Consume the argument.
3513 unsigned argIndex = FS.getArgIndex();
3514 if (argIndex < NumDataArgs) {
3515 // The check to see if the argIndex is valid will come later.
3516 // We set the bit here because we may exit early from this
3517 // function if we encounter some other error.
3518 CoveredArgs.set(argIndex);
3519 }
3520
Ted Kremenek1e51c202010-07-20 20:04:47 +00003521 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003522 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00003523 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3524 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003525 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00003526 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003527 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00003528 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3529 diag::warn_format_non_standard_conversion_spec);
Hans Wennborg76517422012-02-22 10:17:01 +00003530
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003531 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3532 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3533
Ted Kremenek826a3452010-07-16 02:11:22 +00003534 // The remaining checks depend on the data arguments.
3535 if (HasVAListArg)
3536 return true;
3537
Ted Kremenek666a1972010-07-26 19:45:42 +00003538 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00003539 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00003540
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003541 // Check that the argument type matches the format specifier.
3542 const Expr *Ex = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00003543 if (!Ex)
3544 return true;
3545
Hans Wennborg58e1e542012-08-07 08:59:46 +00003546 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3547 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003548 ScanfSpecifier fixedFS = FS;
Stephen Hines651f13c2014-04-23 16:59:28 -07003549 bool success = fixedFS.fixType(Ex->getType(),
3550 Ex->IgnoreImpCasts()->getType(),
3551 S.getLangOpts(), S.Context);
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003552
3553 if (success) {
3554 // Get the fix string from the fixed format specifier.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003555 SmallString<128> buf;
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003556 llvm::raw_svector_ostream os(buf);
3557 fixedFS.toString(os);
3558
3559 EmitFormatDiagnostic(
3560 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003561 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003562 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003563 Ex->getLocStart(),
3564 /*IsStringLocation*/false,
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003565 getSpecifierRange(startSpecifier, specifierLen),
3566 FixItHint::CreateReplacement(
3567 getSpecifierRange(startSpecifier, specifierLen),
3568 os.str()));
3569 } else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003570 EmitFormatDiagnostic(
3571 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003572 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003573 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003574 Ex->getLocStart(),
3575 /*IsStringLocation*/false,
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003576 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003577 }
3578 }
3579
Ted Kremenek826a3452010-07-16 02:11:22 +00003580 return true;
3581}
3582
3583void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00003584 const Expr *OrigFormatExpr,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003585 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003586 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003587 unsigned firstDataArg, FormatStringType Type,
Richard Smith0e218972013-08-05 18:49:43 +00003588 bool inFunctionCall, VariadicCallType CallType,
3589 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003590
Ted Kremeneke0e53132010-01-28 23:39:18 +00003591 // CHECK: is the format string a wide literal?
Richard Smithdf9ef1b2012-06-13 05:37:23 +00003592 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003593 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003594 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003595 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3596 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003597 return;
3598 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003599
Ted Kremeneke0e53132010-01-28 23:39:18 +00003600 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00003601 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00003602 const char *Str = StrRef.data();
Stephen Hines651f13c2014-04-23 16:59:28 -07003603 // Account for cases where the string literal is truncated in a declaration.
3604 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
3605 assert(T && "String literal not of constant array type!");
3606 size_t TypeSize = T->getSize().getZExtValue();
3607 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003608 const unsigned numDataArgs = Args.size() - firstDataArg;
Stephen Hines651f13c2014-04-23 16:59:28 -07003609
3610 // Emit a warning if the string literal is truncated and does not contain an
3611 // embedded null character.
3612 if (TypeSize <= StrRef.size() &&
3613 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
3614 CheckFormatHandler::EmitFormatDiagnostic(
3615 *this, inFunctionCall, Args[format_idx],
3616 PDiag(diag::warn_printf_format_string_not_null_terminated),
3617 FExpr->getLocStart(),
3618 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
3619 return;
3620 }
3621
Ted Kremeneke0e53132010-01-28 23:39:18 +00003622 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00003623 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00003624 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003625 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003626 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3627 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003628 return;
3629 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003630
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003631 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003632 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003633 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003634 Str, HasVAListArg, Args, format_idx,
Richard Smith0e218972013-08-05 18:49:43 +00003635 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek826a3452010-07-16 02:11:22 +00003636
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003637 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003638 getLangOpts(),
3639 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003640 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003641 } else if (Type == FST_Scanf) {
Jordan Rose50687312012-06-04 23:52:23 +00003642 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003643 Str, HasVAListArg, Args, format_idx,
Richard Smith0e218972013-08-05 18:49:43 +00003644 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek826a3452010-07-16 02:11:22 +00003645
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003646 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003647 getLangOpts(),
3648 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003649 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003650 } // TODO: handle other formats
Ted Kremenekce7024e2010-01-28 01:18:22 +00003651}
3652
Stephen Hines651f13c2014-04-23 16:59:28 -07003653//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
3654
3655// Returns the related absolute value function that is larger, of 0 if one
3656// does not exist.
3657static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
3658 switch (AbsFunction) {
3659 default:
3660 return 0;
3661
3662 case Builtin::BI__builtin_abs:
3663 return Builtin::BI__builtin_labs;
3664 case Builtin::BI__builtin_labs:
3665 return Builtin::BI__builtin_llabs;
3666 case Builtin::BI__builtin_llabs:
3667 return 0;
3668
3669 case Builtin::BI__builtin_fabsf:
3670 return Builtin::BI__builtin_fabs;
3671 case Builtin::BI__builtin_fabs:
3672 return Builtin::BI__builtin_fabsl;
3673 case Builtin::BI__builtin_fabsl:
3674 return 0;
3675
3676 case Builtin::BI__builtin_cabsf:
3677 return Builtin::BI__builtin_cabs;
3678 case Builtin::BI__builtin_cabs:
3679 return Builtin::BI__builtin_cabsl;
3680 case Builtin::BI__builtin_cabsl:
3681 return 0;
3682
3683 case Builtin::BIabs:
3684 return Builtin::BIlabs;
3685 case Builtin::BIlabs:
3686 return Builtin::BIllabs;
3687 case Builtin::BIllabs:
3688 return 0;
3689
3690 case Builtin::BIfabsf:
3691 return Builtin::BIfabs;
3692 case Builtin::BIfabs:
3693 return Builtin::BIfabsl;
3694 case Builtin::BIfabsl:
3695 return 0;
3696
3697 case Builtin::BIcabsf:
3698 return Builtin::BIcabs;
3699 case Builtin::BIcabs:
3700 return Builtin::BIcabsl;
3701 case Builtin::BIcabsl:
3702 return 0;
3703 }
3704}
3705
3706// Returns the argument type of the absolute value function.
3707static QualType getAbsoluteValueArgumentType(ASTContext &Context,
3708 unsigned AbsType) {
3709 if (AbsType == 0)
3710 return QualType();
3711
3712 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3713 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
3714 if (Error != ASTContext::GE_None)
3715 return QualType();
3716
3717 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
3718 if (!FT)
3719 return QualType();
3720
3721 if (FT->getNumParams() != 1)
3722 return QualType();
3723
3724 return FT->getParamType(0);
3725}
3726
3727// Returns the best absolute value function, or zero, based on type and
3728// current absolute value function.
3729static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
3730 unsigned AbsFunctionKind) {
3731 unsigned BestKind = 0;
3732 uint64_t ArgSize = Context.getTypeSize(ArgType);
3733 for (unsigned Kind = AbsFunctionKind; Kind != 0;
3734 Kind = getLargerAbsoluteValueFunction(Kind)) {
3735 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
3736 if (Context.getTypeSize(ParamType) >= ArgSize) {
3737 if (BestKind == 0)
3738 BestKind = Kind;
3739 else if (Context.hasSameType(ParamType, ArgType)) {
3740 BestKind = Kind;
3741 break;
3742 }
3743 }
3744 }
3745 return BestKind;
3746}
3747
3748enum AbsoluteValueKind {
3749 AVK_Integer,
3750 AVK_Floating,
3751 AVK_Complex
3752};
3753
3754static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
3755 if (T->isIntegralOrEnumerationType())
3756 return AVK_Integer;
3757 if (T->isRealFloatingType())
3758 return AVK_Floating;
3759 if (T->isAnyComplexType())
3760 return AVK_Complex;
3761
3762 llvm_unreachable("Type not integer, floating, or complex");
3763}
3764
3765// Changes the absolute value function to a different type. Preserves whether
3766// the function is a builtin.
3767static unsigned changeAbsFunction(unsigned AbsKind,
3768 AbsoluteValueKind ValueKind) {
3769 switch (ValueKind) {
3770 case AVK_Integer:
3771 switch (AbsKind) {
3772 default:
3773 return 0;
3774 case Builtin::BI__builtin_fabsf:
3775 case Builtin::BI__builtin_fabs:
3776 case Builtin::BI__builtin_fabsl:
3777 case Builtin::BI__builtin_cabsf:
3778 case Builtin::BI__builtin_cabs:
3779 case Builtin::BI__builtin_cabsl:
3780 return Builtin::BI__builtin_abs;
3781 case Builtin::BIfabsf:
3782 case Builtin::BIfabs:
3783 case Builtin::BIfabsl:
3784 case Builtin::BIcabsf:
3785 case Builtin::BIcabs:
3786 case Builtin::BIcabsl:
3787 return Builtin::BIabs;
3788 }
3789 case AVK_Floating:
3790 switch (AbsKind) {
3791 default:
3792 return 0;
3793 case Builtin::BI__builtin_abs:
3794 case Builtin::BI__builtin_labs:
3795 case Builtin::BI__builtin_llabs:
3796 case Builtin::BI__builtin_cabsf:
3797 case Builtin::BI__builtin_cabs:
3798 case Builtin::BI__builtin_cabsl:
3799 return Builtin::BI__builtin_fabsf;
3800 case Builtin::BIabs:
3801 case Builtin::BIlabs:
3802 case Builtin::BIllabs:
3803 case Builtin::BIcabsf:
3804 case Builtin::BIcabs:
3805 case Builtin::BIcabsl:
3806 return Builtin::BIfabsf;
3807 }
3808 case AVK_Complex:
3809 switch (AbsKind) {
3810 default:
3811 return 0;
3812 case Builtin::BI__builtin_abs:
3813 case Builtin::BI__builtin_labs:
3814 case Builtin::BI__builtin_llabs:
3815 case Builtin::BI__builtin_fabsf:
3816 case Builtin::BI__builtin_fabs:
3817 case Builtin::BI__builtin_fabsl:
3818 return Builtin::BI__builtin_cabsf;
3819 case Builtin::BIabs:
3820 case Builtin::BIlabs:
3821 case Builtin::BIllabs:
3822 case Builtin::BIfabsf:
3823 case Builtin::BIfabs:
3824 case Builtin::BIfabsl:
3825 return Builtin::BIcabsf;
3826 }
3827 }
3828 llvm_unreachable("Unable to convert function");
3829}
3830
3831static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
3832 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
3833 if (!FnInfo)
3834 return 0;
3835
3836 switch (FDecl->getBuiltinID()) {
3837 default:
3838 return 0;
3839 case Builtin::BI__builtin_abs:
3840 case Builtin::BI__builtin_fabs:
3841 case Builtin::BI__builtin_fabsf:
3842 case Builtin::BI__builtin_fabsl:
3843 case Builtin::BI__builtin_labs:
3844 case Builtin::BI__builtin_llabs:
3845 case Builtin::BI__builtin_cabs:
3846 case Builtin::BI__builtin_cabsf:
3847 case Builtin::BI__builtin_cabsl:
3848 case Builtin::BIabs:
3849 case Builtin::BIlabs:
3850 case Builtin::BIllabs:
3851 case Builtin::BIfabs:
3852 case Builtin::BIfabsf:
3853 case Builtin::BIfabsl:
3854 case Builtin::BIcabs:
3855 case Builtin::BIcabsf:
3856 case Builtin::BIcabsl:
3857 return FDecl->getBuiltinID();
3858 }
3859 llvm_unreachable("Unknown Builtin type");
3860}
3861
3862// If the replacement is valid, emit a note with replacement function.
3863// Additionally, suggest including the proper header if not already included.
3864static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
3865 unsigned AbsKind) {
3866 std::string AbsName = S.Context.BuiltinInfo.GetName(AbsKind);
3867
3868 // Look up absolute value function in TU scope.
3869 DeclarationName DN(&S.Context.Idents.get(AbsName));
3870 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
3871 R.suppressDiagnostics();
3872 S.LookupName(R, S.TUScope);
3873
3874 // Skip notes if multiple results found in lookup.
3875 if (!R.empty() && !R.isSingleResult())
3876 return;
3877
3878 FunctionDecl *FD = 0;
3879 bool FoundFunction = R.isSingleResult();
3880 // When one result is found, see if it is the correct function.
3881 if (R.isSingleResult()) {
3882 FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3883 if (!FD || FD->getBuiltinID() != AbsKind)
3884 return;
3885 }
3886
3887 // Look for local name conflict, prepend "::" as necessary.
3888 R.clear();
3889 S.LookupName(R, S.getCurScope());
3890
3891 if (!FoundFunction) {
3892 if (!R.empty()) {
3893 AbsName = "::" + AbsName;
3894 }
3895 } else { // FoundFunction
3896 if (R.isSingleResult()) {
3897 if (R.getFoundDecl() != FD) {
3898 AbsName = "::" + AbsName;
3899 }
3900 } else if (!R.empty()) {
3901 AbsName = "::" + AbsName;
3902 }
3903 }
3904
3905 S.Diag(Loc, diag::note_replace_abs_function)
3906 << AbsName << FixItHint::CreateReplacement(Range, AbsName);
3907
3908 if (!FoundFunction) {
3909 S.Diag(Loc, diag::note_please_include_header)
3910 << S.Context.BuiltinInfo.getHeaderName(AbsKind)
3911 << S.Context.BuiltinInfo.GetName(AbsKind);
3912 }
3913}
3914
3915// Warn when using the wrong abs() function.
3916void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
3917 const FunctionDecl *FDecl,
3918 IdentifierInfo *FnInfo) {
3919 if (Call->getNumArgs() != 1)
3920 return;
3921
3922 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
3923 if (AbsKind == 0)
3924 return;
3925
3926 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
3927 QualType ParamType = Call->getArg(0)->getType();
3928
3929 // Unsigned types can not be negative. Suggest to drop the absolute value
3930 // function.
3931 if (ArgType->isUnsignedIntegerType()) {
3932 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
3933 Diag(Call->getExprLoc(), diag::note_remove_abs)
3934 << FDecl
3935 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
3936 return;
3937 }
3938
3939 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
3940 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
3941
3942 // The argument and parameter are the same kind. Check if they are the right
3943 // size.
3944 if (ArgValueKind == ParamValueKind) {
3945 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
3946 return;
3947
3948 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
3949 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
3950 << FDecl << ArgType << ParamType;
3951
3952 if (NewAbsKind == 0)
3953 return;
3954
3955 emitReplacement(*this, Call->getExprLoc(),
3956 Call->getCallee()->getSourceRange(), NewAbsKind);
3957 return;
3958 }
3959
3960 // ArgValueKind != ParamValueKind
3961 // The wrong type of absolute value function was used. Attempt to find the
3962 // proper one.
3963 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
3964 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
3965 if (NewAbsKind == 0)
3966 return;
3967
3968 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
3969 << FDecl << ParamValueKind << ArgValueKind;
3970
3971 emitReplacement(*this, Call->getExprLoc(),
3972 Call->getCallee()->getSourceRange(), NewAbsKind);
3973 return;
3974}
3975
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003976//===--- CHECK: Standard memory functions ---------------------------------===//
3977
Stephen Hines651f13c2014-04-23 16:59:28 -07003978/// \brief Takes the expression passed to the size_t parameter of functions
3979/// such as memcmp, strncat, etc and warns if it's a comparison.
3980///
3981/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
3982static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
3983 IdentifierInfo *FnName,
3984 SourceLocation FnLoc,
3985 SourceLocation RParenLoc) {
3986 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
3987 if (!Size)
3988 return false;
3989
3990 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
3991 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
3992 return false;
3993
3994 Preprocessor &PP = S.getPreprocessor();
3995 SourceRange SizeRange = Size->getSourceRange();
3996 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
3997 << SizeRange << FnName;
3998 S.Diag(FnLoc, diag::warn_memsize_comparison_paren_note)
3999 << FnName
4000 << FixItHint::CreateInsertion(
4001 PP.getLocForEndOfToken(Size->getLHS()->getLocEnd()),
4002 ")")
4003 << FixItHint::CreateRemoval(RParenLoc);
4004 S.Diag(SizeRange.getBegin(), diag::warn_memsize_comparison_cast_note)
4005 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
4006 << FixItHint::CreateInsertion(
4007 PP.getLocForEndOfToken(SizeRange.getEnd()), ")");
4008
4009 return true;
4010}
4011
Douglas Gregor2a053a32011-05-03 20:05:22 +00004012/// \brief Determine whether the given type is a dynamic class type (e.g.,
4013/// whether it has a vtable).
4014static bool isDynamicClassType(QualType T) {
4015 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4016 if (CXXRecordDecl *Definition = Record->getDefinition())
4017 if (Definition->isDynamicClass())
4018 return true;
4019
4020 return false;
4021}
4022
Chandler Carrutha72a12f2011-06-21 23:04:20 +00004023/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00004024/// otherwise returns NULL.
4025static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00004026 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00004027 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4028 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
4029 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00004030
Chandler Carruth000d4282011-06-16 09:09:40 +00004031 return 0;
4032}
4033
Chandler Carrutha72a12f2011-06-21 23:04:20 +00004034/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00004035static QualType getSizeOfArgType(const Expr* E) {
4036 if (const UnaryExprOrTypeTraitExpr *SizeOf =
4037 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4038 if (SizeOf->getKind() == clang::UETT_SizeOf)
4039 return SizeOf->getTypeOfArgument();
4040
4041 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00004042}
4043
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00004044/// \brief Check for dangerous or invalid arguments to memset().
4045///
Chandler Carruth929f0132011-06-03 06:23:57 +00004046/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00004047/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4048/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00004049///
4050/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00004051void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00004052 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00004053 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00004054 assert(BId != 0);
4055
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00004056 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00004057 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00004058 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00004059 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00004060 return;
4061
Anna Zaks0a151a12012-01-17 00:37:07 +00004062 unsigned LastArg = (BId == Builtin::BImemset ||
4063 BId == Builtin::BIstrndup ? 1 : 2);
4064 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00004065 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00004066
Stephen Hines651f13c2014-04-23 16:59:28 -07004067 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4068 Call->getLocStart(), Call->getRParenLoc()))
4069 return;
4070
Chandler Carruth000d4282011-06-16 09:09:40 +00004071 // We have special checking when the length is a sizeof expression.
4072 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4073 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4074 llvm::FoldingSetNodeID SizeOfArgID;
4075
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00004076 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4077 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00004078 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00004079
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00004080 QualType DestTy = Dest->getType();
4081 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
4082 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00004083
Chandler Carruth000d4282011-06-16 09:09:40 +00004084 // Never warn about void type pointers. This can be used to suppress
4085 // false positives.
4086 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00004087 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00004088
Chandler Carruth000d4282011-06-16 09:09:40 +00004089 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4090 // actually comparing the expressions for equality. Because computing the
4091 // expression IDs can be expensive, we only do this if the diagnostic is
4092 // enabled.
4093 if (SizeOfArg &&
4094 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
4095 SizeOfArg->getExprLoc())) {
4096 // We only compute IDs for expressions if the warning is enabled, and
4097 // cache the sizeof arg's ID.
4098 if (SizeOfArgID == llvm::FoldingSetNodeID())
4099 SizeOfArg->Profile(SizeOfArgID, Context, true);
4100 llvm::FoldingSetNodeID DestID;
4101 Dest->Profile(DestID, Context, true);
4102 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00004103 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4104 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00004105 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks6fcb3722012-05-30 00:34:21 +00004106 StringRef ReadableName = FnName->getName();
4107
Chandler Carruth000d4282011-06-16 09:09:40 +00004108 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaks90c78322012-05-30 23:14:52 +00004109 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth000d4282011-06-16 09:09:40 +00004110 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian7adf4172013-01-30 01:12:44 +00004111 if (!PointeeTy->isIncompleteType() &&
4112 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth000d4282011-06-16 09:09:40 +00004113 ActionIdx = 2; // If the pointee's size is sizeof(char),
4114 // suggest an explicit length.
Anna Zaks6fcb3722012-05-30 00:34:21 +00004115
4116 // If the function is defined as a builtin macro, do not show macro
4117 // expansion.
4118 SourceLocation SL = SizeOfArg->getExprLoc();
4119 SourceRange DSR = Dest->getSourceRange();
4120 SourceRange SSR = SizeOfArg->getSourceRange();
4121 SourceManager &SM = PP.getSourceManager();
4122
4123 if (SM.isMacroArgExpansion(SL)) {
4124 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4125 SL = SM.getSpellingLoc(SL);
4126 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4127 SM.getSpellingLoc(DSR.getEnd()));
4128 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4129 SM.getSpellingLoc(SSR.getEnd()));
4130 }
4131
Anna Zaks90c78322012-05-30 23:14:52 +00004132 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth000d4282011-06-16 09:09:40 +00004133 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks6fcb3722012-05-30 00:34:21 +00004134 << ReadableName
Anna Zaks90c78322012-05-30 23:14:52 +00004135 << PointeeTy
4136 << DestTy
Anna Zaks6fcb3722012-05-30 00:34:21 +00004137 << DSR
Anna Zaks90c78322012-05-30 23:14:52 +00004138 << SSR);
4139 DiagRuntimeBehavior(SL, SizeOfArg,
4140 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4141 << ActionIdx
4142 << SSR);
4143
Chandler Carruth000d4282011-06-16 09:09:40 +00004144 break;
4145 }
4146 }
4147
4148 // Also check for cases where the sizeof argument is the exact same
4149 // type as the memory argument, and where it points to a user-defined
4150 // record type.
4151 if (SizeOfArgTy != QualType()) {
4152 if (PointeeTy->isRecordType() &&
4153 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4154 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4155 PDiag(diag::warn_sizeof_pointer_type_memaccess)
4156 << FnName << SizeOfArgTy << ArgIdx
4157 << PointeeTy << Dest->getSourceRange()
4158 << LenExpr->getSourceRange());
4159 break;
4160 }
Nico Webere4a1c642011-06-14 16:14:58 +00004161 }
4162
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00004163 // Always complain about dynamic classes.
Anna Zaks0a151a12012-01-17 00:37:07 +00004164 if (isDynamicClassType(PointeeTy)) {
4165
4166 unsigned OperationType = 0;
4167 // "overwritten" if we're warning about the destination for any call
4168 // but memcmp; otherwise a verb appropriate to the call.
4169 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4170 if (BId == Builtin::BImemcpy)
4171 OperationType = 1;
4172 else if(BId == Builtin::BImemmove)
4173 OperationType = 2;
4174 else if (BId == Builtin::BImemcmp)
4175 OperationType = 3;
4176 }
4177
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00004178 DiagRuntimeBehavior(
4179 Dest->getExprLoc(), Dest,
4180 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks0a151a12012-01-17 00:37:07 +00004181 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaksd9b859a2012-01-13 21:52:01 +00004182 << FnName << PointeeTy
Anna Zaks0a151a12012-01-17 00:37:07 +00004183 << OperationType
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00004184 << Call->getCallee()->getSourceRange());
Anna Zaks0a151a12012-01-17 00:37:07 +00004185 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4186 BId != Builtin::BImemset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00004187 DiagRuntimeBehavior(
4188 Dest->getExprLoc(), Dest,
4189 PDiag(diag::warn_arc_object_memaccess)
4190 << ArgIdx << FnName << PointeeTy
4191 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00004192 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00004193 continue;
John McCallf85e1932011-06-15 23:02:42 +00004194
4195 DiagRuntimeBehavior(
4196 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00004197 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00004198 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4199 break;
4200 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00004201 }
4202}
4203
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00004204// A little helper routine: ignore addition and subtraction of integer literals.
4205// This intentionally does not ignore all integer constant expressions because
4206// we don't want to remove sizeof().
4207static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4208 Ex = Ex->IgnoreParenCasts();
4209
4210 for (;;) {
4211 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4212 if (!BO || !BO->isAdditiveOp())
4213 break;
4214
4215 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4216 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4217
4218 if (isa<IntegerLiteral>(RHS))
4219 Ex = LHS;
4220 else if (isa<IntegerLiteral>(LHS))
4221 Ex = RHS;
4222 else
4223 break;
4224 }
4225
4226 return Ex;
4227}
4228
Anna Zaks0f38ace2012-08-08 21:42:23 +00004229static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4230 ASTContext &Context) {
4231 // Only handle constant-sized or VLAs, but not flexible members.
4232 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4233 // Only issue the FIXIT for arrays of size > 1.
4234 if (CAT->getSize().getSExtValue() <= 1)
4235 return false;
4236 } else if (!Ty->isVariableArrayType()) {
4237 return false;
4238 }
4239 return true;
4240}
4241
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00004242// Warn if the user has made the 'size' argument to strlcpy or strlcat
4243// be the size of the source, instead of the destination.
4244void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4245 IdentifierInfo *FnName) {
4246
4247 // Don't crash if the user has the wrong number of arguments
4248 if (Call->getNumArgs() != 3)
4249 return;
4250
4251 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4252 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
4253 const Expr *CompareWithSrc = NULL;
Stephen Hines651f13c2014-04-23 16:59:28 -07004254
4255 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4256 Call->getLocStart(), Call->getRParenLoc()))
4257 return;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00004258
4259 // Look for 'strlcpy(dst, x, sizeof(x))'
4260 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4261 CompareWithSrc = Ex;
4262 else {
4263 // Look for 'strlcpy(dst, x, strlen(x))'
4264 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004265 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4266 SizeCall->getNumArgs() == 1)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00004267 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4268 }
4269 }
4270
4271 if (!CompareWithSrc)
4272 return;
4273
4274 // Determine if the argument to sizeof/strlen is equal to the source
4275 // argument. In principle there's all kinds of things you could do
4276 // here, for instance creating an == expression and evaluating it with
4277 // EvaluateAsBooleanCondition, but this uses a more direct technique:
4278 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4279 if (!SrcArgDRE)
4280 return;
4281
4282 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4283 if (!CompareWithSrcDRE ||
4284 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4285 return;
4286
4287 const Expr *OriginalSizeArg = Call->getArg(2);
4288 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4289 << OriginalSizeArg->getSourceRange() << FnName;
4290
4291 // Output a FIXIT hint if the destination is an array (rather than a
4292 // pointer to an array). This could be enhanced to handle some
4293 // pointers if we know the actual size, like if DstArg is 'array+2'
4294 // we could say 'sizeof(array)-2'.
4295 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks0f38ace2012-08-08 21:42:23 +00004296 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek8f746222011-08-18 22:48:41 +00004297 return;
Ted Kremenek8f746222011-08-18 22:48:41 +00004298
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00004299 SmallString<128> sizeString;
Ted Kremenek8f746222011-08-18 22:48:41 +00004300 llvm::raw_svector_ostream OS(sizeString);
4301 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00004302 DstArg->printPretty(OS, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00004303 OS << ")";
4304
4305 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4306 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4307 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00004308}
4309
Anna Zaksc36bedc2012-02-01 19:08:57 +00004310/// Check if two expressions refer to the same declaration.
4311static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4312 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4313 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4314 return D1->getDecl() == D2->getDecl();
4315 return false;
4316}
4317
4318static const Expr *getStrlenExprArg(const Expr *E) {
4319 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
4320 const FunctionDecl *FD = CE->getDirectCallee();
4321 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
4322 return 0;
4323 return CE->getArg(0)->IgnoreParenCasts();
4324 }
4325 return 0;
4326}
4327
4328// Warn on anti-patterns as the 'size' argument to strncat.
4329// The correct size argument should look like following:
4330// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
4331void Sema::CheckStrncatArguments(const CallExpr *CE,
4332 IdentifierInfo *FnName) {
4333 // Don't crash if the user has the wrong number of arguments.
4334 if (CE->getNumArgs() < 3)
4335 return;
4336 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
4337 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
4338 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
4339
Stephen Hines651f13c2014-04-23 16:59:28 -07004340 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
4341 CE->getRParenLoc()))
4342 return;
4343
Anna Zaksc36bedc2012-02-01 19:08:57 +00004344 // Identify common expressions, which are wrongly used as the size argument
4345 // to strncat and may lead to buffer overflows.
4346 unsigned PatternType = 0;
4347 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
4348 // - sizeof(dst)
4349 if (referToTheSameDecl(SizeOfArg, DstArg))
4350 PatternType = 1;
4351 // - sizeof(src)
4352 else if (referToTheSameDecl(SizeOfArg, SrcArg))
4353 PatternType = 2;
4354 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
4355 if (BE->getOpcode() == BO_Sub) {
4356 const Expr *L = BE->getLHS()->IgnoreParenCasts();
4357 const Expr *R = BE->getRHS()->IgnoreParenCasts();
4358 // - sizeof(dst) - strlen(dst)
4359 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
4360 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
4361 PatternType = 1;
4362 // - sizeof(src) - (anything)
4363 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
4364 PatternType = 2;
4365 }
4366 }
4367
4368 if (PatternType == 0)
4369 return;
4370
Anna Zaksafdb0412012-02-03 01:27:37 +00004371 // Generate the diagnostic.
4372 SourceLocation SL = LenArg->getLocStart();
4373 SourceRange SR = LenArg->getSourceRange();
4374 SourceManager &SM = PP.getSourceManager();
4375
4376 // If the function is defined as a builtin macro, do not show macro expansion.
4377 if (SM.isMacroArgExpansion(SL)) {
4378 SL = SM.getSpellingLoc(SL);
4379 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
4380 SM.getSpellingLoc(SR.getEnd()));
4381 }
4382
Anna Zaks0f38ace2012-08-08 21:42:23 +00004383 // Check if the destination is an array (rather than a pointer to an array).
4384 QualType DstTy = DstArg->getType();
4385 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
4386 Context);
4387 if (!isKnownSizeArray) {
4388 if (PatternType == 1)
4389 Diag(SL, diag::warn_strncat_wrong_size) << SR;
4390 else
4391 Diag(SL, diag::warn_strncat_src_size) << SR;
4392 return;
4393 }
4394
Anna Zaksc36bedc2012-02-01 19:08:57 +00004395 if (PatternType == 1)
Anna Zaksafdb0412012-02-03 01:27:37 +00004396 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00004397 else
Anna Zaksafdb0412012-02-03 01:27:37 +00004398 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00004399
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00004400 SmallString<128> sizeString;
Anna Zaksc36bedc2012-02-01 19:08:57 +00004401 llvm::raw_svector_ostream OS(sizeString);
4402 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00004403 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00004404 OS << ") - ";
4405 OS << "strlen(";
Richard Smithd1420c62012-08-16 03:56:14 +00004406 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00004407 OS << ") - 1";
4408
Anna Zaksafdb0412012-02-03 01:27:37 +00004409 Diag(SL, diag::note_strncat_wrong_size)
4410 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaksc36bedc2012-02-01 19:08:57 +00004411}
4412
Ted Kremenek06de2762007-08-17 16:46:58 +00004413//===--- CHECK: Return Address of Stack Variable --------------------------===//
4414
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004415static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4416 Decl *ParentDecl);
4417static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
4418 Decl *ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004419
4420/// CheckReturnStackAddr - Check if a return statement returns the address
4421/// of a stack variable.
Stephen Hines651f13c2014-04-23 16:59:28 -07004422static void
4423CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
4424 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00004425
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004426 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004427 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004428
4429 // Perform checking for returned stack addresses, local blocks,
4430 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00004431 if (lhsType->isPointerType() ||
Stephen Hines651f13c2014-04-23 16:59:28 -07004432 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004433 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00004434 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004435 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004436 }
4437
4438 if (stackE == 0)
4439 return; // Nothing suspicious was found.
4440
4441 SourceLocation diagLoc;
4442 SourceRange diagRange;
4443 if (refVars.empty()) {
4444 diagLoc = stackE->getLocStart();
4445 diagRange = stackE->getSourceRange();
4446 } else {
4447 // We followed through a reference variable. 'stackE' contains the
4448 // problematic expression but we will warn at the return statement pointing
4449 // at the reference variable. We will later display the "trail" of
4450 // reference variables using notes.
4451 diagLoc = refVars[0]->getLocStart();
4452 diagRange = refVars[0]->getSourceRange();
4453 }
4454
4455 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Stephen Hines651f13c2014-04-23 16:59:28 -07004456 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004457 : diag::warn_ret_stack_addr)
4458 << DR->getDecl()->getDeclName() << diagRange;
4459 } else if (isa<BlockExpr>(stackE)) { // local block.
Stephen Hines651f13c2014-04-23 16:59:28 -07004460 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004461 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Stephen Hines651f13c2014-04-23 16:59:28 -07004462 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004463 } else { // local temporary.
Stephen Hines651f13c2014-04-23 16:59:28 -07004464 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
4465 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004466 << diagRange;
4467 }
4468
4469 // Display the "trail" of reference variables that we followed until we
4470 // found the problematic expression using notes.
4471 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4472 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4473 // If this var binds to another reference var, show the range of the next
4474 // var, otherwise the var binds to the problematic expression, in which case
4475 // show the range of the expression.
4476 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4477 : stackE->getSourceRange();
Stephen Hines651f13c2014-04-23 16:59:28 -07004478 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4479 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00004480 }
4481}
4482
4483/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4484/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004485/// to a location on the stack, a local block, an address of a label, or a
4486/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00004487/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004488/// encounter a subexpression that (1) clearly does not lead to one of the
4489/// above problematic expressions (2) is something we cannot determine leads to
4490/// a problematic expression based on such local checking.
4491///
4492/// Both EvalAddr and EvalVal follow through reference variables to evaluate
4493/// the expression that they point to. Such variables are added to the
4494/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00004495///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00004496/// EvalAddr processes expressions that are pointers that are used as
4497/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004498/// At the base case of the recursion is a check for the above problematic
4499/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00004500///
4501/// This implementation handles:
4502///
4503/// * pointer-to-pointer casts
4504/// * implicit conversions from array references to pointers
4505/// * taking the address of fields
4506/// * arbitrary interplay between "&" and "*" operators
4507/// * pointer arithmetic from an address of a stack variable
4508/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004509static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4510 Decl *ParentDecl) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004511 if (E->isTypeDependent())
Craig Topperb61c2942013-08-02 05:10:31 +00004512 return NULL;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004513
Ted Kremenek06de2762007-08-17 16:46:58 +00004514 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00004515 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00004516 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004517 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004518 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00004519
Peter Collingbournef111d932011-04-15 00:35:48 +00004520 E = E->IgnoreParens();
4521
Ted Kremenek06de2762007-08-17 16:46:58 +00004522 // Our "symbolic interpreter" is just a dispatch off the currently
4523 // viewed AST node. We then recursively traverse the AST by calling
4524 // EvalAddr and EvalVal appropriately.
4525 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004526 case Stmt::DeclRefExprClass: {
4527 DeclRefExpr *DR = cast<DeclRefExpr>(E);
4528
Stephen Hines651f13c2014-04-23 16:59:28 -07004529 // If we leave the immediate function, the lifetime isn't about to end.
4530 if (DR->refersToEnclosingLocal())
4531 return 0;
4532
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004533 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
4534 // If this is a reference variable, follow through to the expression that
4535 // it points to.
4536 if (V->hasLocalStorage() &&
4537 V->getType()->isReferenceType() && V->hasInit()) {
4538 // Add the reference variable to the "trail".
4539 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004540 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004541 }
4542
4543 return NULL;
4544 }
Ted Kremenek06de2762007-08-17 16:46:58 +00004545
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004546 case Stmt::UnaryOperatorClass: {
4547 // The only unary operator that make sense to handle here
4548 // is AddrOf. All others don't make sense as pointers.
4549 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004550
John McCall2de56d12010-08-25 11:45:40 +00004551 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004552 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004553 else
Ted Kremenek06de2762007-08-17 16:46:58 +00004554 return NULL;
4555 }
Mike Stump1eb44332009-09-09 15:08:12 +00004556
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004557 case Stmt::BinaryOperatorClass: {
4558 // Handle pointer arithmetic. All other binary operators are not valid
4559 // in this context.
4560 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00004561 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00004562
John McCall2de56d12010-08-25 11:45:40 +00004563 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004564 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00004565
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004566 Expr *Base = B->getLHS();
4567
4568 // Determine which argument is the real pointer base. It could be
4569 // the RHS argument instead of the LHS.
4570 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00004571
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004572 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004573 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004574 }
Steve Naroff61f40a22008-09-10 19:17:48 +00004575
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004576 // For conditional operators we need to see if either the LHS or RHS are
4577 // valid DeclRefExpr*s. If one of them is valid, we return it.
4578 case Stmt::ConditionalOperatorClass: {
4579 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004580
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004581 // Handle the GNU extension for missing LHS.
Stephen Hines651f13c2014-04-23 16:59:28 -07004582 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
4583 if (Expr *LHSExpr = C->getLHS()) {
4584 // In C++, we can have a throw-expression, which has 'void' type.
4585 if (!LHSExpr->getType()->isVoidType())
4586 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00004587 return LHS;
4588 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004589
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00004590 // In C++, we can have a throw-expression, which has 'void' type.
4591 if (C->getRHS()->getType()->isVoidType())
Stephen Hines651f13c2014-04-23 16:59:28 -07004592 return 0;
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00004593
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004594 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004595 }
Stephen Hines651f13c2014-04-23 16:59:28 -07004596
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004597 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00004598 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004599 return E; // local block.
4600 return NULL;
4601
4602 case Stmt::AddrLabelExprClass:
4603 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00004604
John McCall80ee6e82011-11-10 05:35:25 +00004605 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004606 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4607 ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00004608
Ted Kremenek54b52742008-08-07 00:49:01 +00004609 // For casts, we need to handle conversions from arrays to
4610 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00004611 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00004612 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00004613 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8b9414e2012-02-23 23:04:32 +00004614 case Stmt::ObjCBridgedCastExprClass:
Mike Stump1eb44332009-09-09 15:08:12 +00004615 case Stmt::CXXStaticCastExprClass:
4616 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00004617 case Stmt::CXXConstCastExprClass:
4618 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8b9414e2012-02-23 23:04:32 +00004619 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4620 switch (cast<CastExpr>(E)->getCastKind()) {
4621 case CK_BitCast:
4622 case CK_LValueToRValue:
4623 case CK_NoOp:
4624 case CK_BaseToDerived:
4625 case CK_DerivedToBase:
4626 case CK_UncheckedDerivedToBase:
4627 case CK_Dynamic:
4628 case CK_CPointerToObjCPointerCast:
4629 case CK_BlockPointerToObjCPointerCast:
4630 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004631 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00004632
4633 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004634 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00004635
4636 default:
4637 return 0;
4638 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004639 }
Mike Stump1eb44332009-09-09 15:08:12 +00004640
Douglas Gregor03e80032011-06-21 17:03:29 +00004641 case Stmt::MaterializeTemporaryExprClass:
4642 if (Expr *Result = EvalAddr(
4643 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004644 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00004645 return Result;
4646
4647 return E;
4648
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004649 // Everything else: we simply don't reason about them.
4650 default:
4651 return NULL;
4652 }
Ted Kremenek06de2762007-08-17 16:46:58 +00004653}
Mike Stump1eb44332009-09-09 15:08:12 +00004654
Ted Kremenek06de2762007-08-17 16:46:58 +00004655
4656/// EvalVal - This function is complements EvalAddr in the mutual recursion.
4657/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004658static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4659 Decl *ParentDecl) {
Ted Kremenek68957a92010-08-04 20:01:07 +00004660do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00004661 // We should only be called for evaluating non-pointer expressions, or
4662 // expressions with a pointer type that are not used as references but instead
4663 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00004664
Ted Kremenek06de2762007-08-17 16:46:58 +00004665 // Our "symbolic interpreter" is just a dispatch off the currently
4666 // viewed AST node. We then recursively traverse the AST by calling
4667 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00004668
4669 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00004670 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00004671 case Stmt::ImplicitCastExprClass: {
4672 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00004673 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00004674 E = IE->getSubExpr();
4675 continue;
4676 }
4677 return NULL;
4678 }
4679
John McCall80ee6e82011-11-10 05:35:25 +00004680 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004681 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00004682
Douglas Gregora2813ce2009-10-23 18:54:35 +00004683 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004684 // When we hit a DeclRefExpr we are looking at code that refers to a
4685 // variable's name. If it's not a reference variable we check if it has
4686 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00004687 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004688
Stephen Hines651f13c2014-04-23 16:59:28 -07004689 // If we leave the immediate function, the lifetime isn't about to end.
4690 if (DR->refersToEnclosingLocal())
4691 return 0;
4692
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004693 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
4694 // Check if it refers to itself, e.g. "int& i = i;".
4695 if (V == ParentDecl)
4696 return DR;
4697
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004698 if (V->hasLocalStorage()) {
4699 if (!V->getType()->isReferenceType())
4700 return DR;
4701
4702 // Reference variable, follow through to the expression that
4703 // it points to.
4704 if (V->hasInit()) {
4705 // Add the reference variable to the "trail".
4706 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004707 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004708 }
4709 }
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004710 }
Mike Stump1eb44332009-09-09 15:08:12 +00004711
Ted Kremenek06de2762007-08-17 16:46:58 +00004712 return NULL;
4713 }
Mike Stump1eb44332009-09-09 15:08:12 +00004714
Ted Kremenek06de2762007-08-17 16:46:58 +00004715 case Stmt::UnaryOperatorClass: {
4716 // The only unary operator that make sense to handle here
4717 // is Deref. All others don't resolve to a "name." This includes
4718 // handling all sorts of rvalues passed to a unary operator.
4719 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004720
John McCall2de56d12010-08-25 11:45:40 +00004721 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004722 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004723
4724 return NULL;
4725 }
Mike Stump1eb44332009-09-09 15:08:12 +00004726
Ted Kremenek06de2762007-08-17 16:46:58 +00004727 case Stmt::ArraySubscriptExprClass: {
4728 // Array subscripts are potential references to data on the stack. We
4729 // retrieve the DeclRefExpr* for the array variable if it indeed
4730 // has local storage.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004731 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004732 }
Mike Stump1eb44332009-09-09 15:08:12 +00004733
Ted Kremenek06de2762007-08-17 16:46:58 +00004734 case Stmt::ConditionalOperatorClass: {
4735 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004736 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00004737 ConditionalOperator *C = cast<ConditionalOperator>(E);
4738
Anders Carlsson39073232007-11-30 19:04:31 +00004739 // Handle the GNU extension for missing LHS.
Stephen Hines651f13c2014-04-23 16:59:28 -07004740 if (Expr *LHSExpr = C->getLHS()) {
4741 // In C++, we can have a throw-expression, which has 'void' type.
4742 if (!LHSExpr->getType()->isVoidType())
4743 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
4744 return LHS;
4745 }
4746
4747 // In C++, we can have a throw-expression, which has 'void' type.
4748 if (C->getRHS()->getType()->isVoidType())
4749 return 0;
Anders Carlsson39073232007-11-30 19:04:31 +00004750
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004751 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004752 }
Mike Stump1eb44332009-09-09 15:08:12 +00004753
Ted Kremenek06de2762007-08-17 16:46:58 +00004754 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00004755 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00004756 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004757
Ted Kremenek06de2762007-08-17 16:46:58 +00004758 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00004759 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00004760 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00004761
4762 // Check whether the member type is itself a reference, in which case
4763 // we're not going to refer to the member, but to what the member refers to.
4764 if (M->getMemberDecl()->getType()->isReferenceType())
4765 return NULL;
4766
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004767 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004768 }
Mike Stump1eb44332009-09-09 15:08:12 +00004769
Douglas Gregor03e80032011-06-21 17:03:29 +00004770 case Stmt::MaterializeTemporaryExprClass:
4771 if (Expr *Result = EvalVal(
4772 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004773 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00004774 return Result;
4775
4776 return E;
4777
Ted Kremenek06de2762007-08-17 16:46:58 +00004778 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004779 // Check that we don't return or take the address of a reference to a
4780 // temporary. This is only useful in C++.
4781 if (!E->isTypeDependent() && E->isRValue())
4782 return E;
4783
4784 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00004785 return NULL;
4786 }
Ted Kremenek68957a92010-08-04 20:01:07 +00004787} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00004788}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004789
Stephen Hines651f13c2014-04-23 16:59:28 -07004790void
4791Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
4792 SourceLocation ReturnLoc,
4793 bool isObjCMethod,
4794 const AttrVec *Attrs,
4795 const FunctionDecl *FD) {
4796 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
4797
4798 // Check if the return value is null but should not be.
4799 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
4800 CheckNonNullExpr(*this, RetValExp))
4801 Diag(ReturnLoc, diag::warn_null_ret)
4802 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
4803
4804 // C++11 [basic.stc.dynamic.allocation]p4:
4805 // If an allocation function declared with a non-throwing
4806 // exception-specification fails to allocate storage, it shall return
4807 // a null pointer. Any other allocation function that fails to allocate
4808 // storage shall indicate failure only by throwing an exception [...]
4809 if (FD) {
4810 OverloadedOperatorKind Op = FD->getOverloadedOperator();
4811 if (Op == OO_New || Op == OO_Array_New) {
4812 const FunctionProtoType *Proto
4813 = FD->getType()->castAs<FunctionProtoType>();
4814 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
4815 CheckNonNullExpr(*this, RetValExp))
4816 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
4817 << FD << getLangOpts().CPlusPlus11;
4818 }
4819 }
4820}
4821
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004822//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
4823
4824/// Check for comparisons of floating point operands using != and ==.
4825/// Issue a warning if these are no self-comparisons, as they are not likely
4826/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00004827void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieudd225092011-09-15 21:56:47 +00004828 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
4829 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004830
4831 // Special case: check for x == x (which is OK).
4832 // Do not emit warnings for such cases.
4833 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
4834 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
4835 if (DRL->getDecl() == DRR->getDecl())
David Blaikie980343b2012-07-16 20:47:22 +00004836 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004837
4838
Ted Kremenek1b500bb2007-11-29 00:59:04 +00004839 // Special case: check for comparisons against literals that can be exactly
4840 // represented by APFloat. In such cases, do not emit a warning. This
4841 // is a heuristic: often comparison against such literals are used to
4842 // detect if a value in a variable has not changed. This clearly can
4843 // lead to false negatives.
David Blaikie980343b2012-07-16 20:47:22 +00004844 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
4845 if (FLL->isExact())
4846 return;
4847 } else
4848 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
4849 if (FLR->isExact())
4850 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004851
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004852 // Check for comparisons with builtin types.
David Blaikie980343b2012-07-16 20:47:22 +00004853 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Stephen Hines651f13c2014-04-23 16:59:28 -07004854 if (CL->getBuiltinCallee())
David Blaikie980343b2012-07-16 20:47:22 +00004855 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004856
David Blaikie980343b2012-07-16 20:47:22 +00004857 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Stephen Hines651f13c2014-04-23 16:59:28 -07004858 if (CR->getBuiltinCallee())
David Blaikie980343b2012-07-16 20:47:22 +00004859 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004860
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004861 // Emit the diagnostic.
David Blaikie980343b2012-07-16 20:47:22 +00004862 Diag(Loc, diag::warn_floatingpoint_eq)
4863 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004864}
John McCallba26e582010-01-04 23:21:16 +00004865
John McCallf2370c92010-01-06 05:24:50 +00004866//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
4867//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00004868
John McCallf2370c92010-01-06 05:24:50 +00004869namespace {
John McCallba26e582010-01-04 23:21:16 +00004870
John McCallf2370c92010-01-06 05:24:50 +00004871/// Structure recording the 'active' range of an integer-valued
4872/// expression.
4873struct IntRange {
4874 /// The number of bits active in the int.
4875 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00004876
John McCallf2370c92010-01-06 05:24:50 +00004877 /// True if the int is known not to have negative values.
4878 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00004879
John McCallf2370c92010-01-06 05:24:50 +00004880 IntRange(unsigned Width, bool NonNegative)
4881 : Width(Width), NonNegative(NonNegative)
4882 {}
John McCallba26e582010-01-04 23:21:16 +00004883
John McCall1844a6e2010-11-10 23:38:19 +00004884 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00004885 static IntRange forBoolType() {
4886 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00004887 }
4888
John McCall1844a6e2010-11-10 23:38:19 +00004889 /// Returns the range of an opaque value of the given integral type.
4890 static IntRange forValueOfType(ASTContext &C, QualType T) {
4891 return forValueOfCanonicalType(C,
4892 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00004893 }
4894
John McCall1844a6e2010-11-10 23:38:19 +00004895 /// Returns the range of an opaque value of a canonical integral type.
4896 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00004897 assert(T->isCanonicalUnqualified());
4898
4899 if (const VectorType *VT = dyn_cast<VectorType>(T))
4900 T = VT->getElementType().getTypePtr();
4901 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4902 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00004903
David Majnemerf9eaf982013-06-07 22:07:20 +00004904 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00004905 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemerf9eaf982013-06-07 22:07:20 +00004906 EnumDecl *Enum = ET->getDecl();
4907 if (!Enum->isCompleteDefinition())
4908 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall091f23f2010-11-09 22:22:12 +00004909
David Majnemerf9eaf982013-06-07 22:07:20 +00004910 unsigned NumPositive = Enum->getNumPositiveBits();
4911 unsigned NumNegative = Enum->getNumNegativeBits();
John McCall323ed742010-05-06 08:58:33 +00004912
David Majnemerf9eaf982013-06-07 22:07:20 +00004913 if (NumNegative == 0)
4914 return IntRange(NumPositive, true/*NonNegative*/);
4915 else
4916 return IntRange(std::max(NumPositive + 1, NumNegative),
4917 false/*NonNegative*/);
John McCall323ed742010-05-06 08:58:33 +00004918 }
John McCallf2370c92010-01-06 05:24:50 +00004919
4920 const BuiltinType *BT = cast<BuiltinType>(T);
4921 assert(BT->isInteger());
4922
4923 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4924 }
4925
John McCall1844a6e2010-11-10 23:38:19 +00004926 /// Returns the "target" range of a canonical integral type, i.e.
4927 /// the range of values expressible in the type.
4928 ///
4929 /// This matches forValueOfCanonicalType except that enums have the
4930 /// full range of their type, not the range of their enumerators.
4931 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4932 assert(T->isCanonicalUnqualified());
4933
4934 if (const VectorType *VT = dyn_cast<VectorType>(T))
4935 T = VT->getElementType().getTypePtr();
4936 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4937 T = CT->getElementType().getTypePtr();
4938 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00004939 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00004940
4941 const BuiltinType *BT = cast<BuiltinType>(T);
4942 assert(BT->isInteger());
4943
4944 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4945 }
4946
4947 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00004948 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00004949 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00004950 L.NonNegative && R.NonNegative);
4951 }
4952
John McCall1844a6e2010-11-10 23:38:19 +00004953 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00004954 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00004955 return IntRange(std::min(L.Width, R.Width),
4956 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00004957 }
4958};
4959
Ted Kremenek0692a192012-01-31 05:37:37 +00004960static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4961 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004962 if (value.isSigned() && value.isNegative())
4963 return IntRange(value.getMinSignedBits(), false);
4964
4965 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00004966 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004967
4968 // isNonNegative() just checks the sign bit without considering
4969 // signedness.
4970 return IntRange(value.getActiveBits(), true);
4971}
4972
Ted Kremenek0692a192012-01-31 05:37:37 +00004973static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4974 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004975 if (result.isInt())
4976 return GetValueRange(C, result.getInt(), MaxWidth);
4977
4978 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00004979 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4980 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4981 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4982 R = IntRange::join(R, El);
4983 }
John McCallf2370c92010-01-06 05:24:50 +00004984 return R;
4985 }
4986
4987 if (result.isComplexInt()) {
4988 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4989 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4990 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00004991 }
4992
4993 // This can happen with lossless casts to intptr_t of "based" lvalues.
4994 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00004995 // FIXME: The only reason we need to pass the type in here is to get
4996 // the sign right on this one case. It would be nice if APValue
4997 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00004998 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004999 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00005000}
John McCallf2370c92010-01-06 05:24:50 +00005001
Eli Friedman09bddcf2013-07-08 20:20:06 +00005002static QualType GetExprType(Expr *E) {
5003 QualType Ty = E->getType();
5004 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
5005 Ty = AtomicRHS->getValueType();
5006 return Ty;
5007}
5008
John McCallf2370c92010-01-06 05:24:50 +00005009/// Pseudo-evaluate the given integer expression, estimating the
5010/// range of values it might take.
5011///
5012/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek0692a192012-01-31 05:37:37 +00005013static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00005014 E = E->IgnoreParens();
5015
5016 // Try a full evaluation first.
5017 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00005018 if (E->EvaluateAsRValue(result, C))
Eli Friedman09bddcf2013-07-08 20:20:06 +00005019 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00005020
5021 // I think we only want to look through implicit casts here; if the
5022 // user has an explicit widening cast, we should treat the value as
5023 // being of the new, wider type.
5024 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00005025 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00005026 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
5027
Eli Friedman09bddcf2013-07-08 20:20:06 +00005028 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCallf2370c92010-01-06 05:24:50 +00005029
John McCall2de56d12010-08-25 11:45:40 +00005030 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00005031
John McCallf2370c92010-01-06 05:24:50 +00005032 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00005033 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00005034 return OutputTypeRange;
5035
5036 IntRange SubRange
5037 = GetExprRange(C, CE->getSubExpr(),
5038 std::min(MaxWidth, OutputTypeRange.Width));
5039
5040 // Bail out if the subexpr's range is as wide as the cast type.
5041 if (SubRange.Width >= OutputTypeRange.Width)
5042 return OutputTypeRange;
5043
5044 // Otherwise, we take the smaller width, and we're non-negative if
5045 // either the output type or the subexpr is.
5046 return IntRange(SubRange.Width,
5047 SubRange.NonNegative || OutputTypeRange.NonNegative);
5048 }
5049
5050 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5051 // If we can fold the condition, just take that operand.
5052 bool CondResult;
5053 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5054 return GetExprRange(C, CondResult ? CO->getTrueExpr()
5055 : CO->getFalseExpr(),
5056 MaxWidth);
5057
5058 // Otherwise, conservatively merge.
5059 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5060 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5061 return IntRange::join(L, R);
5062 }
5063
5064 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5065 switch (BO->getOpcode()) {
5066
5067 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00005068 case BO_LAnd:
5069 case BO_LOr:
5070 case BO_LT:
5071 case BO_GT:
5072 case BO_LE:
5073 case BO_GE:
5074 case BO_EQ:
5075 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00005076 return IntRange::forBoolType();
5077
John McCall862ff872011-07-13 06:35:24 +00005078 // The type of the assignments is the type of the LHS, so the RHS
5079 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00005080 case BO_MulAssign:
5081 case BO_DivAssign:
5082 case BO_RemAssign:
5083 case BO_AddAssign:
5084 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00005085 case BO_XorAssign:
5086 case BO_OrAssign:
5087 // TODO: bitfields?
Eli Friedman09bddcf2013-07-08 20:20:06 +00005088 return IntRange::forValueOfType(C, GetExprType(E));
John McCallc0cd21d2010-02-23 19:22:29 +00005089
John McCall862ff872011-07-13 06:35:24 +00005090 // Simple assignments just pass through the RHS, which will have
5091 // been coerced to the LHS type.
5092 case BO_Assign:
5093 // TODO: bitfields?
5094 return GetExprRange(C, BO->getRHS(), MaxWidth);
5095
John McCallf2370c92010-01-06 05:24:50 +00005096 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00005097 case BO_PtrMemD:
5098 case BO_PtrMemI:
Eli Friedman09bddcf2013-07-08 20:20:06 +00005099 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00005100
John McCall60fad452010-01-06 22:07:33 +00005101 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00005102 case BO_And:
5103 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00005104 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5105 GetExprRange(C, BO->getRHS(), MaxWidth));
5106
John McCallf2370c92010-01-06 05:24:50 +00005107 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00005108 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00005109 // ...except that we want to treat '1 << (blah)' as logically
5110 // positive. It's an important idiom.
5111 if (IntegerLiteral *I
5112 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5113 if (I->getValue() == 1) {
Eli Friedman09bddcf2013-07-08 20:20:06 +00005114 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall3aae6092010-04-07 01:14:35 +00005115 return IntRange(R.Width, /*NonNegative*/ true);
5116 }
5117 }
5118 // fallthrough
5119
John McCall2de56d12010-08-25 11:45:40 +00005120 case BO_ShlAssign:
Eli Friedman09bddcf2013-07-08 20:20:06 +00005121 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00005122
John McCall60fad452010-01-06 22:07:33 +00005123 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00005124 case BO_Shr:
5125 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00005126 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5127
5128 // If the shift amount is a positive constant, drop the width by
5129 // that much.
5130 llvm::APSInt shift;
5131 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5132 shift.isNonNegative()) {
5133 unsigned zext = shift.getZExtValue();
5134 if (zext >= L.Width)
5135 L.Width = (L.NonNegative ? 0 : 1);
5136 else
5137 L.Width -= zext;
5138 }
5139
5140 return L;
5141 }
5142
5143 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00005144 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00005145 return GetExprRange(C, BO->getRHS(), MaxWidth);
5146
John McCall60fad452010-01-06 22:07:33 +00005147 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00005148 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00005149 if (BO->getLHS()->getType()->isPointerType())
Eli Friedman09bddcf2013-07-08 20:20:06 +00005150 return IntRange::forValueOfType(C, GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00005151 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00005152
John McCall00fe7612011-07-14 22:39:48 +00005153 // The width of a division result is mostly determined by the size
5154 // of the LHS.
5155 case BO_Div: {
5156 // Don't 'pre-truncate' the operands.
Eli Friedman09bddcf2013-07-08 20:20:06 +00005157 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00005158 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5159
5160 // If the divisor is constant, use that.
5161 llvm::APSInt divisor;
5162 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5163 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5164 if (log2 >= L.Width)
5165 L.Width = (L.NonNegative ? 0 : 1);
5166 else
5167 L.Width = std::min(L.Width - log2, MaxWidth);
5168 return L;
5169 }
5170
5171 // Otherwise, just use the LHS's width.
5172 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5173 return IntRange(L.Width, L.NonNegative && R.NonNegative);
5174 }
5175
5176 // The result of a remainder can't be larger than the result of
5177 // either side.
5178 case BO_Rem: {
5179 // Don't 'pre-truncate' the operands.
Eli Friedman09bddcf2013-07-08 20:20:06 +00005180 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00005181 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5182 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5183
5184 IntRange meet = IntRange::meet(L, R);
5185 meet.Width = std::min(meet.Width, MaxWidth);
5186 return meet;
5187 }
5188
5189 // The default behavior is okay for these.
5190 case BO_Mul:
5191 case BO_Add:
5192 case BO_Xor:
5193 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00005194 break;
5195 }
5196
John McCall00fe7612011-07-14 22:39:48 +00005197 // The default case is to treat the operation as if it were closed
5198 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00005199 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5200 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5201 return IntRange::join(L, R);
5202 }
5203
5204 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5205 switch (UO->getOpcode()) {
5206 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00005207 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00005208 return IntRange::forBoolType();
5209
5210 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00005211 case UO_Deref:
5212 case UO_AddrOf: // should be impossible
Eli Friedman09bddcf2013-07-08 20:20:06 +00005213 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00005214
5215 default:
5216 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5217 }
5218 }
5219
Ted Kremenek728a1fb2013-10-14 18:55:27 +00005220 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5221 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5222
John McCall993f43f2013-05-06 21:39:12 +00005223 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005224 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00005225 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00005226
Eli Friedman09bddcf2013-07-08 20:20:06 +00005227 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00005228}
John McCall51313c32010-01-04 23:31:57 +00005229
Ted Kremenek0692a192012-01-31 05:37:37 +00005230static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedman09bddcf2013-07-08 20:20:06 +00005231 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCall323ed742010-05-06 08:58:33 +00005232}
5233
John McCall51313c32010-01-04 23:31:57 +00005234/// Checks whether the given value, which currently has the given
5235/// source semantics, has the same value when coerced through the
5236/// target semantics.
Ted Kremenek0692a192012-01-31 05:37:37 +00005237static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5238 const llvm::fltSemantics &Src,
5239 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00005240 llvm::APFloat truncated = value;
5241
5242 bool ignored;
5243 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5244 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5245
5246 return truncated.bitwiseIsEqual(value);
5247}
5248
5249/// Checks whether the given value, which currently has the given
5250/// source semantics, has the same value when coerced through the
5251/// target semantics.
5252///
5253/// The value might be a vector of floats (or a complex number).
Ted Kremenek0692a192012-01-31 05:37:37 +00005254static bool IsSameFloatAfterCast(const APValue &value,
5255 const llvm::fltSemantics &Src,
5256 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00005257 if (value.isFloat())
5258 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5259
5260 if (value.isVector()) {
5261 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5262 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5263 return false;
5264 return true;
5265 }
5266
5267 assert(value.isComplexFloat());
5268 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5269 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5270}
5271
Ted Kremenek0692a192012-01-31 05:37:37 +00005272static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00005273
Ted Kremeneke3b159c2010-09-23 21:43:44 +00005274static bool IsZero(Sema &S, Expr *E) {
5275 // Suppress cases where we are comparing against an enum constant.
5276 if (const DeclRefExpr *DR =
5277 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5278 if (isa<EnumConstantDecl>(DR->getDecl()))
5279 return false;
5280
5281 // Suppress cases where the '0' value is expanded from a macro.
5282 if (E->getLocStart().isMacroID())
5283 return false;
5284
John McCall323ed742010-05-06 08:58:33 +00005285 llvm::APSInt Value;
5286 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5287}
5288
John McCall372e1032010-10-06 00:25:24 +00005289static bool HasEnumType(Expr *E) {
5290 // Strip off implicit integral promotions.
5291 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00005292 if (ICE->getCastKind() != CK_IntegralCast &&
5293 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00005294 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00005295 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00005296 }
5297
5298 return E->getType()->isEnumeralType();
5299}
5300
Ted Kremenek0692a192012-01-31 05:37:37 +00005301static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieucbc19872013-11-01 21:47:19 +00005302 // Disable warning in template instantiations.
5303 if (!S.ActiveTemplateInstantiations.empty())
5304 return;
5305
John McCall2de56d12010-08-25 11:45:40 +00005306 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00005307 if (E->isValueDependent())
5308 return;
5309
John McCall2de56d12010-08-25 11:45:40 +00005310 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00005311 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00005312 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00005313 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005314 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00005315 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00005316 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00005317 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005318 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00005319 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00005320 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00005321 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005322 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00005323 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00005324 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00005325 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5326 }
5327}
5328
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005329static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00005330 Expr *Constant, Expr *Other,
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005331 llvm::APSInt Value,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00005332 bool RhsConstant) {
Richard Trieu311cb2b2013-11-01 21:19:43 +00005333 // Disable warning in template instantiations.
5334 if (!S.ActiveTemplateInstantiations.empty())
5335 return;
5336
Richard Trieu526e6272012-11-14 22:50:24 +00005337 // 0 values are handled later by CheckTrivialUnsignedComparison().
5338 if (Value == 0)
5339 return;
5340
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005341 BinaryOperatorKind op = E->getOpcode();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00005342 QualType OtherT = Other->getType();
5343 QualType ConstantT = Constant->getType();
Richard Trieu526e6272012-11-14 22:50:24 +00005344 QualType CommonT = E->getLHS()->getType();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00005345 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005346 return;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00005347 assert((OtherT->isIntegerType() && ConstantT->isIntegerType())
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005348 && "comparison with non-integer type");
Richard Trieu526e6272012-11-14 22:50:24 +00005349
5350 bool ConstantSigned = ConstantT->isSignedIntegerType();
Richard Trieu526e6272012-11-14 22:50:24 +00005351 bool CommonSigned = CommonT->isSignedIntegerType();
5352
5353 bool EqualityOnly = false;
5354
5355 // TODO: Investigate using GetExprRange() to get tighter bounds on
5356 // on the bit ranges.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005357 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
Richard Trieu526e6272012-11-14 22:50:24 +00005358 unsigned OtherWidth = OtherRange.Width;
5359
5360 if (CommonSigned) {
5361 // The common type is signed, therefore no signed to unsigned conversion.
Eli Friedmand87de7b2012-11-30 23:09:29 +00005362 if (!OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00005363 // Check that the constant is representable in type OtherT.
5364 if (ConstantSigned) {
5365 if (OtherWidth >= Value.getMinSignedBits())
5366 return;
5367 } else { // !ConstantSigned
5368 if (OtherWidth >= Value.getActiveBits() + 1)
5369 return;
5370 }
5371 } else { // !OtherSigned
5372 // Check that the constant is representable in type OtherT.
5373 // Negative values are out of range.
5374 if (ConstantSigned) {
5375 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
5376 return;
5377 } else { // !ConstantSigned
5378 if (OtherWidth >= Value.getActiveBits())
5379 return;
5380 }
5381 }
5382 } else { // !CommonSigned
Eli Friedmand87de7b2012-11-30 23:09:29 +00005383 if (OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00005384 if (OtherWidth >= Value.getActiveBits())
5385 return;
Eli Friedmand87de7b2012-11-30 23:09:29 +00005386 } else if (!OtherRange.NonNegative && !ConstantSigned) {
Richard Trieu526e6272012-11-14 22:50:24 +00005387 // Check to see if the constant is representable in OtherT.
5388 if (OtherWidth > Value.getActiveBits())
5389 return;
5390 // Check to see if the constant is equivalent to a negative value
5391 // cast to CommonT.
5392 if (S.Context.getIntWidth(ConstantT) == S.Context.getIntWidth(CommonT) &&
Richard Trieu5d1cf4f2012-11-15 03:43:50 +00005393 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
Richard Trieu526e6272012-11-14 22:50:24 +00005394 return;
5395 // The constant value rests between values that OtherT can represent after
5396 // conversion. Relational comparison still works, but equality
5397 // comparisons will be tautological.
5398 EqualityOnly = true;
5399 } else { // OtherSigned && ConstantSigned
5400 assert(0 && "Two signed types converted to unsigned types.");
5401 }
5402 }
5403
5404 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
5405
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005406 bool IsTrue = true;
Richard Trieu526e6272012-11-14 22:50:24 +00005407 if (op == BO_EQ || op == BO_NE) {
5408 IsTrue = op == BO_NE;
5409 } else if (EqualityOnly) {
5410 return;
5411 } else if (RhsConstant) {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005412 if (op == BO_GT || op == BO_GE)
Richard Trieu526e6272012-11-14 22:50:24 +00005413 IsTrue = !PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005414 else // op == BO_LT || op == BO_LE
Richard Trieu526e6272012-11-14 22:50:24 +00005415 IsTrue = PositiveConstant;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00005416 } else {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005417 if (op == BO_LT || op == BO_LE)
Richard Trieu526e6272012-11-14 22:50:24 +00005418 IsTrue = !PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005419 else // op == BO_GT || op == BO_GE
Richard Trieu526e6272012-11-14 22:50:24 +00005420 IsTrue = PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005421 }
Ted Kremenek7adf3a92013-03-15 21:50:10 +00005422
5423 // If this is a comparison to an enum constant, include that
5424 // constant in the diagnostic.
5425 const EnumConstantDecl *ED = 0;
5426 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
5427 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
5428
5429 SmallString<64> PrettySourceValue;
5430 llvm::raw_svector_ostream OS(PrettySourceValue);
5431 if (ED)
Ted Kremenek9de50942013-03-15 22:02:46 +00005432 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenek7adf3a92013-03-15 21:50:10 +00005433 else
5434 OS << Value;
5435
Stephen Hines651f13c2014-04-23 16:59:28 -07005436 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5437 S.PDiag(diag::warn_out_of_range_compare)
5438 << OS.str() << OtherT << IsTrue
5439 << E->getLHS()->getSourceRange()
5440 << E->getRHS()->getSourceRange());
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005441}
5442
John McCall323ed742010-05-06 08:58:33 +00005443/// Analyze the operands of the given comparison. Implements the
5444/// fallback case from AnalyzeComparison.
Ted Kremenek0692a192012-01-31 05:37:37 +00005445static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00005446 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5447 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00005448}
John McCall51313c32010-01-04 23:31:57 +00005449
John McCallba26e582010-01-04 23:21:16 +00005450/// \brief Implements -Wsign-compare.
5451///
Richard Trieudd225092011-09-15 21:56:47 +00005452/// \param E the binary operator to check for warnings
Ted Kremenek0692a192012-01-31 05:37:37 +00005453static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCall323ed742010-05-06 08:58:33 +00005454 // The type the comparison is being performed in.
5455 QualType T = E->getLHS()->getType();
5456 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
5457 && "comparison with mismatched types");
Fariborz Jahanianab4702f2012-09-18 17:46:26 +00005458 if (E->isValueDependent())
5459 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00005460
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005461 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
5462 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005463
5464 bool IsComparisonConstant = false;
5465
Fariborz Jahaniana193f202012-09-20 19:36:41 +00005466 // Check whether an integer constant comparison results in a value
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005467 // of 'true' or 'false'.
5468 if (T->isIntegralType(S.Context)) {
5469 llvm::APSInt RHSValue;
5470 bool IsRHSIntegralLiteral =
5471 RHS->isIntegerConstantExpr(RHSValue, S.Context);
5472 llvm::APSInt LHSValue;
5473 bool IsLHSIntegralLiteral =
5474 LHS->isIntegerConstantExpr(LHSValue, S.Context);
5475 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
5476 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
5477 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
5478 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
5479 else
5480 IsComparisonConstant =
5481 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahaniana193f202012-09-20 19:36:41 +00005482 } else if (!T->hasUnsignedIntegerRepresentation())
5483 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005484
John McCall323ed742010-05-06 08:58:33 +00005485 // We don't do anything special if this isn't an unsigned integral
5486 // comparison: we're only interested in integral comparisons, and
5487 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00005488 //
5489 // We also don't care about value-dependent expressions or expressions
5490 // whose result is a constant.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005491 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCall323ed742010-05-06 08:58:33 +00005492 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005493
John McCall323ed742010-05-06 08:58:33 +00005494 // Check to see if one of the (unmodified) operands is of different
5495 // signedness.
5496 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00005497 if (LHS->getType()->hasSignedIntegerRepresentation()) {
5498 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00005499 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00005500 signedOperand = LHS;
5501 unsignedOperand = RHS;
5502 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
5503 signedOperand = RHS;
5504 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00005505 } else {
John McCall323ed742010-05-06 08:58:33 +00005506 CheckTrivialUnsignedComparison(S, E);
5507 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00005508 }
5509
John McCall323ed742010-05-06 08:58:33 +00005510 // Otherwise, calculate the effective range of the signed operand.
5511 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00005512
John McCall323ed742010-05-06 08:58:33 +00005513 // Go ahead and analyze implicit conversions in the operands. Note
5514 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00005515 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
5516 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00005517
John McCall323ed742010-05-06 08:58:33 +00005518 // If the signed range is non-negative, -Wsign-compare won't fire,
5519 // but we should still check for comparisons which are always true
5520 // or false.
5521 if (signedRange.NonNegative)
5522 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00005523
5524 // For (in)equality comparisons, if the unsigned operand is a
5525 // constant which cannot collide with a overflowed signed operand,
5526 // then reinterpreting the signed operand as unsigned will not
5527 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00005528 if (E->isEqualityOp()) {
5529 unsigned comparisonWidth = S.Context.getIntWidth(T);
5530 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00005531
John McCall323ed742010-05-06 08:58:33 +00005532 // We should never be unable to prove that the unsigned operand is
5533 // non-negative.
5534 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
5535
5536 if (unsignedRange.Width < comparisonWidth)
5537 return;
5538 }
5539
Douglas Gregor6d3b93d2012-05-01 01:53:49 +00005540 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5541 S.PDiag(diag::warn_mixed_sign_comparison)
5542 << LHS->getType() << RHS->getType()
5543 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallba26e582010-01-04 23:21:16 +00005544}
5545
John McCall15d7d122010-11-11 03:21:53 +00005546/// Analyzes an attempt to assign the given value to a bitfield.
5547///
5548/// Returns true if there was something fishy about the attempt.
Ted Kremenek0692a192012-01-31 05:37:37 +00005549static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
5550 SourceLocation InitLoc) {
John McCall15d7d122010-11-11 03:21:53 +00005551 assert(Bitfield->isBitField());
5552 if (Bitfield->isInvalidDecl())
5553 return false;
5554
John McCall91b60142010-11-11 05:33:51 +00005555 // White-list bool bitfields.
5556 if (Bitfield->getType()->isBooleanType())
5557 return false;
5558
Douglas Gregor46ff3032011-02-04 13:09:01 +00005559 // Ignore value- or type-dependent expressions.
5560 if (Bitfield->getBitWidth()->isValueDependent() ||
5561 Bitfield->getBitWidth()->isTypeDependent() ||
5562 Init->isValueDependent() ||
5563 Init->isTypeDependent())
5564 return false;
5565
John McCall15d7d122010-11-11 03:21:53 +00005566 Expr *OriginalInit = Init->IgnoreParenImpCasts();
5567
Richard Smith80d4b552011-12-28 19:48:30 +00005568 llvm::APSInt Value;
5569 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00005570 return false;
5571
John McCall15d7d122010-11-11 03:21:53 +00005572 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005573 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00005574
5575 if (OriginalWidth <= FieldWidth)
5576 return false;
5577
Eli Friedman3a643af2012-01-26 23:11:39 +00005578 // Compute the value which the bitfield will contain.
Jay Foad9f71a8f2010-12-07 08:25:34 +00005579 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedman3a643af2012-01-26 23:11:39 +00005580 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall15d7d122010-11-11 03:21:53 +00005581
Eli Friedman3a643af2012-01-26 23:11:39 +00005582 // Check whether the stored value is equal to the original value.
5583 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieue1ecdc12012-07-23 20:21:35 +00005584 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall15d7d122010-11-11 03:21:53 +00005585 return false;
5586
Eli Friedman3a643af2012-01-26 23:11:39 +00005587 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedman34ff0622012-02-02 00:40:20 +00005588 // therefore don't strictly fit into a signed bitfield of width 1.
5589 if (FieldWidth == 1 && Value == 1)
Eli Friedman3a643af2012-01-26 23:11:39 +00005590 return false;
5591
John McCall15d7d122010-11-11 03:21:53 +00005592 std::string PrettyValue = Value.toString(10);
5593 std::string PrettyTrunc = TruncatedValue.toString(10);
5594
5595 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
5596 << PrettyValue << PrettyTrunc << OriginalInit->getType()
5597 << Init->getSourceRange();
5598
5599 return true;
5600}
5601
John McCallbeb22aa2010-11-09 23:24:47 +00005602/// Analyze the given simple or compound assignment for warning-worthy
5603/// operations.
Ted Kremenek0692a192012-01-31 05:37:37 +00005604static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCallbeb22aa2010-11-09 23:24:47 +00005605 // Just recurse on the LHS.
5606 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5607
5608 // We want to recurse on the RHS as normal unless we're assigning to
5609 // a bitfield.
John McCall993f43f2013-05-06 21:39:12 +00005610 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005611 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall15d7d122010-11-11 03:21:53 +00005612 E->getOperatorLoc())) {
5613 // Recurse, ignoring any implicit conversions on the RHS.
5614 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
5615 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00005616 }
5617 }
5618
5619 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
5620}
5621
John McCall51313c32010-01-04 23:31:57 +00005622/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00005623static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00005624 SourceLocation CContext, unsigned diag,
5625 bool pruneControlFlow = false) {
5626 if (pruneControlFlow) {
5627 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5628 S.PDiag(diag)
5629 << SourceType << T << E->getSourceRange()
5630 << SourceRange(CContext));
5631 return;
5632 }
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005633 S.Diag(E->getExprLoc(), diag)
5634 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
5635}
5636
Chandler Carruthe1b02e02011-04-05 06:47:57 +00005637/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00005638static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00005639 SourceLocation CContext, unsigned diag,
5640 bool pruneControlFlow = false) {
5641 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruthe1b02e02011-04-05 06:47:57 +00005642}
5643
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005644/// Diagnose an implicit cast from a literal expression. Does not warn when the
5645/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00005646void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
5647 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005648 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00005649 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005650 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00005651 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
5652 T->hasUnsignedIntegerRepresentation());
5653 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00005654 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005655 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00005656 return;
5657
Eli Friedman4e1a82c2013-08-29 23:44:43 +00005658 // FIXME: Force the precision of the source value down so we don't print
5659 // digits which are usually useless (we don't really care here if we
5660 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
5661 // would automatically print the shortest representation, but it's a bit
5662 // tricky to implement.
David Blaikiebe0ee872012-05-15 16:56:36 +00005663 SmallString<16> PrettySourceValue;
Eli Friedman4e1a82c2013-08-29 23:44:43 +00005664 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
5665 precision = (precision * 59 + 195) / 196;
5666 Value.toString(PrettySourceValue, precision);
5667
David Blaikiede7e7b82012-05-15 17:18:27 +00005668 SmallString<16> PrettyTargetValue;
David Blaikiebe0ee872012-05-15 16:56:36 +00005669 if (T->isSpecificBuiltinType(BuiltinType::Bool))
5670 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
5671 else
David Blaikiede7e7b82012-05-15 17:18:27 +00005672 IntegerValue.toString(PrettyTargetValue);
David Blaikiebe0ee872012-05-15 16:56:36 +00005673
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005674 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikiebe0ee872012-05-15 16:56:36 +00005675 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
5676 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00005677}
5678
John McCall091f23f2010-11-09 22:22:12 +00005679std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
5680 if (!Range.Width) return "0";
5681
5682 llvm::APSInt ValueInRange = Value;
5683 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00005684 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00005685 return ValueInRange.toString(10);
5686}
5687
Hans Wennborg88617a22012-08-28 15:44:30 +00005688static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
5689 if (!isa<ImplicitCastExpr>(Ex))
5690 return false;
5691
5692 Expr *InnerE = Ex->IgnoreParenImpCasts();
5693 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
5694 const Type *Source =
5695 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5696 if (Target->isDependentType())
5697 return false;
5698
5699 const BuiltinType *FloatCandidateBT =
5700 dyn_cast<BuiltinType>(ToBool ? Source : Target);
5701 const Type *BoolCandidateType = ToBool ? Target : Source;
5702
5703 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
5704 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
5705}
5706
5707void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
5708 SourceLocation CC) {
5709 unsigned NumArgs = TheCall->getNumArgs();
5710 for (unsigned i = 0; i < NumArgs; ++i) {
5711 Expr *CurrA = TheCall->getArg(i);
5712 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
5713 continue;
5714
5715 bool IsSwapped = ((i > 0) &&
5716 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
5717 IsSwapped |= ((i < (NumArgs - 1)) &&
5718 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
5719 if (IsSwapped) {
5720 // Warn on this floating-point to bool conversion.
5721 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
5722 CurrA->getType(), CC,
5723 diag::warn_impcast_floating_point_to_bool);
5724 }
5725 }
5726}
5727
John McCall323ed742010-05-06 08:58:33 +00005728void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005729 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00005730 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00005731
John McCall323ed742010-05-06 08:58:33 +00005732 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
5733 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
5734 if (Source == Target) return;
5735 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00005736
Chandler Carruth108f7562011-07-26 05:40:03 +00005737 // If the conversion context location is invalid don't complain. We also
5738 // don't want to emit a warning if the issue occurs from the expansion of
5739 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
5740 // delay this check as long as possible. Once we detect we are in that
5741 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00005742 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00005743 return;
5744
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005745 // Diagnose implicit casts to bool.
5746 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
5747 if (isa<StringLiteral>(E))
5748 // Warn on string literal to bool. Checks for string literals in logical
Stephen Hines651f13c2014-04-23 16:59:28 -07005749 // and expressions, for instance, assert(0 && "error here"), are
5750 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005751 return DiagnoseImpCast(S, E, T, CC,
5752 diag::warn_impcast_string_literal_to_bool);
Stephen Hines651f13c2014-04-23 16:59:28 -07005753 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
5754 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
5755 // This covers the literal expressions that evaluate to Objective-C
5756 // objects.
5757 return DiagnoseImpCast(S, E, T, CC,
5758 diag::warn_impcast_objective_c_literal_to_bool);
5759 }
5760 if (Source->isPointerType() || Source->canDecayToPointerType()) {
5761 // Warn on pointer to bool conversion that is always true.
5762 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
5763 SourceRange(CC));
Lang Hamese14ca9f2011-12-05 20:49:50 +00005764 }
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005765 }
John McCall51313c32010-01-04 23:31:57 +00005766
5767 // Strip vector types.
5768 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00005769 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005770 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005771 return;
John McCallb4eb64d2010-10-08 02:01:28 +00005772 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005773 }
Chris Lattnerb792b302011-06-14 04:51:15 +00005774
5775 // If the vector cast is cast between two vectors of the same size, it is
5776 // a bitcast, not a conversion.
5777 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
5778 return;
John McCall51313c32010-01-04 23:31:57 +00005779
5780 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
5781 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
5782 }
Stephen Hines651f13c2014-04-23 16:59:28 -07005783 if (auto VecTy = dyn_cast<VectorType>(Target))
5784 Target = VecTy->getElementType().getTypePtr();
John McCall51313c32010-01-04 23:31:57 +00005785
5786 // Strip complex types.
5787 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00005788 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005789 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005790 return;
5791
John McCallb4eb64d2010-10-08 02:01:28 +00005792 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005793 }
John McCall51313c32010-01-04 23:31:57 +00005794
5795 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
5796 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
5797 }
5798
5799 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
5800 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
5801
5802 // If the source is floating point...
5803 if (SourceBT && SourceBT->isFloatingPoint()) {
5804 // ...and the target is floating point...
5805 if (TargetBT && TargetBT->isFloatingPoint()) {
5806 // ...then warn if we're dropping FP rank.
5807
5808 // Builtin FP kinds are ordered by increasing FP rank.
5809 if (SourceBT->getKind() > TargetBT->getKind()) {
5810 // Don't warn about float constants that are precisely
5811 // representable in the target type.
5812 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00005813 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00005814 // Value might be a float, a float vector, or a float complex.
5815 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00005816 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
5817 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00005818 return;
5819 }
5820
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005821 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005822 return;
5823
John McCallb4eb64d2010-10-08 02:01:28 +00005824 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00005825 }
5826 return;
5827 }
5828
Ted Kremenekef9ff882011-03-10 20:03:42 +00005829 // If the target is integral, always warn.
David Blaikiebe0ee872012-05-15 16:56:36 +00005830 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005831 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005832 return;
5833
Chandler Carrutha5b93322011-02-17 11:05:49 +00005834 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00005835 // We also want to warn on, e.g., "int i = -1.234"
5836 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
5837 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
5838 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
5839
Chandler Carruthf65076e2011-04-10 08:36:24 +00005840 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
5841 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00005842 } else {
5843 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
5844 }
5845 }
John McCall51313c32010-01-04 23:31:57 +00005846
Hans Wennborg88617a22012-08-28 15:44:30 +00005847 // If the target is bool, warn if expr is a function or method call.
5848 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
5849 isa<CallExpr>(E)) {
5850 // Check last argument of function call to see if it is an
5851 // implicit cast from a type matching the type the result
5852 // is being cast to.
5853 CallExpr *CEx = cast<CallExpr>(E);
5854 unsigned NumArgs = CEx->getNumArgs();
5855 if (NumArgs > 0) {
5856 Expr *LastA = CEx->getArg(NumArgs - 1);
5857 Expr *InnerE = LastA->IgnoreParenImpCasts();
5858 const Type *InnerType =
5859 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5860 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
5861 // Warn on this floating-point to bool conversion
5862 DiagnoseImpCast(S, E, T, CC,
5863 diag::warn_impcast_floating_point_to_bool);
5864 }
5865 }
5866 }
John McCall51313c32010-01-04 23:31:57 +00005867 return;
5868 }
5869
Richard Trieu1838ca52011-05-29 19:59:02 +00005870 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikieb26331b2012-06-19 21:19:06 +00005871 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiee81b43b2012-11-08 00:41:20 +00005872 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikie896c7dd2013-02-16 00:56:22 +00005873 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieb1360492012-03-16 20:30:12 +00005874 SourceLocation Loc = E->getSourceRange().getBegin();
5875 if (Loc.isMacroID())
5876 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie9fb1ac52012-05-15 21:57:38 +00005877 if (!Loc.isMacroID() || CC.isMacroID())
5878 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
5879 << T << clang::SourceRange(CC)
Richard Smith8adf8372013-09-20 00:27:40 +00005880 << FixItHint::CreateReplacement(Loc,
5881 S.getFixItZeroLiteralForType(T, Loc));
Richard Trieu1838ca52011-05-29 19:59:02 +00005882 }
5883
David Blaikieb26331b2012-06-19 21:19:06 +00005884 if (!Source->isIntegerType() || !Target->isIntegerType())
5885 return;
5886
David Blaikiebe0ee872012-05-15 16:56:36 +00005887 // TODO: remove this early return once the false positives for constant->bool
5888 // in templates, macros, etc, are reduced or removed.
5889 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
5890 return;
5891
John McCall323ed742010-05-06 08:58:33 +00005892 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00005893 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00005894
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005895 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer25ffbef2013-03-28 19:07:11 +00005896 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005897 // TODO: this should happen for bitfield stores, too.
5898 llvm::APSInt Value(32);
5899 if (E->isIntegerConstantExpr(Value, S.Context)) {
5900 if (S.SourceMgr.isInSystemMacro(CC))
5901 return;
5902
John McCall091f23f2010-11-09 22:22:12 +00005903 std::string PrettySourceValue = Value.toString(10);
5904 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005905
Ted Kremenek5e745da2011-10-22 02:37:33 +00005906 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5907 S.PDiag(diag::warn_impcast_integer_precision_constant)
5908 << PrettySourceValue << PrettyTargetValue
5909 << E->getType() << T << E->getSourceRange()
5910 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00005911 return;
5912 }
5913
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005914 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
5915 if (S.SourceMgr.isInSystemMacro(CC))
5916 return;
5917
David Blaikie37050842012-04-12 22:40:54 +00005918 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaksc36bedc2012-02-01 19:08:57 +00005919 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
5920 /* pruneControlFlow */ true);
John McCallb4eb64d2010-10-08 02:01:28 +00005921 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00005922 }
5923
5924 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
5925 (!TargetRange.NonNegative && SourceRange.NonNegative &&
5926 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00005927
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005928 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005929 return;
5930
John McCall323ed742010-05-06 08:58:33 +00005931 unsigned DiagID = diag::warn_impcast_integer_sign;
5932
5933 // Traditionally, gcc has warned about this under -Wsign-compare.
5934 // We also want to warn about it in -Wconversion.
5935 // So if -Wconversion is off, use a completely identical diagnostic
5936 // in the sign-compare group.
5937 // The conditional-checking code will
5938 if (ICContext) {
5939 DiagID = diag::warn_impcast_integer_sign_conditional;
5940 *ICContext = true;
5941 }
5942
John McCallb4eb64d2010-10-08 02:01:28 +00005943 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00005944 }
5945
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005946 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005947 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
5948 // type, to give us better diagnostics.
5949 QualType SourceType = E->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +00005950 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005951 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5952 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
5953 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
5954 SourceType = S.Context.getTypeDeclType(Enum);
5955 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
5956 }
5957 }
5958
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005959 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
5960 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall83972f12013-03-09 00:54:27 +00005961 if (SourceEnum->getDecl()->hasNameForLinkage() &&
5962 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00005963 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005964 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005965 return;
5966
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005967 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005968 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005969 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005970
John McCall51313c32010-01-04 23:31:57 +00005971 return;
5972}
5973
David Blaikie9fb1ac52012-05-15 21:57:38 +00005974void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5975 SourceLocation CC, QualType T);
John McCall323ed742010-05-06 08:58:33 +00005976
5977void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00005978 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00005979 E = E->IgnoreParenImpCasts();
5980
5981 if (isa<ConditionalOperator>(E))
David Blaikie9fb1ac52012-05-15 21:57:38 +00005982 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCall323ed742010-05-06 08:58:33 +00005983
John McCallb4eb64d2010-10-08 02:01:28 +00005984 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005985 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00005986 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00005987 return;
5988}
5989
David Blaikie9fb1ac52012-05-15 21:57:38 +00005990void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5991 SourceLocation CC, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00005992 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00005993
5994 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00005995 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
5996 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00005997
5998 // If -Wconversion would have warned about either of the candidates
5999 // for a signedness conversion to the context type...
6000 if (!Suspicious) return;
6001
6002 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00006003 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
6004 CC))
John McCall323ed742010-05-06 08:58:33 +00006005 return;
6006
John McCall323ed742010-05-06 08:58:33 +00006007 // ...then check whether it would have warned about either of the
6008 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00006009 if (E->getType() == T) return;
6010
6011 Suspicious = false;
6012 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
6013 E->getType(), CC, &Suspicious);
6014 if (!Suspicious)
6015 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00006016 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00006017}
6018
6019/// AnalyzeImplicitConversions - Find and report any interesting
6020/// implicit conversions in the given expression. There are a couple
6021/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00006022void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00006023 QualType T = OrigE->getType();
6024 Expr *E = OrigE->IgnoreParenImpCasts();
6025
Douglas Gregorf8b6e152011-10-10 17:38:18 +00006026 if (E->isTypeDependent() || E->isValueDependent())
6027 return;
6028
John McCall323ed742010-05-06 08:58:33 +00006029 // For conditional operators, we analyze the arguments as if they
6030 // were being fed directly into the output.
6031 if (isa<ConditionalOperator>(E)) {
6032 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie9fb1ac52012-05-15 21:57:38 +00006033 CheckConditionalOperator(S, CO, CC, T);
John McCall323ed742010-05-06 08:58:33 +00006034 return;
6035 }
6036
Hans Wennborg88617a22012-08-28 15:44:30 +00006037 // Check implicit argument conversions for function calls.
6038 if (CallExpr *Call = dyn_cast<CallExpr>(E))
6039 CheckImplicitArgumentConversions(S, Call, CC);
6040
John McCall323ed742010-05-06 08:58:33 +00006041 // Go ahead and check any implicit conversions we might have skipped.
6042 // The non-canonical typecheck is just an optimization;
6043 // CheckImplicitConversion will filter out dead implicit conversions.
6044 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00006045 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00006046
6047 // Now continue drilling into this expression.
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00006048
6049 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00006050 if (POE->getResultExpr())
6051 E = POE->getResultExpr();
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00006052 }
6053
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00006054 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6055 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6056
John McCall323ed742010-05-06 08:58:33 +00006057 // Skip past explicit casts.
6058 if (isa<ExplicitCastExpr>(E)) {
6059 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00006060 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00006061 }
6062
John McCallbeb22aa2010-11-09 23:24:47 +00006063 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6064 // Do a somewhat different check with comparison operators.
6065 if (BO->isComparisonOp())
6066 return AnalyzeComparison(S, BO);
6067
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00006068 // And with simple assignments.
6069 if (BO->getOpcode() == BO_Assign)
John McCallbeb22aa2010-11-09 23:24:47 +00006070 return AnalyzeAssignment(S, BO);
6071 }
John McCall323ed742010-05-06 08:58:33 +00006072
6073 // These break the otherwise-useful invariant below. Fortunately,
6074 // we don't really need to recurse into them, because any internal
6075 // expressions should have been analyzed already when they were
6076 // built into statements.
6077 if (isa<StmtExpr>(E)) return;
6078
6079 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006080 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00006081
6082 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00006083 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00006084 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Stephen Hines651f13c2014-04-23 16:59:28 -07006085 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00006086 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor54042f12012-02-09 10:18:50 +00006087 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor503384f2012-02-09 00:47:04 +00006088 if (!ChildExpr)
6089 continue;
6090
Stephen Hines651f13c2014-04-23 16:59:28 -07006091 if (IsLogicalAndOperator &&
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00006092 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Stephen Hines651f13c2014-04-23 16:59:28 -07006093 // Ignore checking string literals that are in logical and operators.
6094 // This is a common pattern for asserts.
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00006095 continue;
6096 AnalyzeImplicitConversions(S, ChildExpr, CC);
6097 }
John McCall323ed742010-05-06 08:58:33 +00006098}
6099
6100} // end anonymous namespace
6101
Stephen Hines651f13c2014-04-23 16:59:28 -07006102enum {
6103 AddressOf,
6104 FunctionPointer,
6105 ArrayPointer
6106};
6107
6108/// \brief Diagnose pointers that are always non-null.
6109/// \param E the expression containing the pointer
6110/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6111/// compared to a null pointer
6112/// \param IsEqual True when the comparison is equal to a null pointer
6113/// \param Range Extra SourceRange to highlight in the diagnostic
6114void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
6115 Expr::NullPointerConstantKind NullKind,
6116 bool IsEqual, SourceRange Range) {
6117
6118 // Don't warn inside macros.
6119 if (E->getExprLoc().isMacroID())
6120 return;
6121 E = E->IgnoreImpCasts();
6122
6123 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
6124
6125 bool IsAddressOf = false;
6126
6127 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6128 if (UO->getOpcode() != UO_AddrOf)
6129 return;
6130 IsAddressOf = true;
6131 E = UO->getSubExpr();
6132 }
6133
6134 // Expect to find a single Decl. Skip anything more complicated.
6135 ValueDecl *D = 0;
6136 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
6137 D = R->getDecl();
6138 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6139 D = M->getMemberDecl();
6140 }
6141
6142 // Weak Decls can be null.
6143 if (!D || D->isWeak())
6144 return;
6145
6146 QualType T = D->getType();
6147 const bool IsArray = T->isArrayType();
6148 const bool IsFunction = T->isFunctionType();
6149
6150 if (IsAddressOf) {
6151 // Address of function is used to silence the function warning.
6152 if (IsFunction)
6153 return;
6154 // Address of reference can be null.
6155 if (T->isReferenceType())
6156 return;
6157 }
6158
6159 // Found nothing.
6160 if (!IsAddressOf && !IsFunction && !IsArray)
6161 return;
6162
6163 // Pretty print the expression for the diagnostic.
6164 std::string Str;
6165 llvm::raw_string_ostream S(Str);
6166 E->printPretty(S, 0, getPrintingPolicy());
6167
6168 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
6169 : diag::warn_impcast_pointer_to_bool;
6170 unsigned DiagType;
6171 if (IsAddressOf)
6172 DiagType = AddressOf;
6173 else if (IsFunction)
6174 DiagType = FunctionPointer;
6175 else if (IsArray)
6176 DiagType = ArrayPointer;
6177 else
6178 llvm_unreachable("Could not determine diagnostic.");
6179 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
6180 << Range << IsEqual;
6181
6182 if (!IsFunction)
6183 return;
6184
6185 // Suggest '&' to silence the function warning.
6186 Diag(E->getExprLoc(), diag::note_function_warning_silence)
6187 << FixItHint::CreateInsertion(E->getLocStart(), "&");
6188
6189 // Check to see if '()' fixit should be emitted.
6190 QualType ReturnType;
6191 UnresolvedSet<4> NonTemplateOverloads;
6192 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
6193 if (ReturnType.isNull())
6194 return;
6195
6196 if (IsCompare) {
6197 // There are two cases here. If there is null constant, the only suggest
6198 // for a pointer return type. If the null is 0, then suggest if the return
6199 // type is a pointer or an integer type.
6200 if (!ReturnType->isPointerType()) {
6201 if (NullKind == Expr::NPCK_ZeroExpression ||
6202 NullKind == Expr::NPCK_ZeroLiteral) {
6203 if (!ReturnType->isIntegerType())
6204 return;
6205 } else {
6206 return;
6207 }
6208 }
6209 } else { // !IsCompare
6210 // For function to bool, only suggest if the function pointer has bool
6211 // return type.
6212 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
6213 return;
6214 }
6215 Diag(E->getExprLoc(), diag::note_function_to_function_call)
6216 << FixItHint::CreateInsertion(
6217 getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
6218}
6219
6220
John McCall323ed742010-05-06 08:58:33 +00006221/// Diagnoses "dangerous" implicit conversions within the given
6222/// expression (which is a full expression). Implements -Wconversion
6223/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00006224///
6225/// \param CC the "context" location of the implicit conversion, i.e.
6226/// the most location of the syntactic entity requiring the implicit
6227/// conversion
6228void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00006229 // Don't diagnose in unevaluated contexts.
David Blaikie71f55f72012-08-06 22:47:24 +00006230 if (isUnevaluatedContext())
John McCall323ed742010-05-06 08:58:33 +00006231 return;
6232
6233 // Don't diagnose for value- or type-dependent expressions.
6234 if (E->isTypeDependent() || E->isValueDependent())
6235 return;
6236
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006237 // Check for array bounds violations in cases where the check isn't triggered
6238 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
6239 // ArraySubscriptExpr is on the RHS of a variable initialization.
6240 CheckArrayAccess(E);
6241
John McCallb4eb64d2010-10-08 02:01:28 +00006242 // This is not the right CC for (e.g.) a variable initialization.
6243 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00006244}
6245
Fariborz Jahanianad48a502013-01-24 22:11:45 +00006246/// Diagnose when expression is an integer constant expression and its evaluation
6247/// results in integer overflow
6248void Sema::CheckForIntOverflow (Expr *E) {
Richard Smith00043292013-11-05 22:23:30 +00006249 if (isa<BinaryOperator>(E->IgnoreParens()))
6250 E->EvaluateForOverflow(Context);
Fariborz Jahanianad48a502013-01-24 22:11:45 +00006251}
6252
Richard Smith6c3af3d2013-01-17 01:17:56 +00006253namespace {
6254/// \brief Visitor for expressions which looks for unsequenced operations on the
6255/// same object.
6256class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smith0c0b3902013-06-30 10:40:20 +00006257 typedef EvaluatedExprVisitor<SequenceChecker> Base;
6258
Richard Smith6c3af3d2013-01-17 01:17:56 +00006259 /// \brief A tree of sequenced regions within an expression. Two regions are
6260 /// unsequenced if one is an ancestor or a descendent of the other. When we
6261 /// finish processing an expression with sequencing, such as a comma
6262 /// expression, we fold its tree nodes into its parent, since they are
6263 /// unsequenced with respect to nodes we will visit later.
6264 class SequenceTree {
6265 struct Value {
6266 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
6267 unsigned Parent : 31;
6268 bool Merged : 1;
6269 };
Robert Wilhelme7205c02013-08-10 12:33:24 +00006270 SmallVector<Value, 8> Values;
Richard Smith6c3af3d2013-01-17 01:17:56 +00006271
6272 public:
6273 /// \brief A region within an expression which may be sequenced with respect
6274 /// to some other region.
6275 class Seq {
6276 explicit Seq(unsigned N) : Index(N) {}
6277 unsigned Index;
6278 friend class SequenceTree;
6279 public:
6280 Seq() : Index(0) {}
6281 };
6282
6283 SequenceTree() { Values.push_back(Value(0)); }
6284 Seq root() const { return Seq(0); }
6285
6286 /// \brief Create a new sequence of operations, which is an unsequenced
6287 /// subset of \p Parent. This sequence of operations is sequenced with
6288 /// respect to other children of \p Parent.
6289 Seq allocate(Seq Parent) {
6290 Values.push_back(Value(Parent.Index));
6291 return Seq(Values.size() - 1);
6292 }
6293
6294 /// \brief Merge a sequence of operations into its parent.
6295 void merge(Seq S) {
6296 Values[S.Index].Merged = true;
6297 }
6298
6299 /// \brief Determine whether two operations are unsequenced. This operation
6300 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
6301 /// should have been merged into its parent as appropriate.
6302 bool isUnsequenced(Seq Cur, Seq Old) {
6303 unsigned C = representative(Cur.Index);
6304 unsigned Target = representative(Old.Index);
6305 while (C >= Target) {
6306 if (C == Target)
6307 return true;
6308 C = Values[C].Parent;
6309 }
6310 return false;
6311 }
6312
6313 private:
6314 /// \brief Pick a representative for a sequence.
6315 unsigned representative(unsigned K) {
6316 if (Values[K].Merged)
6317 // Perform path compression as we go.
6318 return Values[K].Parent = representative(Values[K].Parent);
6319 return K;
6320 }
6321 };
6322
6323 /// An object for which we can track unsequenced uses.
6324 typedef NamedDecl *Object;
6325
6326 /// Different flavors of object usage which we track. We only track the
6327 /// least-sequenced usage of each kind.
6328 enum UsageKind {
6329 /// A read of an object. Multiple unsequenced reads are OK.
6330 UK_Use,
6331 /// A modification of an object which is sequenced before the value
Richard Smith418dd3e2013-06-26 23:16:51 +00006332 /// computation of the expression, such as ++n in C++.
Richard Smith6c3af3d2013-01-17 01:17:56 +00006333 UK_ModAsValue,
6334 /// A modification of an object which is not sequenced before the value
6335 /// computation of the expression, such as n++.
6336 UK_ModAsSideEffect,
6337
6338 UK_Count = UK_ModAsSideEffect + 1
6339 };
6340
6341 struct Usage {
6342 Usage() : Use(0), Seq() {}
6343 Expr *Use;
6344 SequenceTree::Seq Seq;
6345 };
6346
6347 struct UsageInfo {
6348 UsageInfo() : Diagnosed(false) {}
6349 Usage Uses[UK_Count];
6350 /// Have we issued a diagnostic for this variable already?
6351 bool Diagnosed;
6352 };
6353 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
6354
6355 Sema &SemaRef;
6356 /// Sequenced regions within the expression.
6357 SequenceTree Tree;
6358 /// Declaration modifications and references which we have seen.
6359 UsageInfoMap UsageMap;
6360 /// The region we are currently within.
6361 SequenceTree::Seq Region;
6362 /// Filled in with declarations which were modified as a side-effect
6363 /// (that is, post-increment operations).
Robert Wilhelme7205c02013-08-10 12:33:24 +00006364 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smith1a2dcd52013-01-17 23:18:09 +00006365 /// Expressions to check later. We defer checking these to reduce
6366 /// stack usage.
Robert Wilhelme7205c02013-08-10 12:33:24 +00006367 SmallVectorImpl<Expr *> &WorkList;
Richard Smith6c3af3d2013-01-17 01:17:56 +00006368
6369 /// RAII object wrapping the visitation of a sequenced subexpression of an
6370 /// expression. At the end of this process, the side-effects of the evaluation
6371 /// become sequenced with respect to the value computation of the result, so
6372 /// we downgrade any UK_ModAsSideEffect within the evaluation to
6373 /// UK_ModAsValue.
6374 struct SequencedSubexpression {
6375 SequencedSubexpression(SequenceChecker &Self)
6376 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
6377 Self.ModAsSideEffect = &ModAsSideEffect;
6378 }
6379 ~SequencedSubexpression() {
6380 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
6381 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
6382 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
6383 Self.addUsage(U, ModAsSideEffect[I].first,
6384 ModAsSideEffect[I].second.Use, UK_ModAsValue);
6385 }
6386 Self.ModAsSideEffect = OldModAsSideEffect;
6387 }
6388
6389 SequenceChecker &Self;
Robert Wilhelme7205c02013-08-10 12:33:24 +00006390 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
6391 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smith6c3af3d2013-01-17 01:17:56 +00006392 };
6393
Richard Smith67470052013-06-20 22:21:56 +00006394 /// RAII object wrapping the visitation of a subexpression which we might
6395 /// choose to evaluate as a constant. If any subexpression is evaluated and
6396 /// found to be non-constant, this allows us to suppress the evaluation of
6397 /// the outer expression.
6398 class EvaluationTracker {
6399 public:
6400 EvaluationTracker(SequenceChecker &Self)
6401 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
6402 Self.EvalTracker = this;
6403 }
6404 ~EvaluationTracker() {
6405 Self.EvalTracker = Prev;
6406 if (Prev)
6407 Prev->EvalOK &= EvalOK;
6408 }
6409
6410 bool evaluate(const Expr *E, bool &Result) {
6411 if (!EvalOK || E->isValueDependent())
6412 return false;
6413 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
6414 return EvalOK;
6415 }
6416
6417 private:
6418 SequenceChecker &Self;
6419 EvaluationTracker *Prev;
6420 bool EvalOK;
6421 } *EvalTracker;
6422
Richard Smith6c3af3d2013-01-17 01:17:56 +00006423 /// \brief Find the object which is produced by the specified expression,
6424 /// if any.
6425 Object getObject(Expr *E, bool Mod) const {
6426 E = E->IgnoreParenCasts();
6427 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6428 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
6429 return getObject(UO->getSubExpr(), Mod);
6430 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6431 if (BO->getOpcode() == BO_Comma)
6432 return getObject(BO->getRHS(), Mod);
6433 if (Mod && BO->isAssignmentOp())
6434 return getObject(BO->getLHS(), Mod);
6435 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
6436 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
6437 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
6438 return ME->getMemberDecl();
6439 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6440 // FIXME: If this is a reference, map through to its value.
6441 return DRE->getDecl();
6442 return 0;
6443 }
6444
6445 /// \brief Note that an object was modified or used by an expression.
6446 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
6447 Usage &U = UI.Uses[UK];
6448 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
6449 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
6450 ModAsSideEffect->push_back(std::make_pair(O, U));
6451 U.Use = Ref;
6452 U.Seq = Region;
6453 }
6454 }
6455 /// \brief Check whether a modification or use conflicts with a prior usage.
6456 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
6457 bool IsModMod) {
6458 if (UI.Diagnosed)
6459 return;
6460
6461 const Usage &U = UI.Uses[OtherKind];
6462 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
6463 return;
6464
6465 Expr *Mod = U.Use;
6466 Expr *ModOrUse = Ref;
6467 if (OtherKind == UK_Use)
6468 std::swap(Mod, ModOrUse);
6469
6470 SemaRef.Diag(Mod->getExprLoc(),
6471 IsModMod ? diag::warn_unsequenced_mod_mod
6472 : diag::warn_unsequenced_mod_use)
6473 << O << SourceRange(ModOrUse->getExprLoc());
6474 UI.Diagnosed = true;
6475 }
6476
6477 void notePreUse(Object O, Expr *Use) {
6478 UsageInfo &U = UsageMap[O];
6479 // Uses conflict with other modifications.
6480 checkUsage(O, U, Use, UK_ModAsValue, false);
6481 }
6482 void notePostUse(Object O, Expr *Use) {
6483 UsageInfo &U = UsageMap[O];
6484 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
6485 addUsage(U, O, Use, UK_Use);
6486 }
6487
6488 void notePreMod(Object O, Expr *Mod) {
6489 UsageInfo &U = UsageMap[O];
6490 // Modifications conflict with other modifications and with uses.
6491 checkUsage(O, U, Mod, UK_ModAsValue, true);
6492 checkUsage(O, U, Mod, UK_Use, false);
6493 }
6494 void notePostMod(Object O, Expr *Use, UsageKind UK) {
6495 UsageInfo &U = UsageMap[O];
6496 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
6497 addUsage(U, O, Use, UK);
6498 }
6499
6500public:
Robert Wilhelme7205c02013-08-10 12:33:24 +00006501 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
6502 : Base(S.Context), SemaRef(S), Region(Tree.root()), ModAsSideEffect(0),
6503 WorkList(WorkList), EvalTracker(0) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00006504 Visit(E);
6505 }
6506
6507 void VisitStmt(Stmt *S) {
6508 // Skip all statements which aren't expressions for now.
6509 }
6510
6511 void VisitExpr(Expr *E) {
6512 // By default, just recurse to evaluated subexpressions.
Richard Smith0c0b3902013-06-30 10:40:20 +00006513 Base::VisitStmt(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00006514 }
6515
6516 void VisitCastExpr(CastExpr *E) {
6517 Object O = Object();
6518 if (E->getCastKind() == CK_LValueToRValue)
6519 O = getObject(E->getSubExpr(), false);
6520
6521 if (O)
6522 notePreUse(O, E);
6523 VisitExpr(E);
6524 if (O)
6525 notePostUse(O, E);
6526 }
6527
6528 void VisitBinComma(BinaryOperator *BO) {
6529 // C++11 [expr.comma]p1:
6530 // Every value computation and side effect associated with the left
6531 // expression is sequenced before every value computation and side
6532 // effect associated with the right expression.
6533 SequenceTree::Seq LHS = Tree.allocate(Region);
6534 SequenceTree::Seq RHS = Tree.allocate(Region);
6535 SequenceTree::Seq OldRegion = Region;
6536
6537 {
6538 SequencedSubexpression SeqLHS(*this);
6539 Region = LHS;
6540 Visit(BO->getLHS());
6541 }
6542
6543 Region = RHS;
6544 Visit(BO->getRHS());
6545
6546 Region = OldRegion;
6547
6548 // Forget that LHS and RHS are sequenced. They are both unsequenced
6549 // with respect to other stuff.
6550 Tree.merge(LHS);
6551 Tree.merge(RHS);
6552 }
6553
6554 void VisitBinAssign(BinaryOperator *BO) {
6555 // The modification is sequenced after the value computation of the LHS
6556 // and RHS, so check it before inspecting the operands and update the
6557 // map afterwards.
6558 Object O = getObject(BO->getLHS(), true);
6559 if (!O)
6560 return VisitExpr(BO);
6561
6562 notePreMod(O, BO);
6563
6564 // C++11 [expr.ass]p7:
6565 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
6566 // only once.
6567 //
6568 // Therefore, for a compound assignment operator, O is considered used
6569 // everywhere except within the evaluation of E1 itself.
6570 if (isa<CompoundAssignOperator>(BO))
6571 notePreUse(O, BO);
6572
6573 Visit(BO->getLHS());
6574
6575 if (isa<CompoundAssignOperator>(BO))
6576 notePostUse(O, BO);
6577
6578 Visit(BO->getRHS());
6579
Richard Smith418dd3e2013-06-26 23:16:51 +00006580 // C++11 [expr.ass]p1:
6581 // the assignment is sequenced [...] before the value computation of the
6582 // assignment expression.
6583 // C11 6.5.16/3 has no such rule.
6584 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6585 : UK_ModAsSideEffect);
Richard Smith6c3af3d2013-01-17 01:17:56 +00006586 }
6587 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
6588 VisitBinAssign(CAO);
6589 }
6590
6591 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6592 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6593 void VisitUnaryPreIncDec(UnaryOperator *UO) {
6594 Object O = getObject(UO->getSubExpr(), true);
6595 if (!O)
6596 return VisitExpr(UO);
6597
6598 notePreMod(O, UO);
6599 Visit(UO->getSubExpr());
Richard Smith418dd3e2013-06-26 23:16:51 +00006600 // C++11 [expr.pre.incr]p1:
6601 // the expression ++x is equivalent to x+=1
6602 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6603 : UK_ModAsSideEffect);
Richard Smith6c3af3d2013-01-17 01:17:56 +00006604 }
6605
6606 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6607 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6608 void VisitUnaryPostIncDec(UnaryOperator *UO) {
6609 Object O = getObject(UO->getSubExpr(), true);
6610 if (!O)
6611 return VisitExpr(UO);
6612
6613 notePreMod(O, UO);
6614 Visit(UO->getSubExpr());
6615 notePostMod(O, UO, UK_ModAsSideEffect);
6616 }
6617
6618 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
6619 void VisitBinLOr(BinaryOperator *BO) {
6620 // The side-effects of the LHS of an '&&' are sequenced before the
6621 // value computation of the RHS, and hence before the value computation
6622 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
6623 // as if they were unconditionally sequenced.
Richard Smith67470052013-06-20 22:21:56 +00006624 EvaluationTracker Eval(*this);
Richard Smith6c3af3d2013-01-17 01:17:56 +00006625 {
6626 SequencedSubexpression Sequenced(*this);
6627 Visit(BO->getLHS());
6628 }
6629
6630 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00006631 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith995e4a72013-01-17 22:06:26 +00006632 if (!Result)
6633 Visit(BO->getRHS());
6634 } else {
6635 // Check for unsequenced operations in the RHS, treating it as an
6636 // entirely separate evaluation.
6637 //
6638 // FIXME: If there are operations in the RHS which are unsequenced
6639 // with respect to operations outside the RHS, and those operations
6640 // are unconditionally evaluated, diagnose them.
Richard Smith1a2dcd52013-01-17 23:18:09 +00006641 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00006642 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00006643 }
6644 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith67470052013-06-20 22:21:56 +00006645 EvaluationTracker Eval(*this);
Richard Smith6c3af3d2013-01-17 01:17:56 +00006646 {
6647 SequencedSubexpression Sequenced(*this);
6648 Visit(BO->getLHS());
6649 }
6650
6651 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00006652 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith995e4a72013-01-17 22:06:26 +00006653 if (Result)
6654 Visit(BO->getRHS());
6655 } else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00006656 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00006657 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00006658 }
6659
6660 // Only visit the condition, unless we can be sure which subexpression will
6661 // be chosen.
6662 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith67470052013-06-20 22:21:56 +00006663 EvaluationTracker Eval(*this);
Richard Smith418dd3e2013-06-26 23:16:51 +00006664 {
6665 SequencedSubexpression Sequenced(*this);
6666 Visit(CO->getCond());
6667 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00006668
6669 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00006670 if (Eval.evaluate(CO->getCond(), Result))
Richard Smith6c3af3d2013-01-17 01:17:56 +00006671 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00006672 else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00006673 WorkList.push_back(CO->getTrueExpr());
6674 WorkList.push_back(CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00006675 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00006676 }
6677
Richard Smith0c0b3902013-06-30 10:40:20 +00006678 void VisitCallExpr(CallExpr *CE) {
6679 // C++11 [intro.execution]p15:
6680 // When calling a function [...], every value computation and side effect
6681 // associated with any argument expression, or with the postfix expression
6682 // designating the called function, is sequenced before execution of every
6683 // expression or statement in the body of the function [and thus before
6684 // the value computation of its result].
6685 SequencedSubexpression Sequenced(*this);
6686 Base::VisitCallExpr(CE);
6687
6688 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
6689 }
6690
Richard Smith6c3af3d2013-01-17 01:17:56 +00006691 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smith0c0b3902013-06-30 10:40:20 +00006692 // This is a call, so all subexpressions are sequenced before the result.
6693 SequencedSubexpression Sequenced(*this);
6694
Richard Smith6c3af3d2013-01-17 01:17:56 +00006695 if (!CCE->isListInitialization())
6696 return VisitExpr(CCE);
6697
6698 // In C++11, list initializations are sequenced.
Robert Wilhelme7205c02013-08-10 12:33:24 +00006699 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smith6c3af3d2013-01-17 01:17:56 +00006700 SequenceTree::Seq Parent = Region;
6701 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
6702 E = CCE->arg_end();
6703 I != E; ++I) {
6704 Region = Tree.allocate(Parent);
6705 Elts.push_back(Region);
6706 Visit(*I);
6707 }
6708
6709 // Forget that the initializers are sequenced.
6710 Region = Parent;
6711 for (unsigned I = 0; I < Elts.size(); ++I)
6712 Tree.merge(Elts[I]);
6713 }
6714
6715 void VisitInitListExpr(InitListExpr *ILE) {
6716 if (!SemaRef.getLangOpts().CPlusPlus11)
6717 return VisitExpr(ILE);
6718
6719 // In C++11, list initializations are sequenced.
Robert Wilhelme7205c02013-08-10 12:33:24 +00006720 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smith6c3af3d2013-01-17 01:17:56 +00006721 SequenceTree::Seq Parent = Region;
6722 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
6723 Expr *E = ILE->getInit(I);
6724 if (!E) continue;
6725 Region = Tree.allocate(Parent);
6726 Elts.push_back(Region);
6727 Visit(E);
6728 }
6729
6730 // Forget that the initializers are sequenced.
6731 Region = Parent;
6732 for (unsigned I = 0; I < Elts.size(); ++I)
6733 Tree.merge(Elts[I]);
6734 }
6735};
6736}
6737
6738void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelme7205c02013-08-10 12:33:24 +00006739 SmallVector<Expr *, 8> WorkList;
Richard Smith1a2dcd52013-01-17 23:18:09 +00006740 WorkList.push_back(E);
6741 while (!WorkList.empty()) {
Robert Wilhelm344472e2013-08-23 16:11:15 +00006742 Expr *Item = WorkList.pop_back_val();
Richard Smith1a2dcd52013-01-17 23:18:09 +00006743 SequenceChecker(*this, Item, WorkList);
6744 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00006745}
6746
Fariborz Jahanianad48a502013-01-24 22:11:45 +00006747void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
6748 bool IsConstexpr) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00006749 CheckImplicitConversions(E, CheckLoc);
6750 CheckUnsequencedOperations(E);
Fariborz Jahanianad48a502013-01-24 22:11:45 +00006751 if (!IsConstexpr && !E->isValueDependent())
6752 CheckForIntOverflow(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00006753}
6754
John McCall15d7d122010-11-11 03:21:53 +00006755void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
6756 FieldDecl *BitField,
6757 Expr *Init) {
6758 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
6759}
6760
Mike Stumpf8c49212010-01-21 03:59:47 +00006761/// CheckParmsForFunctionDef - Check that the parameters of the given
6762/// function are appropriate for the definition of a function. This
6763/// takes care of any checks that cannot be performed on the
6764/// declaration itself, e.g., that the types of each of the function
6765/// parameters are complete.
Reid Kleckner8c0501c2013-06-24 14:38:26 +00006766bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
6767 ParmVarDecl *const *PEnd,
Douglas Gregor82aa7132010-11-01 18:37:59 +00006768 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00006769 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00006770 for (; P != PEnd; ++P) {
6771 ParmVarDecl *Param = *P;
6772
Mike Stumpf8c49212010-01-21 03:59:47 +00006773 // C99 6.7.5.3p4: the parameters in a parameter type list in a
6774 // function declarator that is part of a function definition of
6775 // that function shall not have incomplete type.
6776 //
6777 // This is also C++ [dcl.fct]p6.
6778 if (!Param->isInvalidDecl() &&
6779 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00006780 diag::err_typecheck_decl_incomplete_type)) {
Mike Stumpf8c49212010-01-21 03:59:47 +00006781 Param->setInvalidDecl();
6782 HasInvalidParm = true;
6783 }
6784
6785 // C99 6.9.1p5: If the declarator includes a parameter type list, the
6786 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00006787 if (CheckParameterNames &&
6788 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00006789 !Param->isImplicit() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006790 !getLangOpts().CPlusPlus)
Mike Stumpf8c49212010-01-21 03:59:47 +00006791 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00006792
6793 // C99 6.7.5.3p12:
6794 // If the function declarator is not part of a definition of that
6795 // function, parameters may have incomplete type and may use the [*]
6796 // notation in their sequences of declarator specifiers to specify
6797 // variable length array types.
6798 QualType PType = Param->getOriginalType();
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00006799 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigd17e3402010-02-01 05:02:49 +00006800 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitfc093362013-03-01 21:41:22 +00006801 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigd17e3402010-02-01 05:02:49 +00006802 // information is added for it.
6803 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00006804 break;
Sam Weinigd17e3402010-02-01 05:02:49 +00006805 }
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00006806 PType= AT->getElementType();
Sam Weinigd17e3402010-02-01 05:02:49 +00006807 }
Reid Kleckner9b601952013-06-21 12:45:15 +00006808
6809 // MSVC destroys objects passed by value in the callee. Therefore a
6810 // function definition which takes such a parameter must be able to call the
Stephen Hines651f13c2014-04-23 16:59:28 -07006811 // object's destructor. However, we don't perform any direct access check
6812 // on the dtor.
6813 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
6814 .getCXXABI()
6815 .areArgsDestroyedLeftToRightInCallee()) {
6816 if (!Param->isInvalidDecl()) {
6817 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
6818 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
6819 if (!ClassDecl->isInvalidDecl() &&
6820 !ClassDecl->hasIrrelevantDestructor() &&
6821 !ClassDecl->isDependentContext()) {
6822 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
6823 MarkFunctionReferenced(Param->getLocation(), Destructor);
6824 DiagnoseUseOfDecl(Destructor, Param->getLocation());
6825 }
6826 }
6827 }
Reid Kleckner9b601952013-06-21 12:45:15 +00006828 }
Mike Stumpf8c49212010-01-21 03:59:47 +00006829 }
6830
6831 return HasInvalidParm;
6832}
John McCallb7f4ffe2010-08-12 21:44:57 +00006833
6834/// CheckCastAlign - Implements -Wcast-align, which warns when a
6835/// pointer cast increases the alignment requirements.
6836void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
6837 // This is actually a lot of work to potentially be doing on every
6838 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00006839 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
6840 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00006841 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00006842 return;
6843
6844 // Ignore dependent types.
6845 if (T->isDependentType() || Op->getType()->isDependentType())
6846 return;
6847
6848 // Require that the destination be a pointer type.
6849 const PointerType *DestPtr = T->getAs<PointerType>();
6850 if (!DestPtr) return;
6851
6852 // If the destination has alignment 1, we're done.
6853 QualType DestPointee = DestPtr->getPointeeType();
6854 if (DestPointee->isIncompleteType()) return;
6855 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
6856 if (DestAlign.isOne()) return;
6857
6858 // Require that the source be a pointer type.
6859 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
6860 if (!SrcPtr) return;
6861 QualType SrcPointee = SrcPtr->getPointeeType();
6862
6863 // Whitelist casts from cv void*. We already implicitly
6864 // whitelisted casts to cv void*, since they have alignment 1.
6865 // Also whitelist casts involving incomplete types, which implicitly
6866 // includes 'void'.
6867 if (SrcPointee->isIncompleteType()) return;
6868
6869 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
6870 if (SrcAlign >= DestAlign) return;
6871
6872 Diag(TRange.getBegin(), diag::warn_cast_align)
6873 << Op->getType() << T
6874 << static_cast<unsigned>(SrcAlign.getQuantity())
6875 << static_cast<unsigned>(DestAlign.getQuantity())
6876 << TRange << Op->getSourceRange();
6877}
6878
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006879static const Type* getElementType(const Expr *BaseExpr) {
6880 const Type* EltType = BaseExpr->getType().getTypePtr();
6881 if (EltType->isAnyPointerType())
6882 return EltType->getPointeeType().getTypePtr();
6883 else if (EltType->isArrayType())
6884 return EltType->getBaseElementTypeUnsafe();
6885 return EltType;
6886}
6887
Chandler Carruthc2684342011-08-05 09:10:50 +00006888/// \brief Check whether this array fits the idiom of a size-one tail padded
6889/// array member of a struct.
6890///
6891/// We avoid emitting out-of-bounds access warnings for such arrays as they are
6892/// commonly used to emulate flexible arrays in C89 code.
6893static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
6894 const NamedDecl *ND) {
6895 if (Size != 1 || !ND) return false;
6896
6897 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
6898 if (!FD) return false;
6899
6900 // Don't consider sizes resulting from macro expansions or template argument
6901 // substitution to form C89 tail-padded arrays.
Sean Callanand2cf3482012-05-04 18:22:53 +00006902
6903 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00006904 while (TInfo) {
6905 TypeLoc TL = TInfo->getTypeLoc();
6906 // Look through typedefs.
David Blaikie39e6ab42013-02-18 22:06:02 +00006907 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
6908 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00006909 TInfo = TDL->getTypeSourceInfo();
6910 continue;
6911 }
David Blaikie39e6ab42013-02-18 22:06:02 +00006912 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
6913 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier5e253012013-02-06 00:58:34 +00006914 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
6915 return false;
6916 }
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00006917 break;
Sean Callanand2cf3482012-05-04 18:22:53 +00006918 }
Chandler Carruthc2684342011-08-05 09:10:50 +00006919
6920 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00006921 if (!RD) return false;
6922 if (RD->isUnion()) return false;
6923 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
6924 if (!CRD->isStandardLayout()) return false;
6925 }
Chandler Carruthc2684342011-08-05 09:10:50 +00006926
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00006927 // See if this is the last field decl in the record.
6928 const Decl *D = FD;
6929 while ((D = D->getNextDeclInContext()))
6930 if (isa<FieldDecl>(D))
6931 return false;
6932 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00006933}
6934
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006935void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006936 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00006937 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman92b670e2012-02-27 21:21:40 +00006938 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006939 if (IndexExpr->isValueDependent())
6940 return;
6941
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00006942 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006943 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00006944 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006945 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00006946 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00006947 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00006948
Chandler Carruth34064582011-02-17 20:55:08 +00006949 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006950 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00006951 return;
Richard Smith25b009a2011-12-16 19:31:14 +00006952 if (IndexNegated)
6953 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00006954
Chandler Carruthba447122011-08-05 08:07:29 +00006955 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00006956 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6957 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00006958 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00006959 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00006960
Ted Kremenek9e060ca2011-02-23 23:06:04 +00006961 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00006962 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00006963 if (!size.isStrictlyPositive())
6964 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006965
6966 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00006967 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006968 // Make sure we're comparing apples to apples when comparing index to size
6969 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
6970 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00006971 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00006972 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006973 if (ptrarith_typesize != array_typesize) {
6974 // There's a cast to a different size type involved
6975 uint64_t ratio = array_typesize / ptrarith_typesize;
6976 // TODO: Be smarter about handling cases where array_typesize is not a
6977 // multiple of ptrarith_typesize
6978 if (ptrarith_typesize * ratio == array_typesize)
6979 size *= llvm::APInt(size.getBitWidth(), ratio);
6980 }
6981 }
6982
Chandler Carruth34064582011-02-17 20:55:08 +00006983 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00006984 index = index.zext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00006985 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00006986 size = size.zext(index.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00006987
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006988 // For array subscripting the index must be less than size, but for pointer
6989 // arithmetic also allow the index (offset) to be equal to size since
6990 // computing the next address after the end of the array is legal and
6991 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman92b670e2012-02-27 21:21:40 +00006992 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruthba447122011-08-05 08:07:29 +00006993 return;
6994
6995 // Also don't warn for arrays of size 1 which are members of some
6996 // structure. These are often used to approximate flexible arrays in C89
6997 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006998 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00006999 return;
Chandler Carruth34064582011-02-17 20:55:08 +00007000
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00007001 // Suppress the warning if the subscript expression (as identified by the
7002 // ']' location) and the index expression are both from macro expansions
7003 // within a system header.
7004 if (ASE) {
7005 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
7006 ASE->getRBracketLoc());
7007 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
7008 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
7009 IndexExpr->getLocStart());
Eli Friedman24146972013-08-22 00:27:10 +00007010 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00007011 return;
7012 }
7013 }
7014
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007015 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00007016 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007017 DiagID = diag::warn_array_index_exceeds_bounds;
7018
7019 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7020 PDiag(DiagID) << index.toString(10, true)
7021 << size.toString(10, true)
7022 << (unsigned)size.getLimitedValue(~0U)
7023 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00007024 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007025 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00007026 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007027 DiagID = diag::warn_ptr_arith_precedes_bounds;
7028 if (index.isNegative()) index = -index;
7029 }
7030
7031 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7032 PDiag(DiagID) << index.toString(10, true)
7033 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00007034 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00007035
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00007036 if (!ND) {
7037 // Try harder to find a NamedDecl to point at in the note.
7038 while (const ArraySubscriptExpr *ASE =
7039 dyn_cast<ArraySubscriptExpr>(BaseExpr))
7040 BaseExpr = ASE->getBase()->IgnoreParenCasts();
7041 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7042 ND = dyn_cast<NamedDecl>(DRE->getDecl());
7043 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7044 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7045 }
7046
Chandler Carruth35001ca2011-02-17 21:10:52 +00007047 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007048 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
7049 PDiag(diag::note_array_index_out_of_bounds)
7050 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00007051}
7052
Ted Kremenek3aea4da2011-03-01 18:41:00 +00007053void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007054 int AllowOnePastEnd = 0;
7055 while (expr) {
7056 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00007057 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007058 case Stmt::ArraySubscriptExprClass: {
7059 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00007060 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007061 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00007062 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007063 }
7064 case Stmt::UnaryOperatorClass: {
7065 // Only unwrap the * and & unary operators
7066 const UnaryOperator *UO = cast<UnaryOperator>(expr);
7067 expr = UO->getSubExpr();
7068 switch (UO->getOpcode()) {
7069 case UO_AddrOf:
7070 AllowOnePastEnd++;
7071 break;
7072 case UO_Deref:
7073 AllowOnePastEnd--;
7074 break;
7075 default:
7076 return;
7077 }
7078 break;
7079 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00007080 case Stmt::ConditionalOperatorClass: {
7081 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
7082 if (const Expr *lhs = cond->getLHS())
7083 CheckArrayAccess(lhs);
7084 if (const Expr *rhs = cond->getRHS())
7085 CheckArrayAccess(rhs);
7086 return;
7087 }
7088 default:
7089 return;
7090 }
Peter Collingbournef111d932011-04-15 00:35:48 +00007091 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00007092}
John McCallf85e1932011-06-15 23:02:42 +00007093
7094//===--- CHECK: Objective-C retain cycles ----------------------------------//
7095
7096namespace {
7097 struct RetainCycleOwner {
7098 RetainCycleOwner() : Variable(0), Indirect(false) {}
7099 VarDecl *Variable;
7100 SourceRange Range;
7101 SourceLocation Loc;
7102 bool Indirect;
7103
7104 void setLocsFrom(Expr *e) {
7105 Loc = e->getExprLoc();
7106 Range = e->getSourceRange();
7107 }
7108 };
7109}
7110
7111/// Consider whether capturing the given variable can possibly lead to
7112/// a retain cycle.
7113static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00007114 // In ARC, it's captured strongly iff the variable has __strong
John McCallf85e1932011-06-15 23:02:42 +00007115 // lifetime. In MRR, it's captured strongly if the variable is
7116 // __block and has an appropriate type.
7117 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7118 return false;
7119
7120 owner.Variable = var;
Jordan Rosee10f4d32012-09-15 02:48:31 +00007121 if (ref)
7122 owner.setLocsFrom(ref);
John McCallf85e1932011-06-15 23:02:42 +00007123 return true;
7124}
7125
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00007126static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00007127 while (true) {
7128 e = e->IgnoreParens();
7129 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
7130 switch (cast->getCastKind()) {
7131 case CK_BitCast:
7132 case CK_LValueBitCast:
7133 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00007134 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00007135 e = cast->getSubExpr();
7136 continue;
7137
John McCallf85e1932011-06-15 23:02:42 +00007138 default:
7139 return false;
7140 }
7141 }
7142
7143 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
7144 ObjCIvarDecl *ivar = ref->getDecl();
7145 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7146 return false;
7147
7148 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00007149 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00007150 return false;
7151
7152 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
7153 owner.Indirect = true;
7154 return true;
7155 }
7156
7157 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
7158 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
7159 if (!var) return false;
7160 return considerVariable(var, ref, owner);
7161 }
7162
John McCallf85e1932011-06-15 23:02:42 +00007163 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
7164 if (member->isArrow()) return false;
7165
7166 // Don't count this as an indirect ownership.
7167 e = member->getBase();
7168 continue;
7169 }
7170
John McCall4b9c2d22011-11-06 09:01:30 +00007171 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
7172 // Only pay attention to pseudo-objects on property references.
7173 ObjCPropertyRefExpr *pre
7174 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
7175 ->IgnoreParens());
7176 if (!pre) return false;
7177 if (pre->isImplicitProperty()) return false;
7178 ObjCPropertyDecl *property = pre->getExplicitProperty();
7179 if (!property->isRetaining() &&
7180 !(property->getPropertyIvarDecl() &&
7181 property->getPropertyIvarDecl()->getType()
7182 .getObjCLifetime() == Qualifiers::OCL_Strong))
7183 return false;
7184
7185 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00007186 if (pre->isSuperReceiver()) {
7187 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
7188 if (!owner.Variable)
7189 return false;
7190 owner.Loc = pre->getLocation();
7191 owner.Range = pre->getSourceRange();
7192 return true;
7193 }
John McCall4b9c2d22011-11-06 09:01:30 +00007194 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
7195 ->getSourceExpr());
7196 continue;
7197 }
7198
John McCallf85e1932011-06-15 23:02:42 +00007199 // Array ivars?
7200
7201 return false;
7202 }
7203}
7204
7205namespace {
7206 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
7207 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
7208 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
7209 Variable(variable), Capturer(0) {}
7210
7211 VarDecl *Variable;
7212 Expr *Capturer;
7213
7214 void VisitDeclRefExpr(DeclRefExpr *ref) {
7215 if (ref->getDecl() == Variable && !Capturer)
7216 Capturer = ref;
7217 }
7218
John McCallf85e1932011-06-15 23:02:42 +00007219 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
7220 if (Capturer) return;
7221 Visit(ref->getBase());
7222 if (Capturer && ref->isFreeIvar())
7223 Capturer = ref;
7224 }
7225
7226 void VisitBlockExpr(BlockExpr *block) {
7227 // Look inside nested blocks
7228 if (block->getBlockDecl()->capturesVariable(Variable))
7229 Visit(block->getBlockDecl()->getBody());
7230 }
Fariborz Jahanian7e2e4c32012-08-31 20:04:47 +00007231
7232 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
7233 if (Capturer) return;
7234 if (OVE->getSourceExpr())
7235 Visit(OVE->getSourceExpr());
7236 }
John McCallf85e1932011-06-15 23:02:42 +00007237 };
7238}
7239
7240/// Check whether the given argument is a block which captures a
7241/// variable.
7242static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
7243 assert(owner.Variable && owner.Loc.isValid());
7244
7245 e = e->IgnoreParenCasts();
Jordan Rose1fac58a2012-09-17 17:54:30 +00007246
7247 // Look through [^{...} copy] and Block_copy(^{...}).
7248 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
7249 Selector Cmd = ME->getSelector();
7250 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
7251 e = ME->getInstanceReceiver();
7252 if (!e)
7253 return 0;
7254 e = e->IgnoreParenCasts();
7255 }
7256 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
7257 if (CE->getNumArgs() == 1) {
7258 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekd13eff62012-10-02 04:36:54 +00007259 if (Fn) {
7260 const IdentifierInfo *FnI = Fn->getIdentifier();
7261 if (FnI && FnI->isStr("_Block_copy")) {
7262 e = CE->getArg(0)->IgnoreParenCasts();
7263 }
7264 }
Jordan Rose1fac58a2012-09-17 17:54:30 +00007265 }
7266 }
7267
John McCallf85e1932011-06-15 23:02:42 +00007268 BlockExpr *block = dyn_cast<BlockExpr>(e);
7269 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
7270 return 0;
7271
7272 FindCaptureVisitor visitor(S.Context, owner.Variable);
7273 visitor.Visit(block->getBlockDecl()->getBody());
7274 return visitor.Capturer;
7275}
7276
7277static void diagnoseRetainCycle(Sema &S, Expr *capturer,
7278 RetainCycleOwner &owner) {
7279 assert(capturer);
7280 assert(owner.Variable && owner.Loc.isValid());
7281
7282 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
7283 << owner.Variable << capturer->getSourceRange();
7284 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
7285 << owner.Indirect << owner.Range;
7286}
7287
7288/// Check for a keyword selector that starts with the word 'add' or
7289/// 'set'.
7290static bool isSetterLikeSelector(Selector sel) {
7291 if (sel.isUnarySelector()) return false;
7292
Chris Lattner5f9e2722011-07-23 10:55:15 +00007293 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00007294 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00007295 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00007296 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00007297 else if (str.startswith("add")) {
7298 // Specially whitelist 'addOperationWithBlock:'.
7299 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
7300 return false;
7301 str = str.substr(3);
7302 }
John McCallf85e1932011-06-15 23:02:42 +00007303 else
7304 return false;
7305
7306 if (str.empty()) return true;
Jordan Rose3f6f51e2013-02-08 22:30:41 +00007307 return !isLowercase(str.front());
John McCallf85e1932011-06-15 23:02:42 +00007308}
7309
7310/// Check a message send to see if it's likely to cause a retain cycle.
7311void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
7312 // Only check instance methods whose selector looks like a setter.
7313 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
7314 return;
7315
7316 // Try to find a variable that the receiver is strongly owned by.
7317 RetainCycleOwner owner;
7318 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00007319 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00007320 return;
7321 } else {
7322 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
7323 owner.Variable = getCurMethodDecl()->getSelfDecl();
7324 owner.Loc = msg->getSuperLoc();
7325 owner.Range = msg->getSuperLoc();
7326 }
7327
7328 // Check whether the receiver is captured by any of the arguments.
7329 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
7330 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
7331 return diagnoseRetainCycle(*this, capturer, owner);
7332}
7333
7334/// Check a property assign to see if it's likely to cause a retain cycle.
7335void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
7336 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00007337 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00007338 return;
7339
7340 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
7341 diagnoseRetainCycle(*this, capturer, owner);
7342}
7343
Jordan Rosee10f4d32012-09-15 02:48:31 +00007344void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
7345 RetainCycleOwner Owner;
7346 if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
7347 return;
7348
7349 // Because we don't have an expression for the variable, we have to set the
7350 // location explicitly here.
7351 Owner.Loc = Var->getLocation();
7352 Owner.Range = Var->getSourceRange();
7353
7354 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
7355 diagnoseRetainCycle(*this, Capturer, Owner);
7356}
7357
Ted Kremenek9d084012012-12-21 08:04:28 +00007358static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
7359 Expr *RHS, bool isProperty) {
7360 // Check if RHS is an Objective-C object literal, which also can get
7361 // immediately zapped in a weak reference. Note that we explicitly
7362 // allow ObjCStringLiterals, since those are designed to never really die.
7363 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenekf530ff72012-12-21 21:59:39 +00007364
Ted Kremenekd3292c82012-12-21 22:46:35 +00007365 // This enum needs to match with the 'select' in
7366 // warn_objc_arc_literal_assign (off-by-1).
7367 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
7368 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
7369 return false;
Ted Kremenekf530ff72012-12-21 21:59:39 +00007370
7371 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenekd3292c82012-12-21 22:46:35 +00007372 << (unsigned) Kind
Ted Kremenek9d084012012-12-21 08:04:28 +00007373 << (isProperty ? 0 : 1)
7374 << RHS->getSourceRange();
Ted Kremenekf530ff72012-12-21 21:59:39 +00007375
7376 return true;
Ted Kremenek9d084012012-12-21 08:04:28 +00007377}
7378
Ted Kremenekb29b30f2012-12-21 19:45:30 +00007379static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
7380 Qualifiers::ObjCLifetime LT,
7381 Expr *RHS, bool isProperty) {
7382 // Strip off any implicit cast added to get to the one ARC-specific.
7383 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
7384 if (cast->getCastKind() == CK_ARCConsumeObject) {
7385 S.Diag(Loc, diag::warn_arc_retained_assign)
7386 << (LT == Qualifiers::OCL_ExplicitNone)
7387 << (isProperty ? 0 : 1)
7388 << RHS->getSourceRange();
7389 return true;
7390 }
7391 RHS = cast->getSubExpr();
7392 }
7393
7394 if (LT == Qualifiers::OCL_Weak &&
7395 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
7396 return true;
7397
7398 return false;
7399}
7400
Ted Kremenekb1ea5102012-12-21 08:04:20 +00007401bool Sema::checkUnsafeAssigns(SourceLocation Loc,
7402 QualType LHS, Expr *RHS) {
7403 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
7404
7405 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
7406 return false;
7407
7408 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
7409 return true;
7410
7411 return false;
7412}
7413
Fariborz Jahanian921c1432011-06-24 18:25:34 +00007414void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
7415 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00007416 QualType LHSType;
7417 // PropertyRef on LHS type need be directly obtained from
Stephen Hines651f13c2014-04-23 16:59:28 -07007418 // its declaration as it has a PseudoType.
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00007419 ObjCPropertyRefExpr *PRE
7420 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
7421 if (PRE && !PRE->isImplicitProperty()) {
7422 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7423 if (PD)
7424 LHSType = PD->getType();
7425 }
7426
7427 if (LHSType.isNull())
7428 LHSType = LHS->getType();
Jordan Rose7a270482012-09-28 22:21:35 +00007429
7430 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
7431
7432 if (LT == Qualifiers::OCL_Weak) {
7433 DiagnosticsEngine::Level Level =
7434 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
7435 if (Level != DiagnosticsEngine::Ignored)
7436 getCurFunction()->markSafeWeakUse(LHS);
7437 }
7438
Fariborz Jahanian921c1432011-06-24 18:25:34 +00007439 if (checkUnsafeAssigns(Loc, LHSType, RHS))
7440 return;
Jordan Rose7a270482012-09-28 22:21:35 +00007441
Fariborz Jahanian921c1432011-06-24 18:25:34 +00007442 // FIXME. Check for other life times.
7443 if (LT != Qualifiers::OCL_None)
7444 return;
7445
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00007446 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00007447 if (PRE->isImplicitProperty())
7448 return;
7449 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7450 if (!PD)
7451 return;
7452
Bill Wendlingad017fa2012-12-20 19:22:21 +00007453 unsigned Attributes = PD->getPropertyAttributes();
7454 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00007455 // when 'assign' attribute was not explicitly specified
7456 // by user, ignore it and rely on property type itself
7457 // for lifetime info.
7458 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
7459 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
7460 LHSType->isObjCRetainableType())
7461 return;
7462
Fariborz Jahanian921c1432011-06-24 18:25:34 +00007463 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00007464 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00007465 Diag(Loc, diag::warn_arc_retained_property_assign)
7466 << RHS->getSourceRange();
7467 return;
7468 }
7469 RHS = cast->getSubExpr();
7470 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00007471 }
Bill Wendlingad017fa2012-12-20 19:22:21 +00007472 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb1ea5102012-12-21 08:04:20 +00007473 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
7474 return;
Fariborz Jahanianbd2e27e2012-07-06 21:09:27 +00007475 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00007476 }
7477}
Dmitri Gribenko625bb562012-02-14 22:14:32 +00007478
7479//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
7480
7481namespace {
7482bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
7483 SourceLocation StmtLoc,
7484 const NullStmt *Body) {
7485 // Do not warn if the body is a macro that expands to nothing, e.g:
7486 //
7487 // #define CALL(x)
7488 // if (condition)
7489 // CALL(0);
7490 //
7491 if (Body->hasLeadingEmptyMacro())
7492 return false;
7493
7494 // Get line numbers of statement and body.
7495 bool StmtLineInvalid;
7496 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
7497 &StmtLineInvalid);
7498 if (StmtLineInvalid)
7499 return false;
7500
7501 bool BodyLineInvalid;
7502 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
7503 &BodyLineInvalid);
7504 if (BodyLineInvalid)
7505 return false;
7506
7507 // Warn if null statement and body are on the same line.
7508 if (StmtLine != BodyLine)
7509 return false;
7510
7511 return true;
7512}
7513} // Unnamed namespace
7514
7515void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
7516 const Stmt *Body,
7517 unsigned DiagID) {
7518 // Since this is a syntactic check, don't emit diagnostic for template
7519 // instantiations, this just adds noise.
7520 if (CurrentInstantiationScope)
7521 return;
7522
7523 // The body should be a null statement.
7524 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7525 if (!NBody)
7526 return;
7527
7528 // Do the usual checks.
7529 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7530 return;
7531
7532 Diag(NBody->getSemiLoc(), DiagID);
7533 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7534}
7535
7536void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
7537 const Stmt *PossibleBody) {
7538 assert(!CurrentInstantiationScope); // Ensured by caller
7539
7540 SourceLocation StmtLoc;
7541 const Stmt *Body;
7542 unsigned DiagID;
7543 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
7544 StmtLoc = FS->getRParenLoc();
7545 Body = FS->getBody();
7546 DiagID = diag::warn_empty_for_body;
7547 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
7548 StmtLoc = WS->getCond()->getSourceRange().getEnd();
7549 Body = WS->getBody();
7550 DiagID = diag::warn_empty_while_body;
7551 } else
7552 return; // Neither `for' nor `while'.
7553
7554 // The body should be a null statement.
7555 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7556 if (!NBody)
7557 return;
7558
7559 // Skip expensive checks if diagnostic is disabled.
7560 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
7561 DiagnosticsEngine::Ignored)
7562 return;
7563
7564 // Do the usual checks.
7565 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7566 return;
7567
7568 // `for(...);' and `while(...);' are popular idioms, so in order to keep
7569 // noise level low, emit diagnostics only if for/while is followed by a
7570 // CompoundStmt, e.g.:
7571 // for (int i = 0; i < n; i++);
7572 // {
7573 // a(i);
7574 // }
7575 // or if for/while is followed by a statement with more indentation
7576 // than for/while itself:
7577 // for (int i = 0; i < n; i++);
7578 // a(i);
7579 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
7580 if (!ProbableTypo) {
7581 bool BodyColInvalid;
7582 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
7583 PossibleBody->getLocStart(),
7584 &BodyColInvalid);
7585 if (BodyColInvalid)
7586 return;
7587
7588 bool StmtColInvalid;
7589 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
7590 S->getLocStart(),
7591 &StmtColInvalid);
7592 if (StmtColInvalid)
7593 return;
7594
7595 if (BodyCol > StmtCol)
7596 ProbableTypo = true;
7597 }
7598
7599 if (ProbableTypo) {
7600 Diag(NBody->getSemiLoc(), DiagID);
7601 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7602 }
7603}
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00007604
7605//===--- Layout compatibility ----------------------------------------------//
7606
7607namespace {
7608
7609bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
7610
7611/// \brief Check if two enumeration types are layout-compatible.
7612bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
7613 // C++11 [dcl.enum] p8:
7614 // Two enumeration types are layout-compatible if they have the same
7615 // underlying type.
7616 return ED1->isComplete() && ED2->isComplete() &&
7617 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
7618}
7619
7620/// \brief Check if two fields are layout-compatible.
7621bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
7622 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
7623 return false;
7624
7625 if (Field1->isBitField() != Field2->isBitField())
7626 return false;
7627
7628 if (Field1->isBitField()) {
7629 // Make sure that the bit-fields are the same length.
7630 unsigned Bits1 = Field1->getBitWidthValue(C);
7631 unsigned Bits2 = Field2->getBitWidthValue(C);
7632
7633 if (Bits1 != Bits2)
7634 return false;
7635 }
7636
7637 return true;
7638}
7639
7640/// \brief Check if two standard-layout structs are layout-compatible.
7641/// (C++11 [class.mem] p17)
7642bool isLayoutCompatibleStruct(ASTContext &C,
7643 RecordDecl *RD1,
7644 RecordDecl *RD2) {
7645 // If both records are C++ classes, check that base classes match.
7646 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
7647 // If one of records is a CXXRecordDecl we are in C++ mode,
7648 // thus the other one is a CXXRecordDecl, too.
7649 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
7650 // Check number of base classes.
7651 if (D1CXX->getNumBases() != D2CXX->getNumBases())
7652 return false;
7653
7654 // Check the base classes.
7655 for (CXXRecordDecl::base_class_const_iterator
7656 Base1 = D1CXX->bases_begin(),
7657 BaseEnd1 = D1CXX->bases_end(),
7658 Base2 = D2CXX->bases_begin();
7659 Base1 != BaseEnd1;
7660 ++Base1, ++Base2) {
7661 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
7662 return false;
7663 }
7664 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
7665 // If only RD2 is a C++ class, it should have zero base classes.
7666 if (D2CXX->getNumBases() > 0)
7667 return false;
7668 }
7669
7670 // Check the fields.
7671 RecordDecl::field_iterator Field2 = RD2->field_begin(),
7672 Field2End = RD2->field_end(),
7673 Field1 = RD1->field_begin(),
7674 Field1End = RD1->field_end();
7675 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
7676 if (!isLayoutCompatible(C, *Field1, *Field2))
7677 return false;
7678 }
7679 if (Field1 != Field1End || Field2 != Field2End)
7680 return false;
7681
7682 return true;
7683}
7684
7685/// \brief Check if two standard-layout unions are layout-compatible.
7686/// (C++11 [class.mem] p18)
7687bool isLayoutCompatibleUnion(ASTContext &C,
7688 RecordDecl *RD1,
7689 RecordDecl *RD2) {
7690 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Stephen Hines651f13c2014-04-23 16:59:28 -07007691 for (auto *Field2 : RD2->fields())
7692 UnmatchedFields.insert(Field2);
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00007693
Stephen Hines651f13c2014-04-23 16:59:28 -07007694 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00007695 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
7696 I = UnmatchedFields.begin(),
7697 E = UnmatchedFields.end();
7698
7699 for ( ; I != E; ++I) {
Stephen Hines651f13c2014-04-23 16:59:28 -07007700 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00007701 bool Result = UnmatchedFields.erase(*I);
7702 (void) Result;
7703 assert(Result);
7704 break;
7705 }
7706 }
7707 if (I == E)
7708 return false;
7709 }
7710
7711 return UnmatchedFields.empty();
7712}
7713
7714bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
7715 if (RD1->isUnion() != RD2->isUnion())
7716 return false;
7717
7718 if (RD1->isUnion())
7719 return isLayoutCompatibleUnion(C, RD1, RD2);
7720 else
7721 return isLayoutCompatibleStruct(C, RD1, RD2);
7722}
7723
7724/// \brief Check if two types are layout-compatible in C++11 sense.
7725bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
7726 if (T1.isNull() || T2.isNull())
7727 return false;
7728
7729 // C++11 [basic.types] p11:
7730 // If two types T1 and T2 are the same type, then T1 and T2 are
7731 // layout-compatible types.
7732 if (C.hasSameType(T1, T2))
7733 return true;
7734
7735 T1 = T1.getCanonicalType().getUnqualifiedType();
7736 T2 = T2.getCanonicalType().getUnqualifiedType();
7737
7738 const Type::TypeClass TC1 = T1->getTypeClass();
7739 const Type::TypeClass TC2 = T2->getTypeClass();
7740
7741 if (TC1 != TC2)
7742 return false;
7743
7744 if (TC1 == Type::Enum) {
7745 return isLayoutCompatible(C,
7746 cast<EnumType>(T1)->getDecl(),
7747 cast<EnumType>(T2)->getDecl());
7748 } else if (TC1 == Type::Record) {
7749 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
7750 return false;
7751
7752 return isLayoutCompatible(C,
7753 cast<RecordType>(T1)->getDecl(),
7754 cast<RecordType>(T2)->getDecl());
7755 }
7756
7757 return false;
7758}
7759}
7760
7761//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
7762
7763namespace {
7764/// \brief Given a type tag expression find the type tag itself.
7765///
7766/// \param TypeExpr Type tag expression, as it appears in user's code.
7767///
7768/// \param VD Declaration of an identifier that appears in a type tag.
7769///
7770/// \param MagicValue Type tag magic value.
7771bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
7772 const ValueDecl **VD, uint64_t *MagicValue) {
7773 while(true) {
7774 if (!TypeExpr)
7775 return false;
7776
7777 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
7778
7779 switch (TypeExpr->getStmtClass()) {
7780 case Stmt::UnaryOperatorClass: {
7781 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
7782 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
7783 TypeExpr = UO->getSubExpr();
7784 continue;
7785 }
7786 return false;
7787 }
7788
7789 case Stmt::DeclRefExprClass: {
7790 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
7791 *VD = DRE->getDecl();
7792 return true;
7793 }
7794
7795 case Stmt::IntegerLiteralClass: {
7796 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
7797 llvm::APInt MagicValueAPInt = IL->getValue();
7798 if (MagicValueAPInt.getActiveBits() <= 64) {
7799 *MagicValue = MagicValueAPInt.getZExtValue();
7800 return true;
7801 } else
7802 return false;
7803 }
7804
7805 case Stmt::BinaryConditionalOperatorClass:
7806 case Stmt::ConditionalOperatorClass: {
7807 const AbstractConditionalOperator *ACO =
7808 cast<AbstractConditionalOperator>(TypeExpr);
7809 bool Result;
7810 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
7811 if (Result)
7812 TypeExpr = ACO->getTrueExpr();
7813 else
7814 TypeExpr = ACO->getFalseExpr();
7815 continue;
7816 }
7817 return false;
7818 }
7819
7820 case Stmt::BinaryOperatorClass: {
7821 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
7822 if (BO->getOpcode() == BO_Comma) {
7823 TypeExpr = BO->getRHS();
7824 continue;
7825 }
7826 return false;
7827 }
7828
7829 default:
7830 return false;
7831 }
7832 }
7833}
7834
7835/// \brief Retrieve the C type corresponding to type tag TypeExpr.
7836///
7837/// \param TypeExpr Expression that specifies a type tag.
7838///
7839/// \param MagicValues Registered magic values.
7840///
7841/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
7842/// kind.
7843///
7844/// \param TypeInfo Information about the corresponding C type.
7845///
7846/// \returns true if the corresponding C type was found.
7847bool GetMatchingCType(
7848 const IdentifierInfo *ArgumentKind,
7849 const Expr *TypeExpr, const ASTContext &Ctx,
7850 const llvm::DenseMap<Sema::TypeTagMagicValue,
7851 Sema::TypeTagData> *MagicValues,
7852 bool &FoundWrongKind,
7853 Sema::TypeTagData &TypeInfo) {
7854 FoundWrongKind = false;
7855
7856 // Variable declaration that has type_tag_for_datatype attribute.
7857 const ValueDecl *VD = NULL;
7858
7859 uint64_t MagicValue;
7860
7861 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
7862 return false;
7863
7864 if (VD) {
Stephen Hines651f13c2014-04-23 16:59:28 -07007865 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00007866 if (I->getArgumentKind() != ArgumentKind) {
7867 FoundWrongKind = true;
7868 return false;
7869 }
7870 TypeInfo.Type = I->getMatchingCType();
7871 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
7872 TypeInfo.MustBeNull = I->getMustBeNull();
7873 return true;
7874 }
7875 return false;
7876 }
7877
7878 if (!MagicValues)
7879 return false;
7880
7881 llvm::DenseMap<Sema::TypeTagMagicValue,
7882 Sema::TypeTagData>::const_iterator I =
7883 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
7884 if (I == MagicValues->end())
7885 return false;
7886
7887 TypeInfo = I->second;
7888 return true;
7889}
7890} // unnamed namespace
7891
7892void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
7893 uint64_t MagicValue, QualType Type,
7894 bool LayoutCompatible,
7895 bool MustBeNull) {
7896 if (!TypeTagForDatatypeMagicValues)
7897 TypeTagForDatatypeMagicValues.reset(
7898 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
7899
7900 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
7901 (*TypeTagForDatatypeMagicValues)[Magic] =
7902 TypeTagData(Type, LayoutCompatible, MustBeNull);
7903}
7904
7905namespace {
7906bool IsSameCharType(QualType T1, QualType T2) {
7907 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
7908 if (!BT1)
7909 return false;
7910
7911 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
7912 if (!BT2)
7913 return false;
7914
7915 BuiltinType::Kind T1Kind = BT1->getKind();
7916 BuiltinType::Kind T2Kind = BT2->getKind();
7917
7918 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
7919 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
7920 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
7921 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
7922}
7923} // unnamed namespace
7924
7925void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
7926 const Expr * const *ExprArgs) {
7927 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
7928 bool IsPointerAttr = Attr->getIsPointer();
7929
7930 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
7931 bool FoundWrongKind;
7932 TypeTagData TypeInfo;
7933 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
7934 TypeTagForDatatypeMagicValues.get(),
7935 FoundWrongKind, TypeInfo)) {
7936 if (FoundWrongKind)
7937 Diag(TypeTagExpr->getExprLoc(),
7938 diag::warn_type_tag_for_datatype_wrong_kind)
7939 << TypeTagExpr->getSourceRange();
7940 return;
7941 }
7942
7943 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
7944 if (IsPointerAttr) {
7945 // Skip implicit cast of pointer to `void *' (as a function argument).
7946 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5a249802012-11-03 16:07:49 +00007947 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkob57ce4e2012-11-03 22:10:18 +00007948 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00007949 ArgumentExpr = ICE->getSubExpr();
7950 }
7951 QualType ArgumentType = ArgumentExpr->getType();
7952
7953 // Passing a `void*' pointer shouldn't trigger a warning.
7954 if (IsPointerAttr && ArgumentType->isVoidPointerType())
7955 return;
7956
7957 if (TypeInfo.MustBeNull) {
7958 // Type tag with matching void type requires a null pointer.
7959 if (!ArgumentExpr->isNullPointerConstant(Context,
7960 Expr::NPC_ValueDependentIsNotNull)) {
7961 Diag(ArgumentExpr->getExprLoc(),
7962 diag::warn_type_safety_null_pointer_required)
7963 << ArgumentKind->getName()
7964 << ArgumentExpr->getSourceRange()
7965 << TypeTagExpr->getSourceRange();
7966 }
7967 return;
7968 }
7969
7970 QualType RequiredType = TypeInfo.Type;
7971 if (IsPointerAttr)
7972 RequiredType = Context.getPointerType(RequiredType);
7973
7974 bool mismatch = false;
7975 if (!TypeInfo.LayoutCompatible) {
7976 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
7977
7978 // C++11 [basic.fundamental] p1:
7979 // Plain char, signed char, and unsigned char are three distinct types.
7980 //
7981 // But we treat plain `char' as equivalent to `signed char' or `unsigned
7982 // char' depending on the current char signedness mode.
7983 if (mismatch)
7984 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
7985 RequiredType->getPointeeType())) ||
7986 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
7987 mismatch = false;
7988 } else
7989 if (IsPointerAttr)
7990 mismatch = !isLayoutCompatible(Context,
7991 ArgumentType->getPointeeType(),
7992 RequiredType->getPointeeType());
7993 else
7994 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
7995
7996 if (mismatch)
7997 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Stephen Hines651f13c2014-04-23 16:59:28 -07007998 << ArgumentType << ArgumentKind
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00007999 << TypeInfo.LayoutCompatible << RequiredType
8000 << ArgumentExpr->getSourceRange()
8001 << TypeTagExpr->getSourceRange();
8002}
Stephen Hines651f13c2014-04-23 16:59:28 -07008003