blob: 83fb1d78337d3061c34a85efb9c214477db83e48 [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"
Stephen Hines6bcf27b2014-05-29 04:14:42 -070030#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth55fc8732012-12-04 09:13:33 +000031#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 {
Stephen Hines6bcf27b2014-05-29 04:14:42 -070046 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
47 Context.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:
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700179 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000180 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;
Tim Northoverb793f0d2013-08-01 09:23:19 +0000312 case llvm::Triple::aarch64:
Stephen Hines651f13c2014-04-23 16:59:28 -0700313 case llvm::Triple::aarch64_be:
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700314 case llvm::Triple::arm64:
315 case llvm::Triple::arm64_be:
Tim Northoverb793f0d2013-08-01 09:23:19 +0000316 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
317 return ExprError();
318 break;
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000319 case llvm::Triple::mips:
320 case llvm::Triple::mipsel:
321 case llvm::Triple::mips64:
322 case llvm::Triple::mips64el:
323 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
324 return ExprError();
325 break;
Stephen Hines651f13c2014-04-23 16:59:28 -0700326 case llvm::Triple::x86:
327 case llvm::Triple::x86_64:
328 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
329 return ExprError();
330 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000331 default:
332 break;
333 }
334 }
335
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000336 return TheCallResult;
Nate Begeman26a31422010-06-08 02:47:44 +0000337}
338
Nate Begeman61eecf52010-06-14 05:21:25 +0000339// Get the valid immediate range for the specified NEON type code.
Stephen Hines651f13c2014-04-23 16:59:28 -0700340static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilsonda95f732011-11-08 01:16:11 +0000341 NeonTypeFlags Type(t);
Stephen Hines651f13c2014-04-23 16:59:28 -0700342 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilsonda95f732011-11-08 01:16:11 +0000343 switch (Type.getEltType()) {
344 case NeonTypeFlags::Int8:
345 case NeonTypeFlags::Poly8:
346 return shift ? 7 : (8 << IsQuad) - 1;
347 case NeonTypeFlags::Int16:
348 case NeonTypeFlags::Poly16:
349 return shift ? 15 : (4 << IsQuad) - 1;
350 case NeonTypeFlags::Int32:
351 return shift ? 31 : (2 << IsQuad) - 1;
352 case NeonTypeFlags::Int64:
Kevin Qin624bb5e2013-11-14 03:29:16 +0000353 case NeonTypeFlags::Poly64:
Bob Wilsonda95f732011-11-08 01:16:11 +0000354 return shift ? 63 : (1 << IsQuad) - 1;
Stephen Hines651f13c2014-04-23 16:59:28 -0700355 case NeonTypeFlags::Poly128:
356 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilsonda95f732011-11-08 01:16:11 +0000357 case NeonTypeFlags::Float16:
358 assert(!shift && "cannot shift float types!");
359 return (4 << IsQuad) - 1;
360 case NeonTypeFlags::Float32:
361 assert(!shift && "cannot shift float types!");
362 return (2 << IsQuad) - 1;
Tim Northoverb793f0d2013-08-01 09:23:19 +0000363 case NeonTypeFlags::Float64:
364 assert(!shift && "cannot shift float types!");
365 return (1 << IsQuad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000366 }
David Blaikie7530c032012-01-17 06:56:22 +0000367 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman61eecf52010-06-14 05:21:25 +0000368}
369
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000370/// getNeonEltType - Return the QualType corresponding to the elements of
371/// the vector type specified by the NeonTypeFlags. This is used to check
372/// the pointer arguments for Neon load/store intrinsics.
Kevin Qin624bb5e2013-11-14 03:29:16 +0000373static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Stephen Hines651f13c2014-04-23 16:59:28 -0700374 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000375 switch (Flags.getEltType()) {
376 case NeonTypeFlags::Int8:
377 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
378 case NeonTypeFlags::Int16:
379 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
380 case NeonTypeFlags::Int32:
381 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
382 case NeonTypeFlags::Int64:
Stephen Hines651f13c2014-04-23 16:59:28 -0700383 if (IsInt64Long)
384 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
385 else
386 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
387 : Context.LongLongTy;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000388 case NeonTypeFlags::Poly8:
Stephen Hines651f13c2014-04-23 16:59:28 -0700389 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000390 case NeonTypeFlags::Poly16:
Stephen Hines651f13c2014-04-23 16:59:28 -0700391 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qin624bb5e2013-11-14 03:29:16 +0000392 case NeonTypeFlags::Poly64:
Stephen Hines651f13c2014-04-23 16:59:28 -0700393 return Context.UnsignedLongTy;
394 case NeonTypeFlags::Poly128:
395 break;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000396 case NeonTypeFlags::Float16:
Kevin Qin624bb5e2013-11-14 03:29:16 +0000397 return Context.HalfTy;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000398 case NeonTypeFlags::Float32:
399 return Context.FloatTy;
Tim Northoverb793f0d2013-08-01 09:23:19 +0000400 case NeonTypeFlags::Float64:
401 return Context.DoubleTy;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000402 }
David Blaikie7530c032012-01-17 06:56:22 +0000403 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000404}
405
Stephen Hines651f13c2014-04-23 16:59:28 -0700406bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northoverb793f0d2013-08-01 09:23:19 +0000407 llvm::APSInt Result;
Tim Northoverb793f0d2013-08-01 09:23:19 +0000408 uint64_t mask = 0;
409 unsigned TV = 0;
410 int PtrArgNum = -1;
411 bool HasConstPtr = false;
412 switch (BuiltinID) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700413#define GET_NEON_OVERLOAD_CHECK
Tim Northoverb793f0d2013-08-01 09:23:19 +0000414#include "clang/Basic/arm_neon.inc"
Stephen Hines651f13c2014-04-23 16:59:28 -0700415#undef GET_NEON_OVERLOAD_CHECK
Tim Northoverb793f0d2013-08-01 09:23:19 +0000416 }
417
418 // For NEON intrinsics which are overloaded on vector element type, validate
419 // the immediate which specifies which variant to emit.
Stephen Hines651f13c2014-04-23 16:59:28 -0700420 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northoverb793f0d2013-08-01 09:23:19 +0000421 if (mask) {
422 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
423 return true;
424
425 TV = Result.getLimitedValue(64);
426 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
427 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Stephen Hines651f13c2014-04-23 16:59:28 -0700428 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northoverb793f0d2013-08-01 09:23:19 +0000429 }
430
431 if (PtrArgNum >= 0) {
432 // Check that pointer arguments have the specified type.
433 Expr *Arg = TheCall->getArg(PtrArgNum);
434 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
435 Arg = ICE->getSubExpr();
436 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
437 QualType RHSTy = RHS.get()->getType();
Stephen Hines651f13c2014-04-23 16:59:28 -0700438
439 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
440 bool IsPolyUnsigned =
441 Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::arm64;
442 bool IsInt64Long =
443 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
444 QualType EltTy =
445 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northoverb793f0d2013-08-01 09:23:19 +0000446 if (HasConstPtr)
447 EltTy = EltTy.withConst();
448 QualType LHSTy = Context.getPointerType(EltTy);
449 AssignConvertType ConvTy;
450 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
451 if (RHS.isInvalid())
452 return true;
453 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
454 RHS.get(), AA_Assigning))
455 return true;
456 }
457
458 // For NEON intrinsics which take an immediate value as part of the
459 // instruction, range check them here.
460 unsigned i = 0, l = 0, u = 0;
461 switch (BuiltinID) {
462 default:
463 return false;
Stephen Hines651f13c2014-04-23 16:59:28 -0700464#define GET_NEON_IMMEDIATE_CHECK
Tim Northoverb793f0d2013-08-01 09:23:19 +0000465#include "clang/Basic/arm_neon.inc"
Stephen Hines651f13c2014-04-23 16:59:28 -0700466#undef GET_NEON_IMMEDIATE_CHECK
Tim Northoverb793f0d2013-08-01 09:23:19 +0000467 }
Tim Northoverb793f0d2013-08-01 09:23:19 +0000468
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700469 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Stephen Hines651f13c2014-04-23 16:59:28 -0700470}
471
472bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
473 unsigned MaxWidth) {
Tim Northover09df2b02013-07-16 09:47:53 +0000474 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Stephen Hines651f13c2014-04-23 16:59:28 -0700475 BuiltinID == ARM::BI__builtin_arm_strex ||
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700476 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
477 BuiltinID == AArch64::BI__builtin_arm_strex) &&
Tim Northover09df2b02013-07-16 09:47:53 +0000478 "unexpected ARM builtin");
Stephen Hines651f13c2014-04-23 16:59:28 -0700479 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700480 BuiltinID == AArch64::BI__builtin_arm_ldrex;
Tim Northover09df2b02013-07-16 09:47:53 +0000481
482 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
483
484 // Ensure that we have the proper number of arguments.
485 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
486 return true;
487
488 // Inspect the pointer argument of the atomic builtin. This should always be
489 // a pointer type, whose element is an integral scalar or pointer type.
490 // Because it is a pointer type, we don't have to worry about any implicit
491 // casts here.
492 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
493 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
494 if (PointerArgRes.isInvalid())
495 return true;
496 PointerArg = PointerArgRes.take();
497
498 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
499 if (!pointerType) {
500 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
501 << PointerArg->getType() << PointerArg->getSourceRange();
502 return true;
503 }
504
505 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
506 // task is to insert the appropriate casts into the AST. First work out just
507 // what the appropriate type is.
508 QualType ValType = pointerType->getPointeeType();
509 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
510 if (IsLdrex)
511 AddrType.addConst();
512
513 // Issue a warning if the cast is dodgy.
514 CastKind CastNeeded = CK_NoOp;
515 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
516 CastNeeded = CK_BitCast;
517 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
518 << PointerArg->getType()
519 << Context.getPointerType(AddrType)
520 << AA_Passing << PointerArg->getSourceRange();
521 }
522
523 // Finally, do the cast and replace the argument with the corrected version.
524 AddrType = Context.getPointerType(AddrType);
525 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
526 if (PointerArgRes.isInvalid())
527 return true;
528 PointerArg = PointerArgRes.take();
529
530 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
531
532 // In general, we allow ints, floats and pointers to be loaded and stored.
533 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
534 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
535 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
536 << PointerArg->getType() << PointerArg->getSourceRange();
537 return true;
538 }
539
540 // But ARM doesn't have instructions to deal with 128-bit versions.
Stephen Hines651f13c2014-04-23 16:59:28 -0700541 if (Context.getTypeSize(ValType) > MaxWidth) {
542 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover09df2b02013-07-16 09:47:53 +0000543 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
544 << PointerArg->getType() << PointerArg->getSourceRange();
545 return true;
546 }
547
548 switch (ValType.getObjCLifetime()) {
549 case Qualifiers::OCL_None:
550 case Qualifiers::OCL_ExplicitNone:
551 // okay
552 break;
553
554 case Qualifiers::OCL_Weak:
555 case Qualifiers::OCL_Strong:
556 case Qualifiers::OCL_Autoreleasing:
557 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
558 << ValType << PointerArg->getSourceRange();
559 return true;
560 }
561
562
563 if (IsLdrex) {
564 TheCall->setType(ValType);
565 return false;
566 }
567
568 // Initialize the argument to be stored.
569 ExprResult ValArg = TheCall->getArg(0);
570 InitializedEntity Entity = InitializedEntity::InitializeParameter(
571 Context, ValType, /*consume*/ false);
572 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
573 if (ValArg.isInvalid())
574 return true;
Tim Northover09df2b02013-07-16 09:47:53 +0000575 TheCall->setArg(0, ValArg.get());
Tim Northovera6306fc2013-10-29 12:32:58 +0000576
577 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
578 // but the custom checker bypasses all default analysis.
579 TheCall->setType(Context.IntTy);
Tim Northover09df2b02013-07-16 09:47:53 +0000580 return false;
581}
582
Nate Begeman26a31422010-06-08 02:47:44 +0000583bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000584 llvm::APSInt Result;
585
Tim Northover09df2b02013-07-16 09:47:53 +0000586 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
587 BuiltinID == ARM::BI__builtin_arm_strex) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700588 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover09df2b02013-07-16 09:47:53 +0000589 }
590
Stephen Hines651f13c2014-04-23 16:59:28 -0700591 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
592 return true;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000593
Stephen Hines651f13c2014-04-23 16:59:28 -0700594 // For NEON intrinsics which take an immediate value as part of the
Nate Begeman0d15c532010-06-13 04:47:52 +0000595 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000596 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000597 switch (BuiltinID) {
598 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000599 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
600 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000601 case ARM::BI__builtin_arm_vcvtr_f:
602 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao186b26d2013-11-12 21:42:50 +0000603 case ARM::BI__builtin_arm_dmb:
604 case ARM::BI__builtin_arm_dsb: l = 0; u = 15; break;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700605 }
Nate Begeman0d15c532010-06-13 04:47:52 +0000606
Nate Begeman99c40bb2010-08-03 21:32:34 +0000607 // FIXME: VFP Intrinsics should error if VFP not present.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700608 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssond406bf02009-08-16 01:56:34 +0000609}
Daniel Dunbarde454282008-10-02 18:44:07 +0000610
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700611bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Stephen Hines651f13c2014-04-23 16:59:28 -0700612 CallExpr *TheCall) {
613 llvm::APSInt Result;
614
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700615 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
616 BuiltinID == AArch64::BI__builtin_arm_strex) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700617 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
618 }
619
620 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
621 return true;
622
623 return false;
624}
625
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000626bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
627 unsigned i = 0, l = 0, u = 0;
628 switch (BuiltinID) {
629 default: return false;
630 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
631 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyanbe22cb82012-08-27 12:29:20 +0000632 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
633 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
634 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
635 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
636 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700637 }
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000638
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700639 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000640}
641
Stephen Hines651f13c2014-04-23 16:59:28 -0700642bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
643 switch (BuiltinID) {
644 case X86::BI_mm_prefetch:
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700645 // This is declared to take (const char*, int)
646 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
Stephen Hines651f13c2014-04-23 16:59:28 -0700647 }
648 return false;
649}
650
Richard Smith831421f2012-06-25 20:30:08 +0000651/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
652/// parameter with the FormatAttr's correct format_idx and firstDataArg.
653/// Returns true when the format fits the function and the FormatStringInfo has
654/// been populated.
655bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
656 FormatStringInfo *FSI) {
657 FSI->HasVAListArg = Format->getFirstArg() == 0;
658 FSI->FormatIdx = Format->getFormatIdx() - 1;
659 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssond406bf02009-08-16 01:56:34 +0000660
Richard Smith831421f2012-06-25 20:30:08 +0000661 // The way the format attribute works in GCC, the implicit this argument
662 // of member functions is counted. However, it doesn't appear in our own
663 // lists, so decrement format_idx in that case.
664 if (IsCXXMember) {
665 if(FSI->FormatIdx == 0)
666 return false;
667 --FSI->FormatIdx;
668 if (FSI->FirstDataArg != 0)
669 --FSI->FirstDataArg;
670 }
671 return true;
672}
Mike Stump1eb44332009-09-09 15:08:12 +0000673
Stephen Hines651f13c2014-04-23 16:59:28 -0700674/// Checks if a the given expression evaluates to null.
675///
676/// \brief Returns true if the value evaluates to null.
677static bool CheckNonNullExpr(Sema &S,
678 const Expr *Expr) {
679 // As a special case, transparent unions initialized with zero are
680 // considered null for the purposes of the nonnull attribute.
681 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
682 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
683 if (const CompoundLiteralExpr *CLE =
684 dyn_cast<CompoundLiteralExpr>(Expr))
685 if (const InitListExpr *ILE =
686 dyn_cast<InitListExpr>(CLE->getInitializer()))
687 Expr = ILE->getInit(0);
688 }
689
690 bool Result;
691 return (!Expr->isValueDependent() &&
692 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
693 !Result);
694}
695
696static void CheckNonNullArgument(Sema &S,
697 const Expr *ArgExpr,
698 SourceLocation CallSiteLoc) {
699 if (CheckNonNullExpr(S, ArgExpr))
700 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
701}
702
703static void CheckNonNullArguments(Sema &S,
704 const NamedDecl *FDecl,
705 const Expr * const *ExprArgs,
706 SourceLocation CallSiteLoc) {
707 // Check the attributes attached to the method/function itself.
708 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700709 for (const auto &Val : NonNull->args())
710 CheckNonNullArgument(S, ExprArgs[Val], CallSiteLoc);
Stephen Hines651f13c2014-04-23 16:59:28 -0700711 }
712
713 // Check the attributes on the parameters.
714 ArrayRef<ParmVarDecl*> parms;
715 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
716 parms = FD->parameters();
717 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
718 parms = MD->parameters();
719
720 unsigned argIndex = 0;
721 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
722 I != E; ++I, ++argIndex) {
723 const ParmVarDecl *PVD = *I;
724 if (PVD->hasAttr<NonNullAttr>())
725 CheckNonNullArgument(S, ExprArgs[argIndex], CallSiteLoc);
726 }
727}
728
Richard Smith831421f2012-06-25 20:30:08 +0000729/// Handles the checks for format strings, non-POD arguments to vararg
730/// functions, and NULL arguments passed to non-NULL parameters.
Stephen Hines651f13c2014-04-23 16:59:28 -0700731void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
732 unsigned NumParams, bool IsMemberFunction,
733 SourceLocation Loc, SourceRange Range,
Richard Smith831421f2012-06-25 20:30:08 +0000734 VariadicCallType CallType) {
Richard Smith0e218972013-08-05 18:49:43 +0000735 // FIXME: We should check as much as we can in the template definition.
Jordan Rose66360e22012-10-02 01:49:54 +0000736 if (CurContext->isDependentContext())
737 return;
Daniel Dunbarde454282008-10-02 18:44:07 +0000738
Ted Kremenekc82faca2010-09-09 04:33:05 +0000739 // Printf and scanf checking.
Richard Smith0e218972013-08-05 18:49:43 +0000740 llvm::SmallBitVector CheckedVarArgs;
741 if (FDecl) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700742 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer541a28f2013-08-09 09:39:17 +0000743 // Only create vector if there are format attributes.
744 CheckedVarArgs.resize(Args.size());
745
Stephen Hines651f13c2014-04-23 16:59:28 -0700746 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramer47abb252013-08-08 11:08:26 +0000747 CheckedVarArgs);
Benjamin Kramer541a28f2013-08-09 09:39:17 +0000748 }
Richard Smith0e218972013-08-05 18:49:43 +0000749 }
Richard Smith831421f2012-06-25 20:30:08 +0000750
751 // Refuse POD arguments that weren't caught by the format string
752 // checks above.
Richard Smith0e218972013-08-05 18:49:43 +0000753 if (CallType != VariadicDoesNotApply) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700754 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek0234bfa2012-10-11 19:06:43 +0000755 // Args[ArgIdx] can be null in malformed code.
Richard Smith0e218972013-08-05 18:49:43 +0000756 if (const Expr *Arg = Args[ArgIdx]) {
757 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
758 checkVariadicArgument(Arg, CallType);
759 }
Ted Kremenek0234bfa2012-10-11 19:06:43 +0000760 }
Richard Smith0e218972013-08-05 18:49:43 +0000761 }
Mike Stump1eb44332009-09-09 15:08:12 +0000762
Richard Trieu0538f0e2013-06-22 00:20:41 +0000763 if (FDecl) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700764 CheckNonNullArguments(*this, FDecl, Args.data(), Loc);
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +0000765
Richard Trieu0538f0e2013-06-22 00:20:41 +0000766 // Type safety checking.
Stephen Hines651f13c2014-04-23 16:59:28 -0700767 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
768 CheckArgumentWithTypeTag(I, Args.data());
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +0000769 }
Richard Smith831421f2012-06-25 20:30:08 +0000770}
771
772/// CheckConstructorCall - Check a constructor call for correctness and safety
773/// properties not enforced by the C type system.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000774void Sema::CheckConstructorCall(FunctionDecl *FDecl,
775 ArrayRef<const Expr *> Args,
Richard Smith831421f2012-06-25 20:30:08 +0000776 const FunctionProtoType *Proto,
777 SourceLocation Loc) {
778 VariadicCallType CallType =
779 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Stephen Hines651f13c2014-04-23 16:59:28 -0700780 checkCall(FDecl, Args, Proto->getNumParams(),
Richard Smith831421f2012-06-25 20:30:08 +0000781 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
782}
783
784/// CheckFunctionCall - Check a direct function call for various correctness
785/// and safety properties not strictly enforced by the C type system.
786bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
787 const FunctionProtoType *Proto) {
Eli Friedman2edcde82012-10-11 00:30:58 +0000788 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
789 isa<CXXMethodDecl>(FDecl);
790 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
791 IsMemberOperatorCall;
Richard Smith831421f2012-06-25 20:30:08 +0000792 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
793 TheCall->getCallee());
Stephen Hines651f13c2014-04-23 16:59:28 -0700794 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Eli Friedman2edcde82012-10-11 00:30:58 +0000795 Expr** Args = TheCall->getArgs();
796 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmandf75b0c2012-10-11 00:34:15 +0000797 if (IsMemberOperatorCall) {
Eli Friedman2edcde82012-10-11 00:30:58 +0000798 // If this is a call to a member operator, hide the first argument
799 // from checkCall.
800 // FIXME: Our choice of AST representation here is less than ideal.
801 ++Args;
802 --NumArgs;
803 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700804 checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs), NumParams,
Richard Smith831421f2012-06-25 20:30:08 +0000805 IsMemberFunction, TheCall->getRParenLoc(),
806 TheCall->getCallee()->getSourceRange(), CallType);
807
808 IdentifierInfo *FnInfo = FDecl->getIdentifier();
809 // None of the checks below are needed for functions that don't have
810 // simple names (e.g., C++ conversion functions).
811 if (!FnInfo)
812 return false;
Sebastian Redl0eb23302009-01-19 00:08:26 +0000813
Stephen Hines651f13c2014-04-23 16:59:28 -0700814 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
815
Anna Zaks0a151a12012-01-17 00:37:07 +0000816 unsigned CMId = FDecl->getMemoryFunctionKind();
817 if (CMId == 0)
Anna Zaksd9b859a2012-01-13 21:52:01 +0000818 return false;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000819
Anna Zaksd9b859a2012-01-13 21:52:01 +0000820 // Handle memory setting and copying functions.
Anna Zaks0a151a12012-01-17 00:37:07 +0000821 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000822 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaksc36bedc2012-02-01 19:08:57 +0000823 else if (CMId == Builtin::BIstrncat)
824 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaksd9b859a2012-01-13 21:52:01 +0000825 else
Anna Zaks0a151a12012-01-17 00:37:07 +0000826 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000827
Anders Carlssond406bf02009-08-16 01:56:34 +0000828 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000829}
830
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000831bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko287f24d2013-05-05 19:42:09 +0000832 ArrayRef<const Expr *> Args) {
Richard Smith831421f2012-06-25 20:30:08 +0000833 VariadicCallType CallType =
834 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000835
Dmitri Gribenko287f24d2013-05-05 19:42:09 +0000836 checkCall(Method, Args, Method->param_size(),
Richard Smith831421f2012-06-25 20:30:08 +0000837 /*IsMemberFunction=*/false,
838 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000839
840 return false;
841}
842
Richard Trieuf462b012013-06-20 21:03:13 +0000843bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
844 const FunctionProtoType *Proto) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000845 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
846 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000847 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000848
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000849 QualType Ty = V->getType();
Richard Trieuf462b012013-06-20 21:03:13 +0000850 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000851 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000852
Richard Trieuf462b012013-06-20 21:03:13 +0000853 VariadicCallType CallType;
Richard Trieua4993772013-06-20 23:21:54 +0000854 if (!Proto || !Proto->isVariadic()) {
Richard Trieuf462b012013-06-20 21:03:13 +0000855 CallType = VariadicDoesNotApply;
856 } else if (Ty->isBlockPointerType()) {
857 CallType = VariadicBlock;
858 } else { // Ty->isFunctionPointerType()
859 CallType = VariadicFunction;
860 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700861 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Anders Carlssond406bf02009-08-16 01:56:34 +0000862
Stephen Hines651f13c2014-04-23 16:59:28 -0700863 checkCall(NDecl, llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
864 TheCall->getNumArgs()),
865 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith831421f2012-06-25 20:30:08 +0000866 TheCall->getCallee()->getSourceRange(), CallType);
Stephen Hines651f13c2014-04-23 16:59:28 -0700867
Anders Carlssond406bf02009-08-16 01:56:34 +0000868 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000869}
870
Richard Trieu0538f0e2013-06-22 00:20:41 +0000871/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
872/// such as function pointers returned from functions.
873bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700874 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu0538f0e2013-06-22 00:20:41 +0000875 TheCall->getCallee());
Stephen Hines651f13c2014-04-23 16:59:28 -0700876 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Richard Trieu0538f0e2013-06-22 00:20:41 +0000877
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700878 checkCall(/*FDecl=*/nullptr,
879 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
880 TheCall->getNumArgs()),
Stephen Hines651f13c2014-04-23 16:59:28 -0700881 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu0538f0e2013-06-22 00:20:41 +0000882 TheCall->getCallee()->getSourceRange(), CallType);
883
884 return false;
885}
886
Stephen Hines651f13c2014-04-23 16:59:28 -0700887static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
888 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
889 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
890 return false;
891
892 switch (Op) {
893 case AtomicExpr::AO__c11_atomic_init:
894 llvm_unreachable("There is no ordering argument for an init");
895
896 case AtomicExpr::AO__c11_atomic_load:
897 case AtomicExpr::AO__atomic_load_n:
898 case AtomicExpr::AO__atomic_load:
899 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
900 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
901
902 case AtomicExpr::AO__c11_atomic_store:
903 case AtomicExpr::AO__atomic_store:
904 case AtomicExpr::AO__atomic_store_n:
905 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
906 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
907 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
908
909 default:
910 return true;
911 }
912}
913
Richard Smithff34d402012-04-12 05:08:17 +0000914ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
915 AtomicExpr::AtomicOp Op) {
Eli Friedman276b0612011-10-11 02:20:01 +0000916 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
917 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000918
Richard Smithff34d402012-04-12 05:08:17 +0000919 // All these operations take one of the following forms:
920 enum {
921 // C __c11_atomic_init(A *, C)
922 Init,
923 // C __c11_atomic_load(A *, int)
924 Load,
925 // void __atomic_load(A *, CP, int)
926 Copy,
927 // C __c11_atomic_add(A *, M, int)
928 Arithmetic,
929 // C __atomic_exchange_n(A *, CP, int)
930 Xchg,
931 // void __atomic_exchange(A *, C *, CP, int)
932 GNUXchg,
933 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
934 C11CmpXchg,
935 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
936 GNUCmpXchg
937 } Form = Init;
938 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
939 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
940 // where:
941 // C is an appropriate type,
942 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
943 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
944 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
945 // the int parameters are for orderings.
Eli Friedman276b0612011-10-11 02:20:01 +0000946
Richard Smithff34d402012-04-12 05:08:17 +0000947 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
948 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
949 && "need to update code for modified C11 atomics");
950 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
951 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
952 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
953 Op == AtomicExpr::AO__atomic_store_n ||
954 Op == AtomicExpr::AO__atomic_exchange_n ||
955 Op == AtomicExpr::AO__atomic_compare_exchange_n;
956 bool IsAddSub = false;
957
958 switch (Op) {
959 case AtomicExpr::AO__c11_atomic_init:
960 Form = Init;
961 break;
962
963 case AtomicExpr::AO__c11_atomic_load:
964 case AtomicExpr::AO__atomic_load_n:
965 Form = Load;
966 break;
967
968 case AtomicExpr::AO__c11_atomic_store:
969 case AtomicExpr::AO__atomic_load:
970 case AtomicExpr::AO__atomic_store:
971 case AtomicExpr::AO__atomic_store_n:
972 Form = Copy;
973 break;
974
975 case AtomicExpr::AO__c11_atomic_fetch_add:
976 case AtomicExpr::AO__c11_atomic_fetch_sub:
977 case AtomicExpr::AO__atomic_fetch_add:
978 case AtomicExpr::AO__atomic_fetch_sub:
979 case AtomicExpr::AO__atomic_add_fetch:
980 case AtomicExpr::AO__atomic_sub_fetch:
981 IsAddSub = true;
982 // Fall through.
983 case AtomicExpr::AO__c11_atomic_fetch_and:
984 case AtomicExpr::AO__c11_atomic_fetch_or:
985 case AtomicExpr::AO__c11_atomic_fetch_xor:
986 case AtomicExpr::AO__atomic_fetch_and:
987 case AtomicExpr::AO__atomic_fetch_or:
988 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smith51b92402012-04-13 06:31:38 +0000989 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithff34d402012-04-12 05:08:17 +0000990 case AtomicExpr::AO__atomic_and_fetch:
991 case AtomicExpr::AO__atomic_or_fetch:
992 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smith51b92402012-04-13 06:31:38 +0000993 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithff34d402012-04-12 05:08:17 +0000994 Form = Arithmetic;
995 break;
996
997 case AtomicExpr::AO__c11_atomic_exchange:
998 case AtomicExpr::AO__atomic_exchange_n:
999 Form = Xchg;
1000 break;
1001
1002 case AtomicExpr::AO__atomic_exchange:
1003 Form = GNUXchg;
1004 break;
1005
1006 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1007 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1008 Form = C11CmpXchg;
1009 break;
1010
1011 case AtomicExpr::AO__atomic_compare_exchange:
1012 case AtomicExpr::AO__atomic_compare_exchange_n:
1013 Form = GNUCmpXchg;
1014 break;
1015 }
1016
1017 // Check we have the right number of arguments.
1018 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedman276b0612011-10-11 02:20:01 +00001019 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithff34d402012-04-12 05:08:17 +00001020 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +00001021 << TheCall->getCallee()->getSourceRange();
1022 return ExprError();
Richard Smithff34d402012-04-12 05:08:17 +00001023 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1024 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedman276b0612011-10-11 02:20:01 +00001025 diag::err_typecheck_call_too_many_args)
Richard Smithff34d402012-04-12 05:08:17 +00001026 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +00001027 << TheCall->getCallee()->getSourceRange();
1028 return ExprError();
1029 }
1030
Richard Smithff34d402012-04-12 05:08:17 +00001031 // Inspect the first argument of the atomic operation.
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001032 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +00001033 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1034 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1035 if (!pointerType) {
Richard Smithff34d402012-04-12 05:08:17 +00001036 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedman276b0612011-10-11 02:20:01 +00001037 << Ptr->getType() << Ptr->getSourceRange();
1038 return ExprError();
1039 }
1040
Richard Smithff34d402012-04-12 05:08:17 +00001041 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1042 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1043 QualType ValType = AtomTy; // 'C'
1044 if (IsC11) {
1045 if (!AtomTy->isAtomicType()) {
1046 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1047 << Ptr->getType() << Ptr->getSourceRange();
1048 return ExprError();
1049 }
Richard Smithbc57b102012-09-15 06:09:58 +00001050 if (AtomTy.isConstQualified()) {
1051 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1052 << Ptr->getType() << Ptr->getSourceRange();
1053 return ExprError();
1054 }
Richard Smithff34d402012-04-12 05:08:17 +00001055 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedman276b0612011-10-11 02:20:01 +00001056 }
Eli Friedman276b0612011-10-11 02:20:01 +00001057
Richard Smithff34d402012-04-12 05:08:17 +00001058 // For an arithmetic operation, the implied arithmetic must be well-formed.
1059 if (Form == Arithmetic) {
1060 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1061 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1062 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1063 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1064 return ExprError();
1065 }
1066 if (!IsAddSub && !ValType->isIntegerType()) {
1067 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1068 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1069 return ExprError();
1070 }
1071 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1072 // For __atomic_*_n operations, the value type must be a scalar integral or
1073 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedman276b0612011-10-11 02:20:01 +00001074 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithff34d402012-04-12 05:08:17 +00001075 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1076 return ExprError();
1077 }
1078
Eli Friedmana3d727b2013-09-11 03:49:34 +00001079 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1080 !AtomTy->isScalarType()) {
Richard Smithff34d402012-04-12 05:08:17 +00001081 // For GNU atomics, require a trivially-copyable type. This is not part of
1082 // the GNU atomics specification, but we enforce it for sanity.
1083 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedman276b0612011-10-11 02:20:01 +00001084 << Ptr->getType() << Ptr->getSourceRange();
1085 return ExprError();
1086 }
1087
Richard Smithff34d402012-04-12 05:08:17 +00001088 // FIXME: For any builtin other than a load, the ValType must not be
1089 // const-qualified.
Eli Friedman276b0612011-10-11 02:20:01 +00001090
1091 switch (ValType.getObjCLifetime()) {
1092 case Qualifiers::OCL_None:
1093 case Qualifiers::OCL_ExplicitNone:
1094 // okay
1095 break;
1096
1097 case Qualifiers::OCL_Weak:
1098 case Qualifiers::OCL_Strong:
1099 case Qualifiers::OCL_Autoreleasing:
Richard Smithff34d402012-04-12 05:08:17 +00001100 // FIXME: Can this happen? By this point, ValType should be known
1101 // to be trivially copyable.
Eli Friedman276b0612011-10-11 02:20:01 +00001102 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1103 << ValType << Ptr->getSourceRange();
1104 return ExprError();
1105 }
1106
1107 QualType ResultType = ValType;
Richard Smithff34d402012-04-12 05:08:17 +00001108 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedman276b0612011-10-11 02:20:01 +00001109 ResultType = Context.VoidTy;
Richard Smithff34d402012-04-12 05:08:17 +00001110 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedman276b0612011-10-11 02:20:01 +00001111 ResultType = Context.BoolTy;
1112
Richard Smithff34d402012-04-12 05:08:17 +00001113 // The type of a parameter passed 'by value'. In the GNU atomics, such
1114 // arguments are actually passed as pointers.
1115 QualType ByValType = ValType; // 'CP'
1116 if (!IsC11 && !IsN)
1117 ByValType = Ptr->getType();
1118
Eli Friedman276b0612011-10-11 02:20:01 +00001119 // The first argument --- the pointer --- has a fixed type; we
1120 // deduce the types of the rest of the arguments accordingly. Walk
1121 // the remaining arguments, converting them to the deduced value type.
Richard Smithff34d402012-04-12 05:08:17 +00001122 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedman276b0612011-10-11 02:20:01 +00001123 QualType Ty;
Richard Smithff34d402012-04-12 05:08:17 +00001124 if (i < NumVals[Form] + 1) {
1125 switch (i) {
1126 case 1:
1127 // The second argument is the non-atomic operand. For arithmetic, this
1128 // is always passed by value, and for a compare_exchange it is always
1129 // passed by address. For the rest, GNU uses by-address and C11 uses
1130 // by-value.
1131 assert(Form != Load);
1132 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1133 Ty = ValType;
1134 else if (Form == Copy || Form == Xchg)
1135 Ty = ByValType;
1136 else if (Form == Arithmetic)
1137 Ty = Context.getPointerDiffType();
1138 else
1139 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1140 break;
1141 case 2:
1142 // The third argument to compare_exchange / GNU exchange is a
1143 // (pointer to a) desired value.
1144 Ty = ByValType;
1145 break;
1146 case 3:
1147 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1148 Ty = Context.BoolTy;
1149 break;
1150 }
Eli Friedman276b0612011-10-11 02:20:01 +00001151 } else {
1152 // The order(s) are always converted to int.
1153 Ty = Context.IntTy;
1154 }
Richard Smithff34d402012-04-12 05:08:17 +00001155
Eli Friedman276b0612011-10-11 02:20:01 +00001156 InitializedEntity Entity =
1157 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithff34d402012-04-12 05:08:17 +00001158 ExprResult Arg = TheCall->getArg(i);
Eli Friedman276b0612011-10-11 02:20:01 +00001159 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1160 if (Arg.isInvalid())
1161 return true;
1162 TheCall->setArg(i, Arg.get());
1163 }
1164
Richard Smithff34d402012-04-12 05:08:17 +00001165 // Permute the arguments into a 'consistent' order.
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001166 SmallVector<Expr*, 5> SubExprs;
1167 SubExprs.push_back(Ptr);
Richard Smithff34d402012-04-12 05:08:17 +00001168 switch (Form) {
1169 case Init:
1170 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnall7a7ee302012-01-16 17:27:18 +00001171 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +00001172 break;
1173 case Load:
1174 SubExprs.push_back(TheCall->getArg(1)); // Order
1175 break;
1176 case Copy:
1177 case Arithmetic:
1178 case Xchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001179 SubExprs.push_back(TheCall->getArg(2)); // Order
1180 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +00001181 break;
1182 case GNUXchg:
1183 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1184 SubExprs.push_back(TheCall->getArg(3)); // Order
1185 SubExprs.push_back(TheCall->getArg(1)); // Val1
1186 SubExprs.push_back(TheCall->getArg(2)); // Val2
1187 break;
1188 case C11CmpXchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001189 SubExprs.push_back(TheCall->getArg(3)); // Order
1190 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001191 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall2ebb98a2012-03-29 17:58:59 +00001192 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithff34d402012-04-12 05:08:17 +00001193 break;
1194 case GNUCmpXchg:
1195 SubExprs.push_back(TheCall->getArg(4)); // Order
1196 SubExprs.push_back(TheCall->getArg(1)); // Val1
1197 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1198 SubExprs.push_back(TheCall->getArg(2)); // Val2
1199 SubExprs.push_back(TheCall->getArg(3)); // Weak
1200 break;
Eli Friedman276b0612011-10-11 02:20:01 +00001201 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001202
1203 if (SubExprs.size() >= 2 && Form != Init) {
1204 llvm::APSInt Result(32);
1205 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1206 !isValidOrderingForOp(Result.getSExtValue(), Op))
1207 Diag(SubExprs[1]->getLocStart(),
1208 diag::warn_atomic_op_has_invalid_memory_order)
1209 << SubExprs[1]->getSourceRange();
1210 }
1211
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00001212 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1213 SubExprs, ResultType, Op,
1214 TheCall->getRParenLoc());
1215
1216 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1217 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1218 Context.AtomicUsesUnsupportedLibcall(AE))
1219 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1220 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001221
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00001222 return Owned(AE);
Eli Friedman276b0612011-10-11 02:20:01 +00001223}
1224
1225
John McCall5f8d6042011-08-27 01:09:30 +00001226/// checkBuiltinArgument - Given a call to a builtin function, perform
1227/// normal type-checking on the given argument, updating the call in
1228/// place. This is useful when a builtin function requires custom
1229/// type-checking for some of its arguments but not necessarily all of
1230/// them.
1231///
1232/// Returns true on error.
1233static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1234 FunctionDecl *Fn = E->getDirectCallee();
1235 assert(Fn && "builtin call without direct callee!");
1236
1237 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1238 InitializedEntity Entity =
1239 InitializedEntity::InitializeParameter(S.Context, Param);
1240
1241 ExprResult Arg = E->getArg(0);
1242 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1243 if (Arg.isInvalid())
1244 return true;
1245
1246 E->setArg(ArgIndex, Arg.take());
1247 return false;
1248}
1249
Chris Lattner5caa3702009-05-08 06:58:22 +00001250/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1251/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1252/// type of its first argument. The main ActOnCallExpr routines have already
1253/// promoted the types of arguments because all of these calls are prototyped as
1254/// void(...).
1255///
1256/// This function goes through and does final semantic checking for these
1257/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +00001258ExprResult
1259Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +00001260 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +00001261 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1262 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1263
1264 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +00001265 if (TheCall->getNumArgs() < 1) {
1266 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1267 << 0 << 1 << TheCall->getNumArgs()
1268 << TheCall->getCallee()->getSourceRange();
1269 return ExprError();
1270 }
Mike Stump1eb44332009-09-09 15:08:12 +00001271
Chris Lattner5caa3702009-05-08 06:58:22 +00001272 // Inspect the first argument of the atomic builtin. This should always be
1273 // a pointer type, whose element is an integral scalar or pointer type.
1274 // Because it is a pointer type, we don't have to worry about any implicit
1275 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +00001276 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +00001277 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman8c382062012-01-23 02:35:22 +00001278 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1279 if (FirstArgResult.isInvalid())
1280 return ExprError();
1281 FirstArg = FirstArgResult.take();
1282 TheCall->setArg(0, FirstArg);
1283
John McCallf85e1932011-06-15 23:02:42 +00001284 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1285 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +00001286 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1287 << FirstArg->getType() << FirstArg->getSourceRange();
1288 return ExprError();
1289 }
Mike Stump1eb44332009-09-09 15:08:12 +00001290
John McCallf85e1932011-06-15 23:02:42 +00001291 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +00001292 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +00001293 !ValType->isBlockPointerType()) {
1294 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1295 << FirstArg->getType() << FirstArg->getSourceRange();
1296 return ExprError();
1297 }
Chris Lattner5caa3702009-05-08 06:58:22 +00001298
John McCallf85e1932011-06-15 23:02:42 +00001299 switch (ValType.getObjCLifetime()) {
1300 case Qualifiers::OCL_None:
1301 case Qualifiers::OCL_ExplicitNone:
1302 // okay
1303 break;
1304
1305 case Qualifiers::OCL_Weak:
1306 case Qualifiers::OCL_Strong:
1307 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001308 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001309 << ValType << FirstArg->getSourceRange();
1310 return ExprError();
1311 }
1312
John McCallb45ae252011-10-05 07:41:44 +00001313 // Strip any qualifiers off ValType.
1314 ValType = ValType.getUnqualifiedType();
1315
Chandler Carruth8d13d222010-07-18 20:54:12 +00001316 // The majority of builtins return a value, but a few have special return
1317 // types, so allow them to override appropriately below.
1318 QualType ResultType = ValType;
1319
Chris Lattner5caa3702009-05-08 06:58:22 +00001320 // We need to figure out which concrete builtin this maps onto. For example,
1321 // __sync_fetch_and_add with a 2 byte object turns into
1322 // __sync_fetch_and_add_2.
1323#define BUILTIN_ROW(x) \
1324 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1325 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +00001326
Chris Lattner5caa3702009-05-08 06:58:22 +00001327 static const unsigned BuiltinIndices[][5] = {
1328 BUILTIN_ROW(__sync_fetch_and_add),
1329 BUILTIN_ROW(__sync_fetch_and_sub),
1330 BUILTIN_ROW(__sync_fetch_and_or),
1331 BUILTIN_ROW(__sync_fetch_and_and),
1332 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +00001333
Chris Lattner5caa3702009-05-08 06:58:22 +00001334 BUILTIN_ROW(__sync_add_and_fetch),
1335 BUILTIN_ROW(__sync_sub_and_fetch),
1336 BUILTIN_ROW(__sync_and_and_fetch),
1337 BUILTIN_ROW(__sync_or_and_fetch),
1338 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +00001339
Chris Lattner5caa3702009-05-08 06:58:22 +00001340 BUILTIN_ROW(__sync_val_compare_and_swap),
1341 BUILTIN_ROW(__sync_bool_compare_and_swap),
1342 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +00001343 BUILTIN_ROW(__sync_lock_release),
1344 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +00001345 };
Mike Stump1eb44332009-09-09 15:08:12 +00001346#undef BUILTIN_ROW
1347
Chris Lattner5caa3702009-05-08 06:58:22 +00001348 // Determine the index of the size.
1349 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +00001350 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +00001351 case 1: SizeIndex = 0; break;
1352 case 2: SizeIndex = 1; break;
1353 case 4: SizeIndex = 2; break;
1354 case 8: SizeIndex = 3; break;
1355 case 16: SizeIndex = 4; break;
1356 default:
Chandler Carruthd2014572010-07-09 18:59:35 +00001357 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1358 << FirstArg->getType() << FirstArg->getSourceRange();
1359 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +00001360 }
Mike Stump1eb44332009-09-09 15:08:12 +00001361
Chris Lattner5caa3702009-05-08 06:58:22 +00001362 // Each of these builtins has one pointer argument, followed by some number of
1363 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1364 // that we ignore. Find out which row of BuiltinIndices to read from as well
1365 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00001366 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +00001367 unsigned BuiltinIndex, NumFixed = 1;
1368 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001369 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +00001370 case Builtin::BI__sync_fetch_and_add:
1371 case Builtin::BI__sync_fetch_and_add_1:
1372 case Builtin::BI__sync_fetch_and_add_2:
1373 case Builtin::BI__sync_fetch_and_add_4:
1374 case Builtin::BI__sync_fetch_and_add_8:
1375 case Builtin::BI__sync_fetch_and_add_16:
1376 BuiltinIndex = 0;
1377 break;
1378
1379 case Builtin::BI__sync_fetch_and_sub:
1380 case Builtin::BI__sync_fetch_and_sub_1:
1381 case Builtin::BI__sync_fetch_and_sub_2:
1382 case Builtin::BI__sync_fetch_and_sub_4:
1383 case Builtin::BI__sync_fetch_and_sub_8:
1384 case Builtin::BI__sync_fetch_and_sub_16:
1385 BuiltinIndex = 1;
1386 break;
1387
1388 case Builtin::BI__sync_fetch_and_or:
1389 case Builtin::BI__sync_fetch_and_or_1:
1390 case Builtin::BI__sync_fetch_and_or_2:
1391 case Builtin::BI__sync_fetch_and_or_4:
1392 case Builtin::BI__sync_fetch_and_or_8:
1393 case Builtin::BI__sync_fetch_and_or_16:
1394 BuiltinIndex = 2;
1395 break;
1396
1397 case Builtin::BI__sync_fetch_and_and:
1398 case Builtin::BI__sync_fetch_and_and_1:
1399 case Builtin::BI__sync_fetch_and_and_2:
1400 case Builtin::BI__sync_fetch_and_and_4:
1401 case Builtin::BI__sync_fetch_and_and_8:
1402 case Builtin::BI__sync_fetch_and_and_16:
1403 BuiltinIndex = 3;
1404 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001405
Douglas Gregora9766412011-11-28 16:30:08 +00001406 case Builtin::BI__sync_fetch_and_xor:
1407 case Builtin::BI__sync_fetch_and_xor_1:
1408 case Builtin::BI__sync_fetch_and_xor_2:
1409 case Builtin::BI__sync_fetch_and_xor_4:
1410 case Builtin::BI__sync_fetch_and_xor_8:
1411 case Builtin::BI__sync_fetch_and_xor_16:
1412 BuiltinIndex = 4;
1413 break;
1414
1415 case Builtin::BI__sync_add_and_fetch:
1416 case Builtin::BI__sync_add_and_fetch_1:
1417 case Builtin::BI__sync_add_and_fetch_2:
1418 case Builtin::BI__sync_add_and_fetch_4:
1419 case Builtin::BI__sync_add_and_fetch_8:
1420 case Builtin::BI__sync_add_and_fetch_16:
1421 BuiltinIndex = 5;
1422 break;
1423
1424 case Builtin::BI__sync_sub_and_fetch:
1425 case Builtin::BI__sync_sub_and_fetch_1:
1426 case Builtin::BI__sync_sub_and_fetch_2:
1427 case Builtin::BI__sync_sub_and_fetch_4:
1428 case Builtin::BI__sync_sub_and_fetch_8:
1429 case Builtin::BI__sync_sub_and_fetch_16:
1430 BuiltinIndex = 6;
1431 break;
1432
1433 case Builtin::BI__sync_and_and_fetch:
1434 case Builtin::BI__sync_and_and_fetch_1:
1435 case Builtin::BI__sync_and_and_fetch_2:
1436 case Builtin::BI__sync_and_and_fetch_4:
1437 case Builtin::BI__sync_and_and_fetch_8:
1438 case Builtin::BI__sync_and_and_fetch_16:
1439 BuiltinIndex = 7;
1440 break;
1441
1442 case Builtin::BI__sync_or_and_fetch:
1443 case Builtin::BI__sync_or_and_fetch_1:
1444 case Builtin::BI__sync_or_and_fetch_2:
1445 case Builtin::BI__sync_or_and_fetch_4:
1446 case Builtin::BI__sync_or_and_fetch_8:
1447 case Builtin::BI__sync_or_and_fetch_16:
1448 BuiltinIndex = 8;
1449 break;
1450
1451 case Builtin::BI__sync_xor_and_fetch:
1452 case Builtin::BI__sync_xor_and_fetch_1:
1453 case Builtin::BI__sync_xor_and_fetch_2:
1454 case Builtin::BI__sync_xor_and_fetch_4:
1455 case Builtin::BI__sync_xor_and_fetch_8:
1456 case Builtin::BI__sync_xor_and_fetch_16:
1457 BuiltinIndex = 9;
1458 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001459
Chris Lattner5caa3702009-05-08 06:58:22 +00001460 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001461 case Builtin::BI__sync_val_compare_and_swap_1:
1462 case Builtin::BI__sync_val_compare_and_swap_2:
1463 case Builtin::BI__sync_val_compare_and_swap_4:
1464 case Builtin::BI__sync_val_compare_and_swap_8:
1465 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001466 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +00001467 NumFixed = 2;
1468 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001469
Chris Lattner5caa3702009-05-08 06:58:22 +00001470 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001471 case Builtin::BI__sync_bool_compare_and_swap_1:
1472 case Builtin::BI__sync_bool_compare_and_swap_2:
1473 case Builtin::BI__sync_bool_compare_and_swap_4:
1474 case Builtin::BI__sync_bool_compare_and_swap_8:
1475 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001476 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +00001477 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001478 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001479 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001480
1481 case Builtin::BI__sync_lock_test_and_set:
1482 case Builtin::BI__sync_lock_test_and_set_1:
1483 case Builtin::BI__sync_lock_test_and_set_2:
1484 case Builtin::BI__sync_lock_test_and_set_4:
1485 case Builtin::BI__sync_lock_test_and_set_8:
1486 case Builtin::BI__sync_lock_test_and_set_16:
1487 BuiltinIndex = 12;
1488 break;
1489
Chris Lattner5caa3702009-05-08 06:58:22 +00001490 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +00001491 case Builtin::BI__sync_lock_release_1:
1492 case Builtin::BI__sync_lock_release_2:
1493 case Builtin::BI__sync_lock_release_4:
1494 case Builtin::BI__sync_lock_release_8:
1495 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001496 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +00001497 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001498 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001499 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001500
1501 case Builtin::BI__sync_swap:
1502 case Builtin::BI__sync_swap_1:
1503 case Builtin::BI__sync_swap_2:
1504 case Builtin::BI__sync_swap_4:
1505 case Builtin::BI__sync_swap_8:
1506 case Builtin::BI__sync_swap_16:
1507 BuiltinIndex = 14;
1508 break;
Chris Lattner5caa3702009-05-08 06:58:22 +00001509 }
Mike Stump1eb44332009-09-09 15:08:12 +00001510
Chris Lattner5caa3702009-05-08 06:58:22 +00001511 // Now that we know how many fixed arguments we expect, first check that we
1512 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +00001513 if (TheCall->getNumArgs() < 1+NumFixed) {
1514 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1515 << 0 << 1+NumFixed << TheCall->getNumArgs()
1516 << TheCall->getCallee()->getSourceRange();
1517 return ExprError();
1518 }
Mike Stump1eb44332009-09-09 15:08:12 +00001519
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001520 // Get the decl for the concrete builtin from this, we can tell what the
1521 // concrete integer type we should convert to is.
1522 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1523 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara2ad11cd2012-09-22 09:05:22 +00001524 FunctionDecl *NewBuiltinDecl;
1525 if (NewBuiltinID == BuiltinID)
1526 NewBuiltinDecl = FDecl;
1527 else {
1528 // Perform builtin lookup to avoid redeclaring it.
1529 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1530 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1531 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1532 assert(Res.getFoundDecl());
1533 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001534 if (!NewBuiltinDecl)
Abramo Bagnara2ad11cd2012-09-22 09:05:22 +00001535 return ExprError();
1536 }
Chandler Carruthd2014572010-07-09 18:59:35 +00001537
John McCallf871d0c2010-08-07 06:22:56 +00001538 // The first argument --- the pointer --- has a fixed type; we
1539 // deduce the types of the rest of the arguments accordingly. Walk
1540 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +00001541 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +00001542 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +00001543
Chris Lattner5caa3702009-05-08 06:58:22 +00001544 // GCC does an implicit conversion to the pointer or integer ValType. This
1545 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +00001546 // Initialize the argument.
1547 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1548 ValType, /*consume*/ false);
1549 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +00001550 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +00001551 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001552
Chris Lattner5caa3702009-05-08 06:58:22 +00001553 // Okay, we have something that *can* be converted to the right type. Check
1554 // to see if there is a potentially weird extension going on here. This can
1555 // happen when you do an atomic operation on something like an char* and
1556 // pass in 42. The 42 gets converted to char. This is even more strange
1557 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +00001558 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +00001559 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +00001560 }
Mike Stump1eb44332009-09-09 15:08:12 +00001561
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001562 ASTContext& Context = this->getASTContext();
1563
1564 // Create a new DeclRefExpr to refer to the new decl.
1565 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1566 Context,
1567 DRE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001568 SourceLocation(),
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001569 NewBuiltinDecl,
John McCallf4b88a42012-03-10 09:33:50 +00001570 /*enclosing*/ false,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001571 DRE->getLocation(),
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001572 Context.BuiltinFnTy,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001573 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +00001574
Chris Lattner5caa3702009-05-08 06:58:22 +00001575 // Set the callee in the CallExpr.
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001576 // FIXME: This loses syntactic information.
1577 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1578 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1579 CK_BuiltinFnToFnPtr);
John Wiegley429bb272011-04-08 18:41:53 +00001580 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001581
Chandler Carruthdb4325b2010-07-18 07:23:17 +00001582 // Change the result type of the call to match the original value type. This
1583 // is arbitrary, but the codegen for these builtins ins design to handle it
1584 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +00001585 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001586
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001587 return TheCallResult;
Chris Lattner5caa3702009-05-08 06:58:22 +00001588}
1589
Chris Lattner69039812009-02-18 06:01:06 +00001590/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00001591/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00001592/// Note: It might also make sense to do the UTF-16 conversion here (would
1593/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00001594bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00001595 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00001596 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1597
Douglas Gregor5cee1192011-07-27 05:40:30 +00001598 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001599 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1600 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001601 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001602 }
Mike Stump1eb44332009-09-09 15:08:12 +00001603
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001604 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001605 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001606 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001607 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divacky31ba6132012-09-06 15:59:27 +00001608 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001609 UTF16 *ToPtr = &ToBuf[0];
1610
1611 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1612 &ToPtr, ToPtr + NumBytes,
1613 strictConversion);
1614 // Check for conversion failure.
1615 if (Result != conversionOK)
1616 Diag(Arg->getLocStart(),
1617 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1618 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001619 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00001620}
1621
Chris Lattnerc27c6652007-12-20 00:05:45 +00001622/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1623/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00001624bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1625 Expr *Fn = TheCall->getCallee();
1626 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001627 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001628 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001629 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1630 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00001631 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001632 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00001633 return true;
1634 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00001635
1636 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00001637 return Diag(TheCall->getLocEnd(),
1638 diag::err_typecheck_call_too_few_args_at_least)
1639 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00001640 }
1641
John McCall5f8d6042011-08-27 01:09:30 +00001642 // Type-check the first argument normally.
1643 if (checkBuiltinArgument(*this, TheCall, 0))
1644 return true;
1645
Chris Lattnerc27c6652007-12-20 00:05:45 +00001646 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001647 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00001648 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001649 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00001650 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00001651 else if (FunctionDecl *FD = getCurFunctionDecl())
1652 isVariadic = FD->isVariadic();
1653 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001654 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00001655
Chris Lattnerc27c6652007-12-20 00:05:45 +00001656 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001657 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1658 return true;
1659 }
Mike Stump1eb44332009-09-09 15:08:12 +00001660
Chris Lattner30ce3442007-12-19 23:59:04 +00001661 // Verify that the second argument to the builtin is the last argument of the
1662 // current function or method.
1663 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00001664 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001665
Nico Weberb07d4482013-05-24 23:31:57 +00001666 // These are valid if SecondArgIsLastNamedArgument is false after the next
1667 // block.
1668 QualType Type;
1669 SourceLocation ParamLoc;
1670
Anders Carlsson88cf2262008-02-11 04:20:54 +00001671 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1672 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001673 // FIXME: This isn't correct for methods (results in bogus warning).
1674 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00001675 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001676 if (CurBlock)
1677 LastArg = *(CurBlock->TheDecl->param_end()-1);
1678 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00001679 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001680 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001681 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001682 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weberb07d4482013-05-24 23:31:57 +00001683
1684 Type = PV->getType();
1685 ParamLoc = PV->getLocation();
Chris Lattner30ce3442007-12-19 23:59:04 +00001686 }
1687 }
Mike Stump1eb44332009-09-09 15:08:12 +00001688
Chris Lattner30ce3442007-12-19 23:59:04 +00001689 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001690 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00001691 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weberb07d4482013-05-24 23:31:57 +00001692 else if (Type->isReferenceType()) {
1693 Diag(Arg->getLocStart(),
1694 diag::warn_va_start_of_reference_type_is_undefined);
1695 Diag(ParamLoc, diag::note_parameter_type) << Type;
1696 }
1697
Enea Zaffanella54de9bb2013-11-07 08:14:26 +00001698 TheCall->setType(Context.VoidTy);
Chris Lattner30ce3442007-12-19 23:59:04 +00001699 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00001700}
Chris Lattner30ce3442007-12-19 23:59:04 +00001701
Chris Lattner1b9a0792007-12-20 00:26:33 +00001702/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1703/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00001704bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1705 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001706 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001707 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001708 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001709 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001710 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001711 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001712 << SourceRange(TheCall->getArg(2)->getLocStart(),
1713 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001714
John Wiegley429bb272011-04-08 18:41:53 +00001715 ExprResult OrigArg0 = TheCall->getArg(0);
1716 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001717
Chris Lattner1b9a0792007-12-20 00:26:33 +00001718 // Do standard promotions between the two arguments, returning their common
1719 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001720 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001721 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1722 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001723
1724 // Make sure any conversions are pushed back into the call; this is
1725 // type safe since unordered compare builtins are declared as "_Bool
1726 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001727 TheCall->setArg(0, OrigArg0.get());
1728 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001729
John Wiegley429bb272011-04-08 18:41:53 +00001730 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001731 return false;
1732
Chris Lattner1b9a0792007-12-20 00:26:33 +00001733 // If the common type isn't a real floating type, then the arguments were
1734 // invalid for this operation.
Eli Friedman860a3192012-06-16 02:19:17 +00001735 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001736 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001737 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001738 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1739 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001740
Chris Lattner1b9a0792007-12-20 00:26:33 +00001741 return false;
1742}
1743
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001744/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1745/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001746/// to check everything. We expect the last argument to be a floating point
1747/// value.
1748bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1749 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001750 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001751 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001752 if (TheCall->getNumArgs() > NumArgs)
1753 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001754 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001755 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001756 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001757 (*(TheCall->arg_end()-1))->getLocEnd());
1758
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001759 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001760
Eli Friedman9ac6f622009-08-31 20:06:00 +00001761 if (OrigArg->isTypeDependent())
1762 return false;
1763
Chris Lattner81368fb2010-05-06 05:50:07 +00001764 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001765 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001766 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001767 diag::err_typecheck_call_invalid_unary_fp)
1768 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001769
Chris Lattner81368fb2010-05-06 05:50:07 +00001770 // If this is an implicit conversion from float -> double, remove it.
1771 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1772 Expr *CastArg = Cast->getSubExpr();
1773 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1774 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1775 "promotion from float to double is the only expected cast here");
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001776 Cast->setSubExpr(nullptr);
Chris Lattner81368fb2010-05-06 05:50:07 +00001777 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner81368fb2010-05-06 05:50:07 +00001778 }
1779 }
1780
Eli Friedman9ac6f622009-08-31 20:06:00 +00001781 return false;
1782}
1783
Eli Friedmand38617c2008-05-14 19:38:39 +00001784/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1785// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001786ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001787 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001788 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001789 diag::err_typecheck_call_too_few_args_at_least)
Craig Topperb44545a2013-07-28 21:50:10 +00001790 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1791 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001792
Nate Begeman37b6a572010-06-08 00:16:34 +00001793 // Determine which of the following types of shufflevector we're checking:
1794 // 1) unary, vector mask: (lhs, mask)
1795 // 2) binary, vector mask: (lhs, rhs, mask)
1796 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1797 QualType resType = TheCall->getArg(0)->getType();
1798 unsigned numElements = 0;
Craig Toppere3fbbe92013-07-19 04:46:31 +00001799
Douglas Gregorcde01732009-05-19 22:10:17 +00001800 if (!TheCall->getArg(0)->isTypeDependent() &&
1801 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001802 QualType LHSType = TheCall->getArg(0)->getType();
1803 QualType RHSType = TheCall->getArg(1)->getType();
Craig Toppere3fbbe92013-07-19 04:46:31 +00001804
Craig Topperbbe759c2013-07-29 06:47:04 +00001805 if (!LHSType->isVectorType() || !RHSType->isVectorType())
1806 return ExprError(Diag(TheCall->getLocStart(),
1807 diag::err_shufflevector_non_vector)
1808 << SourceRange(TheCall->getArg(0)->getLocStart(),
1809 TheCall->getArg(1)->getLocEnd()));
Craig Toppere3fbbe92013-07-19 04:46:31 +00001810
Nate Begeman37b6a572010-06-08 00:16:34 +00001811 numElements = LHSType->getAs<VectorType>()->getNumElements();
1812 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001813
Nate Begeman37b6a572010-06-08 00:16:34 +00001814 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1815 // with mask. If so, verify that RHS is an integer vector type with the
1816 // same number of elts as lhs.
1817 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru4cb3d902013-07-06 08:00:09 +00001818 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001819 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbbe759c2013-07-29 06:47:04 +00001820 return ExprError(Diag(TheCall->getLocStart(),
1821 diag::err_shufflevector_incompatible_vector)
1822 << SourceRange(TheCall->getArg(1)->getLocStart(),
1823 TheCall->getArg(1)->getLocEnd()));
Craig Toppere3fbbe92013-07-19 04:46:31 +00001824 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbbe759c2013-07-29 06:47:04 +00001825 return ExprError(Diag(TheCall->getLocStart(),
1826 diag::err_shufflevector_incompatible_vector)
1827 << SourceRange(TheCall->getArg(0)->getLocStart(),
1828 TheCall->getArg(1)->getLocEnd()));
Nate Begeman37b6a572010-06-08 00:16:34 +00001829 } else if (numElements != numResElements) {
1830 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001831 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001832 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001833 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001834 }
1835
1836 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001837 if (TheCall->getArg(i)->isTypeDependent() ||
1838 TheCall->getArg(i)->isValueDependent())
1839 continue;
1840
Nate Begeman37b6a572010-06-08 00:16:34 +00001841 llvm::APSInt Result(32);
1842 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1843 return ExprError(Diag(TheCall->getLocStart(),
Craig Topperb44545a2013-07-28 21:50:10 +00001844 diag::err_shufflevector_nonconstant_argument)
1845 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001846
Craig Topper6f4f8082013-08-03 17:40:38 +00001847 // Allow -1 which will be translated to undef in the IR.
1848 if (Result.isSigned() && Result.isAllOnesValue())
1849 continue;
1850
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001851 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001852 return ExprError(Diag(TheCall->getLocStart(),
Craig Topperb44545a2013-07-28 21:50:10 +00001853 diag::err_shufflevector_argument_too_large)
1854 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001855 }
1856
Chris Lattner5f9e2722011-07-23 10:55:15 +00001857 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001858
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001859 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001860 exprs.push_back(TheCall->getArg(i));
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001861 TheCall->setArg(i, nullptr);
Eli Friedmand38617c2008-05-14 19:38:39 +00001862 }
1863
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001864 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001865 TheCall->getCallee()->getLocStart(),
1866 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001867}
Chris Lattner30ce3442007-12-19 23:59:04 +00001868
Hal Finkel414a1bd2013-09-18 03:29:45 +00001869/// SemaConvertVectorExpr - Handle __builtin_convertvector
1870ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
1871 SourceLocation BuiltinLoc,
1872 SourceLocation RParenLoc) {
1873 ExprValueKind VK = VK_RValue;
1874 ExprObjectKind OK = OK_Ordinary;
1875 QualType DstTy = TInfo->getType();
1876 QualType SrcTy = E->getType();
1877
1878 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
1879 return ExprError(Diag(BuiltinLoc,
1880 diag::err_convertvector_non_vector)
1881 << E->getSourceRange());
1882 if (!DstTy->isVectorType() && !DstTy->isDependentType())
1883 return ExprError(Diag(BuiltinLoc,
1884 diag::err_convertvector_non_vector_type));
1885
1886 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
1887 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
1888 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
1889 if (SrcElts != DstElts)
1890 return ExprError(Diag(BuiltinLoc,
1891 diag::err_convertvector_incompatible_vector)
1892 << E->getSourceRange());
1893 }
1894
1895 return Owned(new (Context) ConvertVectorExpr(E, TInfo, DstTy, VK, OK,
1896 BuiltinLoc, RParenLoc));
1897
1898}
1899
Daniel Dunbar4493f792008-07-21 22:59:13 +00001900/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1901// This is declared to take (const void*, ...) and can take two
1902// optional constant int args.
1903bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001904 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001905
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001906 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001907 return Diag(TheCall->getLocEnd(),
1908 diag::err_typecheck_call_too_many_args_at_most)
1909 << 0 /*function call*/ << 3 << NumArgs
1910 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001911
1912 // Argument 0 is checked for us and the remaining arguments must be
1913 // constant integers.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001914 for (unsigned i = 1; i != NumArgs; ++i)
1915 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher691ebc32010-04-17 02:26:23 +00001916 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001917
Stephen Hines651f13c2014-04-23 16:59:28 -07001918 return false;
1919}
1920
Eric Christopher691ebc32010-04-17 02:26:23 +00001921/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1922/// TheCall is a constant expression.
1923bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1924 llvm::APSInt &Result) {
1925 Expr *Arg = TheCall->getArg(ArgNum);
1926 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1927 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1928
1929 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1930
1931 if (!Arg->isIntegerConstantExpr(Result, Context))
1932 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001933 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001934
Chris Lattner21fb98e2009-09-23 06:06:36 +00001935 return false;
1936}
1937
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001938/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
1939/// TheCall is a constant expression in the range [Low, High].
1940bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
1941 int Low, int High) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001942 llvm::APSInt Result;
Douglas Gregor592a4232012-06-29 01:05:22 +00001943
1944 // We can't check the value of a dependent argument.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001945 Expr *Arg = TheCall->getArg(ArgNum);
1946 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor592a4232012-06-29 01:05:22 +00001947 return false;
1948
Eric Christopher691ebc32010-04-17 02:26:23 +00001949 // Check constant-ness first.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001950 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher691ebc32010-04-17 02:26:23 +00001951 return true;
1952
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001953 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001954 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001955 << Low << High << Arg->getSourceRange();
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001956
1957 return false;
1958}
1959
Eli Friedman586d6a82009-05-03 06:04:26 +00001960/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001961/// This checks that val is a constant 1.
1962bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1963 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001964 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001965
Eric Christopher691ebc32010-04-17 02:26:23 +00001966 // TODO: This is less than ideal. Overload this to take a value.
1967 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1968 return true;
1969
1970 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001971 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1972 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1973
1974 return false;
1975}
1976
Richard Smith0e218972013-08-05 18:49:43 +00001977namespace {
1978enum StringLiteralCheckType {
1979 SLCT_NotALiteral,
1980 SLCT_UncheckedLiteral,
1981 SLCT_CheckedLiteral
1982};
1983}
1984
Richard Smith831421f2012-06-25 20:30:08 +00001985// Determine if an expression is a string literal or constant string.
1986// If this function returns false on the arguments to a function expecting a
1987// format string, we will usually need to emit a warning.
1988// True string literals are then checked by CheckFormatString.
Richard Smith0e218972013-08-05 18:49:43 +00001989static StringLiteralCheckType
1990checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
1991 bool HasVAListArg, unsigned format_idx,
1992 unsigned firstDataArg, Sema::FormatStringType Type,
1993 Sema::VariadicCallType CallType, bool InFunctionCall,
1994 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001995 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001996 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith831421f2012-06-25 20:30:08 +00001997 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001998
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001999 E = E->IgnoreParenCasts();
Peter Collingbournef111d932011-04-15 00:35:48 +00002000
Richard Smith0e218972013-08-05 18:49:43 +00002001 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikiea73cdcb2012-02-10 21:07:25 +00002002 // Technically -Wformat-nonliteral does not warn about this case.
2003 // The behavior of printf and friends in this case is implementation
2004 // dependent. Ideally if the format string cannot be null then
2005 // it should have a 'nonnull' attribute in the function prototype.
Richard Smith0e218972013-08-05 18:49:43 +00002006 return SLCT_UncheckedLiteral;
David Blaikiea73cdcb2012-02-10 21:07:25 +00002007
Ted Kremenekd30ef872009-01-12 23:09:09 +00002008 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00002009 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00002010 case Stmt::ConditionalOperatorClass: {
Richard Smith831421f2012-06-25 20:30:08 +00002011 // The expression is a literal if both sub-expressions were, and it was
2012 // completely checked only if both sub-expressions were checked.
2013 const AbstractConditionalOperator *C =
2014 cast<AbstractConditionalOperator>(E);
2015 StringLiteralCheckType Left =
Richard Smith0e218972013-08-05 18:49:43 +00002016 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00002017 HasVAListArg, format_idx, firstDataArg,
Richard Smith0e218972013-08-05 18:49:43 +00002018 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002019 if (Left == SLCT_NotALiteral)
2020 return SLCT_NotALiteral;
2021 StringLiteralCheckType Right =
Richard Smith0e218972013-08-05 18:49:43 +00002022 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00002023 HasVAListArg, format_idx, firstDataArg,
Richard Smith0e218972013-08-05 18:49:43 +00002024 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002025 return Left < Right ? Left : Right;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002026 }
2027
2028 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00002029 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2030 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002031 }
2032
John McCall56ca35d2011-02-17 10:25:35 +00002033 case Stmt::OpaqueValueExprClass:
2034 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2035 E = src;
2036 goto tryAgain;
2037 }
Richard Smith831421f2012-06-25 20:30:08 +00002038 return SLCT_NotALiteral;
John McCall56ca35d2011-02-17 10:25:35 +00002039
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00002040 case Stmt::PredefinedExprClass:
2041 // While __func__, etc., are technically not string literals, they
2042 // cannot contain format specifiers and thus are not a security
2043 // liability.
Richard Smith831421f2012-06-25 20:30:08 +00002044 return SLCT_UncheckedLiteral;
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00002045
Ted Kremenek082d9362009-03-20 21:35:28 +00002046 case Stmt::DeclRefExprClass: {
2047 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002048
Ted Kremenek082d9362009-03-20 21:35:28 +00002049 // As an exception, do not flag errors for variables binding to
2050 // const string literals.
2051 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2052 bool isConstant = false;
2053 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00002054
Richard Smith0e218972013-08-05 18:49:43 +00002055 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2056 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002057 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smith0e218972013-08-05 18:49:43 +00002058 isConstant = T.isConstant(S.Context) &&
2059 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupase98e5b52012-01-25 10:35:33 +00002060 } else if (T->isObjCObjectPointerType()) {
2061 // In ObjC, there is usually no "const ObjectPointer" type,
2062 // so don't check if the pointee type is constant.
Richard Smith0e218972013-08-05 18:49:43 +00002063 isConstant = T.isConstant(S.Context);
Ted Kremenek082d9362009-03-20 21:35:28 +00002064 }
Mike Stump1eb44332009-09-09 15:08:12 +00002065
Ted Kremenek082d9362009-03-20 21:35:28 +00002066 if (isConstant) {
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00002067 if (const Expr *Init = VD->getAnyInitializer()) {
2068 // Look through initializers like const char c[] = { "foo" }
2069 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2070 if (InitList->isStringLiteralInit())
2071 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2072 }
Richard Smith0e218972013-08-05 18:49:43 +00002073 return checkFormatStringExpr(S, Init, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002074 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002075 firstDataArg, Type, CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002076 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00002077 }
Ted Kremenek082d9362009-03-20 21:35:28 +00002078 }
Mike Stump1eb44332009-09-09 15:08:12 +00002079
Anders Carlssond966a552009-06-28 19:55:58 +00002080 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2081 // special check to see if the format string is a function parameter
2082 // of the function calling the printf function. If the function
2083 // has an attribute indicating it is a printf-like function, then we
2084 // should suppress warnings concerning non-literals being used in a call
2085 // to a vprintf function. For example:
2086 //
2087 // void
2088 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2089 // va_list ap;
2090 // va_start(ap, fmt);
2091 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2092 // ...
Richard Smith0e218972013-08-05 18:49:43 +00002093 // }
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00002094 if (HasVAListArg) {
2095 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2096 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2097 int PVIndex = PV->getFunctionScopeIndex() + 1;
Stephen Hines651f13c2014-04-23 16:59:28 -07002098 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00002099 // adjust for implicit parameter
2100 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2101 if (MD->isInstance())
2102 ++PVIndex;
2103 // We also check if the formats are compatible.
2104 // We can't pass a 'scanf' string to a 'printf' function.
2105 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smith0e218972013-08-05 18:49:43 +00002106 Type == S.GetFormatStringType(PVFormat))
Richard Smith831421f2012-06-25 20:30:08 +00002107 return SLCT_UncheckedLiteral;
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00002108 }
2109 }
2110 }
2111 }
Ted Kremenek082d9362009-03-20 21:35:28 +00002112 }
Mike Stump1eb44332009-09-09 15:08:12 +00002113
Richard Smith831421f2012-06-25 20:30:08 +00002114 return SLCT_NotALiteral;
Ted Kremenek082d9362009-03-20 21:35:28 +00002115 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00002116
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00002117 case Stmt::CallExprClass:
2118 case Stmt::CXXMemberCallExprClass: {
Anders Carlsson8f031b32009-06-27 04:05:33 +00002119 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00002120 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2121 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2122 unsigned ArgIndex = FA->getFormatIdx();
2123 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2124 if (MD->isInstance())
2125 --ArgIndex;
2126 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00002127
Richard Smith0e218972013-08-05 18:49:43 +00002128 return checkFormatStringExpr(S, Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002129 HasVAListArg, format_idx, firstDataArg,
Richard Smith0e218972013-08-05 18:49:43 +00002130 Type, CallType, InFunctionCall,
2131 CheckedVarArgs);
Jordan Rose50687312012-06-04 23:52:23 +00002132 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2133 unsigned BuiltinID = FD->getBuiltinID();
2134 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2135 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2136 const Expr *Arg = CE->getArg(0);
Richard Smith0e218972013-08-05 18:49:43 +00002137 return checkFormatStringExpr(S, Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002138 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002139 firstDataArg, Type, CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002140 InFunctionCall, CheckedVarArgs);
Jordan Rose50687312012-06-04 23:52:23 +00002141 }
Anders Carlsson8f031b32009-06-27 04:05:33 +00002142 }
2143 }
Mike Stump1eb44332009-09-09 15:08:12 +00002144
Richard Smith831421f2012-06-25 20:30:08 +00002145 return SLCT_NotALiteral;
Anders Carlsson8f031b32009-06-27 04:05:33 +00002146 }
Ted Kremenek082d9362009-03-20 21:35:28 +00002147 case Stmt::ObjCStringLiteralClass:
2148 case Stmt::StringLiteralClass: {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002149 const StringLiteral *StrE = nullptr;
Mike Stump1eb44332009-09-09 15:08:12 +00002150
Ted Kremenek082d9362009-03-20 21:35:28 +00002151 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00002152 StrE = ObjCFExpr->getString();
2153 else
Ted Kremenek082d9362009-03-20 21:35:28 +00002154 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002155
Ted Kremenekd30ef872009-01-12 23:09:09 +00002156 if (StrE) {
Richard Smith0e218972013-08-05 18:49:43 +00002157 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2158 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002159 return SLCT_CheckedLiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002160 }
Mike Stump1eb44332009-09-09 15:08:12 +00002161
Richard Smith831421f2012-06-25 20:30:08 +00002162 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002163 }
Mike Stump1eb44332009-09-09 15:08:12 +00002164
Ted Kremenek082d9362009-03-20 21:35:28 +00002165 default:
Richard Smith831421f2012-06-25 20:30:08 +00002166 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002167 }
2168}
2169
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002170Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmancaa5ab22013-09-03 21:02:22 +00002171 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002172 .Case("scanf", FST_Scanf)
2173 .Cases("printf", "printf0", FST_Printf)
2174 .Cases("NSString", "CFString", FST_NSString)
2175 .Case("strftime", FST_Strftime)
2176 .Case("strfmon", FST_Strfmon)
2177 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2178 .Default(FST_Unknown);
2179}
2180
Jordan Roseddcfbc92012-07-19 18:10:23 +00002181/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek826a3452010-07-16 02:11:22 +00002182/// functions) for correct use of format strings.
Richard Smith831421f2012-06-25 20:30:08 +00002183/// Returns true if a format string has been fully checked.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002184bool Sema::CheckFormatArguments(const FormatAttr *Format,
2185 ArrayRef<const Expr *> Args,
2186 bool IsCXXMember,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002187 VariadicCallType CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002188 SourceLocation Loc, SourceRange Range,
2189 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith831421f2012-06-25 20:30:08 +00002190 FormatStringInfo FSI;
2191 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002192 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith831421f2012-06-25 20:30:08 +00002193 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smith0e218972013-08-05 18:49:43 +00002194 CallType, Loc, Range, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002195 return false;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002196}
Sebastian Redl4a2614e2009-11-17 18:02:24 +00002197
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002198bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002199 bool HasVAListArg, unsigned format_idx,
2200 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002201 VariadicCallType CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002202 SourceLocation Loc, SourceRange Range,
2203 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002204 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002205 if (format_idx >= Args.size()) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002206 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith831421f2012-06-25 20:30:08 +00002207 return false;
Ted Kremenek71895b92007-08-14 17:39:48 +00002208 }
Mike Stump1eb44332009-09-09 15:08:12 +00002209
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002210 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00002211
Chris Lattner59907c42007-08-10 20:18:51 +00002212 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00002213 //
Ted Kremenek71895b92007-08-14 17:39:48 +00002214 // Dynamically generated format strings are difficult to
2215 // automatically vet at compile time. Requiring that format strings
2216 // are string literals: (1) permits the checking of format strings by
2217 // the compiler and thereby (2) can practically remove the source of
2218 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002219
Mike Stump1eb44332009-09-09 15:08:12 +00002220 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002221 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00002222 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002223 // the same format string checking logic for both ObjC and C strings.
Richard Smith831421f2012-06-25 20:30:08 +00002224 StringLiteralCheckType CT =
Richard Smith0e218972013-08-05 18:49:43 +00002225 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2226 format_idx, firstDataArg, Type, CallType,
2227 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002228 if (CT != SLCT_NotALiteral)
2229 // Literal format string found, check done!
2230 return CT == SLCT_CheckedLiteral;
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002231
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00002232 // Strftime is particular as it always uses a single 'time' argument,
2233 // so it is safe to pass a non-literal string.
2234 if (Type == FST_Strftime)
Richard Smith831421f2012-06-25 20:30:08 +00002235 return false;
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00002236
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00002237 // Do not emit diag when the string param is a macro expansion and the
2238 // format is either NSString or CFString. This is a hack to prevent
2239 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2240 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupasdc170202012-05-04 21:08:08 +00002241 if (Type == FST_NSString &&
2242 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith831421f2012-06-25 20:30:08 +00002243 return false;
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00002244
Chris Lattner655f1412009-04-29 04:59:47 +00002245 // If there are no arguments specified, warn with -Wformat-security, otherwise
2246 // warn only with -Wformat-nonliteral.
Eli Friedman2243e782013-06-18 18:10:01 +00002247 if (Args.size() == firstDataArg)
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002248 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00002249 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00002250 << OrigFormatExpr->getSourceRange();
2251 else
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002252 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00002253 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00002254 << OrigFormatExpr->getSourceRange();
Richard Smith831421f2012-06-25 20:30:08 +00002255 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002256}
Ted Kremenek71895b92007-08-14 17:39:48 +00002257
Ted Kremeneke0e53132010-01-28 23:39:18 +00002258namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00002259class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2260protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00002261 Sema &S;
2262 const StringLiteral *FExpr;
2263 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00002264 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00002265 const unsigned NumDataArgs;
Ted Kremeneke0e53132010-01-28 23:39:18 +00002266 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00002267 const bool HasVAListArg;
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002268 ArrayRef<const Expr *> Args;
Ted Kremenek0d277352010-01-29 01:06:55 +00002269 unsigned FormatIdx;
Richard Smith0e218972013-08-05 18:49:43 +00002270 llvm::SmallBitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00002271 bool usesPositionalArgs;
2272 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00002273 bool inFunctionCall;
Jordan Roseddcfbc92012-07-19 18:10:23 +00002274 Sema::VariadicCallType CallType;
Richard Smith0e218972013-08-05 18:49:43 +00002275 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002276public:
Ted Kremenek826a3452010-07-16 02:11:22 +00002277 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00002278 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002279 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002280 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002281 unsigned formatIdx, bool inFunctionCall,
Richard Smith0e218972013-08-05 18:49:43 +00002282 Sema::VariadicCallType callType,
2283 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremeneke0e53132010-01-28 23:39:18 +00002284 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose50687312012-06-04 23:52:23 +00002285 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2286 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002287 Args(Args), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00002288 usesPositionalArgs(false), atFirstArg(true),
Richard Smith0e218972013-08-05 18:49:43 +00002289 inFunctionCall(inFunctionCall), CallType(callType),
2290 CheckedVarArgs(CheckedVarArgs) {
2291 CoveredArgs.resize(numDataArgs);
2292 CoveredArgs.reset();
2293 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002294
Ted Kremenek07d161f2010-01-29 01:50:07 +00002295 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002296
Ted Kremenek826a3452010-07-16 02:11:22 +00002297 void HandleIncompleteSpecifier(const char *startSpecifier,
Stephen Hines651f13c2014-04-23 16:59:28 -07002298 unsigned specifierLen) override;
Hans Wennborg76517422012-02-22 10:17:01 +00002299
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002300 void HandleInvalidLengthModifier(
Stephen Hines651f13c2014-04-23 16:59:28 -07002301 const analyze_format_string::FormatSpecifier &FS,
2302 const analyze_format_string::ConversionSpecifier &CS,
2303 const char *startSpecifier, unsigned specifierLen,
2304 unsigned DiagID);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002305
Hans Wennborg76517422012-02-22 10:17:01 +00002306 void HandleNonStandardLengthModifier(
Stephen Hines651f13c2014-04-23 16:59:28 -07002307 const analyze_format_string::FormatSpecifier &FS,
2308 const char *startSpecifier, unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00002309
2310 void HandleNonStandardConversionSpecifier(
Stephen Hines651f13c2014-04-23 16:59:28 -07002311 const analyze_format_string::ConversionSpecifier &CS,
2312 const char *startSpecifier, unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00002313
Stephen Hines651f13c2014-04-23 16:59:28 -07002314 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgf8562642012-03-09 10:10:54 +00002315
Stephen Hines651f13c2014-04-23 16:59:28 -07002316 void HandleInvalidPosition(const char *startSpecifier,
2317 unsigned specifierLen,
2318 analyze_format_string::PositionContext p) override;
Ted Kremenekefaff192010-02-27 01:41:03 +00002319
Stephen Hines651f13c2014-04-23 16:59:28 -07002320 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekefaff192010-02-27 01:41:03 +00002321
Stephen Hines651f13c2014-04-23 16:59:28 -07002322 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002323
Richard Trieu55733de2011-10-28 00:41:25 +00002324 template <typename Range>
2325 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2326 const Expr *ArgumentExpr,
2327 PartialDiagnostic PDiag,
2328 SourceLocation StringLoc,
2329 bool IsStringLocation, Range StringRange,
Dmitri Gribenko55431692013-05-05 00:41:58 +00002330 ArrayRef<FixItHint> Fixit = None);
Richard Trieu55733de2011-10-28 00:41:25 +00002331
Ted Kremenek826a3452010-07-16 02:11:22 +00002332protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002333 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2334 const char *startSpec,
2335 unsigned specifierLen,
2336 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00002337
2338 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2339 const char *startSpec,
2340 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002341
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002342 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00002343 CharSourceRange getSpecifierRange(const char *startSpecifier,
2344 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002345 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002346
Ted Kremenek0d277352010-01-29 01:06:55 +00002347 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00002348
2349 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2350 const analyze_format_string::ConversionSpecifier &CS,
2351 const char *startSpecifier, unsigned specifierLen,
2352 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00002353
2354 template <typename Range>
2355 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2356 bool IsStringLocation, Range StringRange,
Dmitri Gribenko55431692013-05-05 00:41:58 +00002357 ArrayRef<FixItHint> Fixit = None);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002358};
2359}
2360
Ted Kremenek826a3452010-07-16 02:11:22 +00002361SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00002362 return OrigFormatExpr->getSourceRange();
2363}
2364
Ted Kremenek826a3452010-07-16 02:11:22 +00002365CharSourceRange CheckFormatHandler::
2366getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002367 SourceLocation Start = getLocationOfByte(startSpecifier);
2368 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2369
2370 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002371 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00002372
2373 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002374}
2375
Ted Kremenek826a3452010-07-16 02:11:22 +00002376SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002377 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002378}
2379
Ted Kremenek826a3452010-07-16 02:11:22 +00002380void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2381 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00002382 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2383 getLocationOfByte(startSpecifier),
2384 /*IsStringLocation*/true,
2385 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00002386}
2387
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002388void CheckFormatHandler::HandleInvalidLengthModifier(
2389 const analyze_format_string::FormatSpecifier &FS,
2390 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00002391 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002392 using namespace analyze_format_string;
2393
2394 const LengthModifier &LM = FS.getLengthModifier();
2395 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2396
2397 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002398 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002399 if (FixedLM) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002400 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002401 getLocationOfByte(LM.getStart()),
2402 /*IsStringLocation*/true,
2403 getSpecifierRange(startSpecifier, specifierLen));
2404
2405 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2406 << FixedLM->toString()
2407 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2408
2409 } else {
Jordan Rose8be066e2012-09-08 04:00:12 +00002410 FixItHint Hint;
2411 if (DiagID == diag::warn_format_nonsensical_length)
2412 Hint = FixItHint::CreateRemoval(LMRange);
2413
2414 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002415 getLocationOfByte(LM.getStart()),
2416 /*IsStringLocation*/true,
2417 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose8be066e2012-09-08 04:00:12 +00002418 Hint);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002419 }
2420}
2421
Hans Wennborg76517422012-02-22 10:17:01 +00002422void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00002423 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00002424 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002425 using namespace analyze_format_string;
2426
2427 const LengthModifier &LM = FS.getLengthModifier();
2428 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2429
2430 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002431 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose8be066e2012-09-08 04:00:12 +00002432 if (FixedLM) {
2433 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2434 << LM.toString() << 0,
2435 getLocationOfByte(LM.getStart()),
2436 /*IsStringLocation*/true,
2437 getSpecifierRange(startSpecifier, specifierLen));
2438
2439 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2440 << FixedLM->toString()
2441 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2442
2443 } else {
2444 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2445 << LM.toString() << 0,
2446 getLocationOfByte(LM.getStart()),
2447 /*IsStringLocation*/true,
2448 getSpecifierRange(startSpecifier, specifierLen));
2449 }
Hans Wennborg76517422012-02-22 10:17:01 +00002450}
2451
2452void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2453 const analyze_format_string::ConversionSpecifier &CS,
2454 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose670941c2012-09-13 02:11:15 +00002455 using namespace analyze_format_string;
2456
2457 // See if we know how to fix this conversion specifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002458 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose670941c2012-09-13 02:11:15 +00002459 if (FixedCS) {
2460 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2461 << CS.toString() << /*conversion specifier*/1,
2462 getLocationOfByte(CS.getStart()),
2463 /*IsStringLocation*/true,
2464 getSpecifierRange(startSpecifier, specifierLen));
2465
2466 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2467 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2468 << FixedCS->toString()
2469 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2470 } else {
2471 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2472 << CS.toString() << /*conversion specifier*/1,
2473 getLocationOfByte(CS.getStart()),
2474 /*IsStringLocation*/true,
2475 getSpecifierRange(startSpecifier, specifierLen));
2476 }
Hans Wennborg76517422012-02-22 10:17:01 +00002477}
2478
Hans Wennborgf8562642012-03-09 10:10:54 +00002479void CheckFormatHandler::HandlePosition(const char *startPos,
2480 unsigned posLen) {
2481 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2482 getLocationOfByte(startPos),
2483 /*IsStringLocation*/true,
2484 getSpecifierRange(startPos, posLen));
2485}
2486
Ted Kremenekefaff192010-02-27 01:41:03 +00002487void
Ted Kremenek826a3452010-07-16 02:11:22 +00002488CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2489 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00002490 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2491 << (unsigned) p,
2492 getLocationOfByte(startPos), /*IsStringLocation*/true,
2493 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002494}
2495
Ted Kremenek826a3452010-07-16 02:11:22 +00002496void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00002497 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00002498 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2499 getLocationOfByte(startPos),
2500 /*IsStringLocation*/true,
2501 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002502}
2503
Ted Kremenek826a3452010-07-16 02:11:22 +00002504void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose50687312012-06-04 23:52:23 +00002505 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0c069442011-03-15 21:18:48 +00002506 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00002507 EmitFormatDiagnostic(
2508 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2509 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2510 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00002511 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002512}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002513
Jordan Rose48716662012-07-19 18:10:08 +00002514// Note that this may return NULL if there was an error parsing or building
2515// one of the argument expressions.
Ted Kremenek826a3452010-07-16 02:11:22 +00002516const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002517 return Args[FirstDataArg + i];
Ted Kremenek826a3452010-07-16 02:11:22 +00002518}
2519
2520void CheckFormatHandler::DoneProcessing() {
2521 // Does the number of data arguments exceed the number of
2522 // format conversions in the format string?
2523 if (!HasVAListArg) {
2524 // Find any arguments that weren't covered.
2525 CoveredArgs.flip();
2526 signed notCoveredArg = CoveredArgs.find_first();
2527 if (notCoveredArg >= 0) {
2528 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose48716662012-07-19 18:10:08 +00002529 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2530 SourceLocation Loc = E->getLocStart();
2531 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2532 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2533 Loc, /*IsStringLocation*/false,
2534 getFormatStringRange());
2535 }
Bob Wilsonc03f2df2012-05-03 19:47:19 +00002536 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002537 }
2538 }
2539}
2540
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002541bool
2542CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2543 SourceLocation Loc,
2544 const char *startSpec,
2545 unsigned specifierLen,
2546 const char *csStart,
2547 unsigned csLen) {
2548
2549 bool keepGoing = true;
2550 if (argIndex < NumDataArgs) {
2551 // Consider the argument coverered, even though the specifier doesn't
2552 // make sense.
2553 CoveredArgs.set(argIndex);
2554 }
2555 else {
2556 // If argIndex exceeds the number of data arguments we
2557 // don't issue a warning because that is just a cascade of warnings (and
2558 // they may have intended '%%' anyway). We don't want to continue processing
2559 // the format string after this point, however, as we will like just get
2560 // gibberish when trying to match arguments.
2561 keepGoing = false;
2562 }
2563
Richard Trieu55733de2011-10-28 00:41:25 +00002564 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2565 << StringRef(csStart, csLen),
2566 Loc, /*IsStringLocation*/true,
2567 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002568
2569 return keepGoing;
2570}
2571
Richard Trieu55733de2011-10-28 00:41:25 +00002572void
2573CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2574 const char *startSpec,
2575 unsigned specifierLen) {
2576 EmitFormatDiagnostic(
2577 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2578 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2579}
2580
Ted Kremenek666a1972010-07-26 19:45:42 +00002581bool
2582CheckFormatHandler::CheckNumArgs(
2583 const analyze_format_string::FormatSpecifier &FS,
2584 const analyze_format_string::ConversionSpecifier &CS,
2585 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2586
2587 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002588 PartialDiagnostic PDiag = FS.usesPositionalArg()
2589 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2590 << (argIndex+1) << NumDataArgs)
2591 : S.PDiag(diag::warn_printf_insufficient_data_args);
2592 EmitFormatDiagnostic(
2593 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2594 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00002595 return false;
2596 }
2597 return true;
2598}
2599
Richard Trieu55733de2011-10-28 00:41:25 +00002600template<typename Range>
2601void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2602 SourceLocation Loc,
2603 bool IsStringLocation,
2604 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002605 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002606 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu55733de2011-10-28 00:41:25 +00002607 Loc, IsStringLocation, StringRange, FixIt);
2608}
2609
2610/// \brief If the format string is not within the funcion call, emit a note
2611/// so that the function call and string are in diagnostic messages.
2612///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002613/// \param InFunctionCall if true, the format string is within the function
Richard Trieu55733de2011-10-28 00:41:25 +00002614/// call and only one diagnostic message will be produced. Otherwise, an
2615/// extra note will be emitted pointing to location of the format string.
2616///
2617/// \param ArgumentExpr the expression that is passed as the format string
2618/// argument in the function call. Used for getting locations when two
2619/// diagnostics are emitted.
2620///
2621/// \param PDiag the callee should already have provided any strings for the
2622/// diagnostic message. This function only adds locations and fixits
2623/// to diagnostics.
2624///
2625/// \param Loc primary location for diagnostic. If two diagnostics are
2626/// required, one will be at Loc and a new SourceLocation will be created for
2627/// the other one.
2628///
2629/// \param IsStringLocation if true, Loc points to the format string should be
2630/// used for the note. Otherwise, Loc points to the argument list and will
2631/// be used with PDiag.
2632///
2633/// \param StringRange some or all of the string to highlight. This is
2634/// templated so it can accept either a CharSourceRange or a SourceRange.
2635///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002636/// \param FixIt optional fix it hint for the format string.
Richard Trieu55733de2011-10-28 00:41:25 +00002637template<typename Range>
2638void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2639 const Expr *ArgumentExpr,
2640 PartialDiagnostic PDiag,
2641 SourceLocation Loc,
2642 bool IsStringLocation,
2643 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002644 ArrayRef<FixItHint> FixIt) {
2645 if (InFunctionCall) {
2646 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2647 D << StringRange;
2648 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2649 I != E; ++I) {
2650 D << *I;
2651 }
2652 } else {
Richard Trieu55733de2011-10-28 00:41:25 +00002653 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2654 << ArgumentExpr->getSourceRange();
Jordan Roseec087352012-09-05 22:56:26 +00002655
2656 const Sema::SemaDiagnosticBuilder &Note =
2657 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2658 diag::note_format_string_defined);
2659
2660 Note << StringRange;
2661 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2662 I != E; ++I) {
2663 Note << *I;
2664 }
Richard Trieu55733de2011-10-28 00:41:25 +00002665 }
2666}
2667
Ted Kremenek826a3452010-07-16 02:11:22 +00002668//===--- CHECK: Printf format string checking ------------------------------===//
2669
2670namespace {
2671class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose50687312012-06-04 23:52:23 +00002672 bool ObjCContext;
Ted Kremenek826a3452010-07-16 02:11:22 +00002673public:
2674 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2675 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002676 unsigned numDataArgs, bool isObjC,
Ted Kremenek826a3452010-07-16 02:11:22 +00002677 const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002678 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002679 unsigned formatIdx, bool inFunctionCall,
Richard Smith0e218972013-08-05 18:49:43 +00002680 Sema::VariadicCallType CallType,
2681 llvm::SmallBitVector &CheckedVarArgs)
2682 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2683 numDataArgs, beg, hasVAListArg, Args,
2684 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
2685 ObjCContext(isObjC)
Jordan Roseddcfbc92012-07-19 18:10:23 +00002686 {}
2687
Stephen Hines651f13c2014-04-23 16:59:28 -07002688
Ted Kremenek826a3452010-07-16 02:11:22 +00002689 bool HandleInvalidPrintfConversionSpecifier(
2690 const analyze_printf::PrintfSpecifier &FS,
2691 const char *startSpecifier,
Stephen Hines651f13c2014-04-23 16:59:28 -07002692 unsigned specifierLen) override;
2693
Ted Kremenek826a3452010-07-16 02:11:22 +00002694 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2695 const char *startSpecifier,
Stephen Hines651f13c2014-04-23 16:59:28 -07002696 unsigned specifierLen) override;
Richard Smith831421f2012-06-25 20:30:08 +00002697 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2698 const char *StartSpecifier,
2699 unsigned SpecifierLen,
2700 const Expr *E);
2701
Ted Kremenek826a3452010-07-16 02:11:22 +00002702 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2703 const char *startSpecifier, unsigned specifierLen);
2704 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2705 const analyze_printf::OptionalAmount &Amt,
2706 unsigned type,
2707 const char *startSpecifier, unsigned specifierLen);
2708 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2709 const analyze_printf::OptionalFlag &flag,
2710 const char *startSpecifier, unsigned specifierLen);
2711 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2712 const analyze_printf::OptionalFlag &ignoredFlag,
2713 const analyze_printf::OptionalFlag &flag,
2714 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgf3749f42012-08-07 08:11:26 +00002715 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Stephen Hines651f13c2014-04-23 16:59:28 -07002716 const Expr *E);
Richard Smith831421f2012-06-25 20:30:08 +00002717
Ted Kremenek826a3452010-07-16 02:11:22 +00002718};
2719}
2720
2721bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2722 const analyze_printf::PrintfSpecifier &FS,
2723 const char *startSpecifier,
2724 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002725 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002726 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002727
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002728 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2729 getLocationOfByte(CS.getStart()),
2730 startSpecifier, specifierLen,
2731 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00002732}
2733
Ted Kremenek826a3452010-07-16 02:11:22 +00002734bool CheckPrintfHandler::HandleAmount(
2735 const analyze_format_string::OptionalAmount &Amt,
2736 unsigned k, const char *startSpecifier,
2737 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002738
2739 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002740 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002741 unsigned argIndex = Amt.getArgIndex();
2742 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002743 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2744 << k,
2745 getLocationOfByte(Amt.getStart()),
2746 /*IsStringLocation*/true,
2747 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002748 // Don't do any more checking. We will just emit
2749 // spurious errors.
2750 return false;
2751 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002752
Ted Kremenek0d277352010-01-29 01:06:55 +00002753 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00002754 // Although not in conformance with C99, we also allow the argument to be
2755 // an 'unsigned int' as that is a reasonably safe case. GCC also
2756 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002757 CoveredArgs.set(argIndex);
2758 const Expr *Arg = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00002759 if (!Arg)
2760 return false;
2761
Ted Kremenek0d277352010-01-29 01:06:55 +00002762 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002763
Hans Wennborgf3749f42012-08-07 08:11:26 +00002764 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2765 assert(AT.isValid());
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002766
Hans Wennborgf3749f42012-08-07 08:11:26 +00002767 if (!AT.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00002768 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgf3749f42012-08-07 08:11:26 +00002769 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00002770 << T << Arg->getSourceRange(),
2771 getLocationOfByte(Amt.getStart()),
2772 /*IsStringLocation*/true,
2773 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002774 // Don't do any more checking. We will just emit
2775 // spurious errors.
2776 return false;
2777 }
2778 }
2779 }
2780 return true;
2781}
Ted Kremenek0d277352010-01-29 01:06:55 +00002782
Tom Caree4ee9662010-06-17 19:00:27 +00002783void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00002784 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002785 const analyze_printf::OptionalAmount &Amt,
2786 unsigned type,
2787 const char *startSpecifier,
2788 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002789 const analyze_printf::PrintfConversionSpecifier &CS =
2790 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00002791
Richard Trieu55733de2011-10-28 00:41:25 +00002792 FixItHint fixit =
2793 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2794 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2795 Amt.getConstantLength()))
2796 : FixItHint();
2797
2798 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2799 << type << CS.toString(),
2800 getLocationOfByte(Amt.getStart()),
2801 /*IsStringLocation*/true,
2802 getSpecifierRange(startSpecifier, specifierLen),
2803 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00002804}
2805
Ted Kremenek826a3452010-07-16 02:11:22 +00002806void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002807 const analyze_printf::OptionalFlag &flag,
2808 const char *startSpecifier,
2809 unsigned specifierLen) {
2810 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002811 const analyze_printf::PrintfConversionSpecifier &CS =
2812 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00002813 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2814 << flag.toString() << CS.toString(),
2815 getLocationOfByte(flag.getPosition()),
2816 /*IsStringLocation*/true,
2817 getSpecifierRange(startSpecifier, specifierLen),
2818 FixItHint::CreateRemoval(
2819 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002820}
2821
2822void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00002823 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002824 const analyze_printf::OptionalFlag &ignoredFlag,
2825 const analyze_printf::OptionalFlag &flag,
2826 const char *startSpecifier,
2827 unsigned specifierLen) {
2828 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00002829 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2830 << ignoredFlag.toString() << flag.toString(),
2831 getLocationOfByte(ignoredFlag.getPosition()),
2832 /*IsStringLocation*/true,
2833 getSpecifierRange(startSpecifier, specifierLen),
2834 FixItHint::CreateRemoval(
2835 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002836}
2837
Richard Smith831421f2012-06-25 20:30:08 +00002838// Determines if the specified is a C++ class or struct containing
2839// a member with the specified name and kind (e.g. a CXXMethodDecl named
2840// "c_str()").
2841template<typename MemberKind>
2842static llvm::SmallPtrSet<MemberKind*, 1>
2843CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2844 const RecordType *RT = Ty->getAs<RecordType>();
2845 llvm::SmallPtrSet<MemberKind*, 1> Results;
2846
2847 if (!RT)
2848 return Results;
2849 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Stephen Hines651f13c2014-04-23 16:59:28 -07002850 if (!RD || !RD->getDefinition())
Richard Smith831421f2012-06-25 20:30:08 +00002851 return Results;
2852
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002853 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith831421f2012-06-25 20:30:08 +00002854 Sema::LookupMemberName);
Stephen Hines651f13c2014-04-23 16:59:28 -07002855 R.suppressDiagnostics();
Richard Smith831421f2012-06-25 20:30:08 +00002856
2857 // We just need to include all members of the right kind turned up by the
2858 // filter, at this point.
2859 if (S.LookupQualifiedName(R, RT->getDecl()))
2860 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2861 NamedDecl *decl = (*I)->getUnderlyingDecl();
2862 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2863 Results.insert(FK);
2864 }
2865 return Results;
2866}
2867
Stephen Hines651f13c2014-04-23 16:59:28 -07002868/// Check if we could call '.c_str()' on an object.
2869///
2870/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
2871/// allow the call, or if it would be ambiguous).
2872bool Sema::hasCStrMethod(const Expr *E) {
2873 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2874 MethodSet Results =
2875 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
2876 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2877 MI != ME; ++MI)
2878 if ((*MI)->getMinRequiredArguments() == 0)
2879 return true;
2880 return false;
2881}
2882
Richard Smith831421f2012-06-25 20:30:08 +00002883// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgf3749f42012-08-07 08:11:26 +00002884// better diagnostic if so. AT is assumed to be valid.
Richard Smith831421f2012-06-25 20:30:08 +00002885// Returns true when a c_str() conversion method is found.
2886bool CheckPrintfHandler::checkForCStrMembers(
Stephen Hines651f13c2014-04-23 16:59:28 -07002887 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith831421f2012-06-25 20:30:08 +00002888 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2889
2890 MethodSet Results =
2891 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2892
2893 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2894 MI != ME; ++MI) {
2895 const CXXMethodDecl *Method = *MI;
Stephen Hines651f13c2014-04-23 16:59:28 -07002896 if (Method->getMinRequiredArguments() == 0 &&
2897 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith831421f2012-06-25 20:30:08 +00002898 // FIXME: Suggest parens if the expression needs them.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002899 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith831421f2012-06-25 20:30:08 +00002900 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2901 << "c_str()"
2902 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2903 return true;
2904 }
2905 }
2906
2907 return false;
2908}
2909
Ted Kremeneke0e53132010-01-28 23:39:18 +00002910bool
Ted Kremenek826a3452010-07-16 02:11:22 +00002911CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002912 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00002913 const char *startSpecifier,
2914 unsigned specifierLen) {
2915
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002916 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00002917 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002918 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00002919
Ted Kremenekbaa40062010-07-19 22:01:06 +00002920 if (FS.consumesDataArgument()) {
2921 if (atFirstArg) {
2922 atFirstArg = false;
2923 usesPositionalArgs = FS.usesPositionalArg();
2924 }
2925 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002926 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2927 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002928 return false;
2929 }
Ted Kremenek0d277352010-01-29 01:06:55 +00002930 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002931
Ted Kremenekefaff192010-02-27 01:41:03 +00002932 // First check if the field width, precision, and conversion specifier
2933 // have matching data arguments.
2934 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2935 startSpecifier, specifierLen)) {
2936 return false;
2937 }
2938
2939 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2940 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002941 return false;
2942 }
2943
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002944 if (!CS.consumesDataArgument()) {
2945 // FIXME: Technically specifying a precision or field width here
2946 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002947 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002948 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002949
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002950 // Consume the argument.
2951 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00002952 if (argIndex < NumDataArgs) {
2953 // The check to see if the argIndex is valid will come later.
2954 // We set the bit here because we may exit early from this
2955 // function if we encounter some other error.
2956 CoveredArgs.set(argIndex);
2957 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002958
2959 // Check for using an Objective-C specific conversion specifier
2960 // in a non-ObjC literal.
Jordan Rose50687312012-06-04 23:52:23 +00002961 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002962 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2963 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002964 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002965
Tom Caree4ee9662010-06-17 19:00:27 +00002966 // Check for invalid use of field width
2967 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002968 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00002969 startSpecifier, specifierLen);
2970 }
2971
2972 // Check for invalid use of precision
2973 if (!FS.hasValidPrecision()) {
2974 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2975 startSpecifier, specifierLen);
2976 }
2977
2978 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00002979 if (!FS.hasValidThousandsGroupingPrefix())
2980 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002981 if (!FS.hasValidLeadingZeros())
2982 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2983 if (!FS.hasValidPlusPrefix())
2984 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00002985 if (!FS.hasValidSpacePrefix())
2986 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002987 if (!FS.hasValidAlternativeForm())
2988 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2989 if (!FS.hasValidLeftJustified())
2990 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2991
2992 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00002993 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2994 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2995 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002996 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2997 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2998 startSpecifier, specifierLen);
2999
3000 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003001 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00003002 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3003 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003004 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00003005 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003006 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00003007 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3008 diag::warn_format_non_standard_conversion_spec);
Tom Caree4ee9662010-06-17 19:00:27 +00003009
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003010 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3011 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3012
Ted Kremenekda51f0d2010-01-29 01:43:31 +00003013 // The remaining checks depend on the data arguments.
3014 if (HasVAListArg)
3015 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003016
Ted Kremenek666a1972010-07-26 19:45:42 +00003017 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00003018 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003019
Jordan Rose48716662012-07-19 18:10:08 +00003020 const Expr *Arg = getDataArg(argIndex);
3021 if (!Arg)
3022 return true;
3023
3024 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith831421f2012-06-25 20:30:08 +00003025}
3026
Jordan Roseec087352012-09-05 22:56:26 +00003027static bool requiresParensToAddCast(const Expr *E) {
3028 // FIXME: We should have a general way to reason about operator
3029 // precedence and whether parens are actually needed here.
3030 // Take care of a few common cases where they aren't.
3031 const Expr *Inside = E->IgnoreImpCasts();
3032 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3033 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3034
3035 switch (Inside->getStmtClass()) {
3036 case Stmt::ArraySubscriptExprClass:
3037 case Stmt::CallExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003038 case Stmt::CharacterLiteralClass:
3039 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00003040 case Stmt::DeclRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003041 case Stmt::FloatingLiteralClass:
3042 case Stmt::IntegerLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00003043 case Stmt::MemberExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003044 case Stmt::ObjCArrayLiteralClass:
3045 case Stmt::ObjCBoolLiteralExprClass:
3046 case Stmt::ObjCBoxedExprClass:
3047 case Stmt::ObjCDictionaryLiteralClass:
3048 case Stmt::ObjCEncodeExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00003049 case Stmt::ObjCIvarRefExprClass:
3050 case Stmt::ObjCMessageExprClass:
3051 case Stmt::ObjCPropertyRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003052 case Stmt::ObjCStringLiteralClass:
3053 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00003054 case Stmt::ParenExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003055 case Stmt::StringLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00003056 case Stmt::UnaryOperatorClass:
3057 return false;
3058 default:
3059 return true;
3060 }
3061}
3062
Richard Smith831421f2012-06-25 20:30:08 +00003063bool
3064CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3065 const char *StartSpecifier,
3066 unsigned SpecifierLen,
3067 const Expr *E) {
3068 using namespace analyze_format_string;
3069 using namespace analyze_printf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003070 // Now type check the data expression that matches the
3071 // format specifier.
Hans Wennborgf3749f42012-08-07 08:11:26 +00003072 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3073 ObjCContext);
Jordan Rose614a8652012-09-05 22:56:19 +00003074 if (!AT.isValid())
3075 return true;
Jordan Roseec087352012-09-05 22:56:26 +00003076
Jordan Rose448ac3e2012-12-05 18:44:40 +00003077 QualType ExprTy = E->getType();
Ted Kremenek02be9682013-04-10 06:26:26 +00003078 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3079 ExprTy = TET->getUnderlyingExpr()->getType();
3080 }
3081
Jordan Rose448ac3e2012-12-05 18:44:40 +00003082 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00003083 return true;
Jordan Roseee0259d2012-06-04 22:48:57 +00003084
Jordan Rose614a8652012-09-05 22:56:19 +00003085 // Look through argument promotions for our error message's reported type.
3086 // This includes the integral and floating promotions, but excludes array
3087 // and function pointer decay; seeing that an argument intended to be a
3088 // string has type 'char [6]' is probably more confusing than 'char *'.
3089 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3090 if (ICE->getCastKind() == CK_IntegralCast ||
3091 ICE->getCastKind() == CK_FloatingCast) {
3092 E = ICE->getSubExpr();
Jordan Rose448ac3e2012-12-05 18:44:40 +00003093 ExprTy = E->getType();
Jordan Rose614a8652012-09-05 22:56:19 +00003094
3095 // Check if we didn't match because of an implicit cast from a 'char'
3096 // or 'short' to an 'int'. This is done because printf is a varargs
3097 // function.
3098 if (ICE->getType() == S.Context.IntTy ||
3099 ICE->getType() == S.Context.UnsignedIntTy) {
3100 // All further checking is done on the subexpression.
Jordan Rose448ac3e2012-12-05 18:44:40 +00003101 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00003102 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00003103 }
Jordan Roseee0259d2012-06-04 22:48:57 +00003104 }
Jordan Rose448ac3e2012-12-05 18:44:40 +00003105 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3106 // Special case for 'a', which has type 'int' in C.
3107 // Note, however, that we do /not/ want to treat multibyte constants like
3108 // 'MooV' as characters! This form is deprecated but still exists.
3109 if (ExprTy == S.Context.IntTy)
3110 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3111 ExprTy = S.Context.CharTy;
Jordan Rose614a8652012-09-05 22:56:19 +00003112 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003113
Jordan Rose2cd34402012-12-05 18:44:49 +00003114 // %C in an Objective-C context prints a unichar, not a wchar_t.
3115 // If the argument is an integer of some kind, believe the %C and suggest
3116 // a cast instead of changing the conversion specifier.
Jordan Rose448ac3e2012-12-05 18:44:40 +00003117 QualType IntendedTy = ExprTy;
Jordan Rose2cd34402012-12-05 18:44:49 +00003118 if (ObjCContext &&
3119 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3120 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3121 !ExprTy->isCharType()) {
3122 // 'unichar' is defined as a typedef of unsigned short, but we should
3123 // prefer using the typedef if it is visible.
3124 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenek656465d2013-10-15 05:25:17 +00003125
3126 // While we are here, check if the value is an IntegerLiteral that happens
3127 // to be within the valid range.
3128 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3129 const llvm::APInt &V = IL->getValue();
3130 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3131 return true;
3132 }
3133
Jordan Rose2cd34402012-12-05 18:44:49 +00003134 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3135 Sema::LookupOrdinaryName);
3136 if (S.LookupName(Result, S.getCurScope())) {
3137 NamedDecl *ND = Result.getFoundDecl();
3138 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3139 if (TD->getUnderlyingType() == IntendedTy)
3140 IntendedTy = S.Context.getTypedefType(TD);
3141 }
3142 }
3143 }
3144
3145 // Special-case some of Darwin's platform-independence types by suggesting
3146 // casts to primitive types that are known to be large enough.
3147 bool ShouldNotPrintDirectly = false;
Jordan Roseec087352012-09-05 22:56:26 +00003148 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Ted Kremenek6edb0292013-03-25 22:28:37 +00003149 // Use a 'while' to peel off layers of typedefs.
3150 QualType TyTy = IntendedTy;
3151 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
Jordan Roseec087352012-09-05 22:56:26 +00003152 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose2cd34402012-12-05 18:44:49 +00003153 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseec087352012-09-05 22:56:26 +00003154 .Case("NSInteger", S.Context.LongTy)
3155 .Case("NSUInteger", S.Context.UnsignedLongTy)
3156 .Case("SInt32", S.Context.IntTy)
3157 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose2cd34402012-12-05 18:44:49 +00003158 .Default(QualType());
3159
3160 if (!CastTy.isNull()) {
3161 ShouldNotPrintDirectly = true;
3162 IntendedTy = CastTy;
Ted Kremenek6edb0292013-03-25 22:28:37 +00003163 break;
Jordan Rose2cd34402012-12-05 18:44:49 +00003164 }
Ted Kremenek6edb0292013-03-25 22:28:37 +00003165 TyTy = UserTy->desugar();
Jordan Roseec087352012-09-05 22:56:26 +00003166 }
3167 }
3168
Jordan Rose614a8652012-09-05 22:56:19 +00003169 // We may be able to offer a FixItHint if it is a supported type.
3170 PrintfSpecifier fixedFS = FS;
Jordan Roseec087352012-09-05 22:56:26 +00003171 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose614a8652012-09-05 22:56:19 +00003172 S.Context, ObjCContext);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003173
Jordan Rose614a8652012-09-05 22:56:19 +00003174 if (success) {
3175 // Get the fix string from the fixed format specifier
3176 SmallString<16> buf;
3177 llvm::raw_svector_ostream os(buf);
3178 fixedFS.toString(os);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003179
Jordan Roseec087352012-09-05 22:56:26 +00003180 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3181
Jordan Rose2cd34402012-12-05 18:44:49 +00003182 if (IntendedTy == ExprTy) {
3183 // In this case, the specifier is wrong and should be changed to match
3184 // the argument.
3185 EmitFormatDiagnostic(
3186 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3187 << AT.getRepresentativeTypeName(S.Context) << IntendedTy
3188 << E->getSourceRange(),
3189 E->getLocStart(),
3190 /*IsStringLocation*/false,
3191 SpecRange,
3192 FixItHint::CreateReplacement(SpecRange, os.str()));
3193
3194 } else {
Jordan Roseec087352012-09-05 22:56:26 +00003195 // The canonical type for formatting this value is different from the
3196 // actual type of the expression. (This occurs, for example, with Darwin's
3197 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3198 // should be printed as 'long' for 64-bit compatibility.)
3199 // Rather than emitting a normal format/argument mismatch, we want to
3200 // add a cast to the recommended type (and correct the format string
3201 // if necessary).
3202 SmallString<16> CastBuf;
3203 llvm::raw_svector_ostream CastFix(CastBuf);
3204 CastFix << "(";
3205 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3206 CastFix << ")";
3207
3208 SmallVector<FixItHint,4> Hints;
3209 if (!AT.matchesType(S.Context, IntendedTy))
3210 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3211
3212 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3213 // If there's already a cast present, just replace it.
3214 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3215 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3216
3217 } else if (!requiresParensToAddCast(E)) {
3218 // If the expression has high enough precedence,
3219 // just write the C-style cast.
3220 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3221 CastFix.str()));
3222 } else {
3223 // Otherwise, add parens around the expression as well as the cast.
3224 CastFix << "(";
3225 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3226 CastFix.str()));
3227
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003228 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseec087352012-09-05 22:56:26 +00003229 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3230 }
3231
Jordan Rose2cd34402012-12-05 18:44:49 +00003232 if (ShouldNotPrintDirectly) {
3233 // The expression has a type that should not be printed directly.
3234 // We extract the name from the typedef because we don't want to show
3235 // the underlying type in the diagnostic.
3236 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseec087352012-09-05 22:56:26 +00003237
Jordan Rose2cd34402012-12-05 18:44:49 +00003238 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
3239 << Name << IntendedTy
3240 << E->getSourceRange(),
3241 E->getLocStart(), /*IsStringLocation=*/false,
3242 SpecRange, Hints);
3243 } else {
3244 // In this case, the expression could be printed using a different
3245 // specifier, but we've decided that the specifier is probably correct
3246 // and we should cast instead. Just use the normal warning message.
3247 EmitFormatDiagnostic(
3248 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3249 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3250 << E->getSourceRange(),
3251 E->getLocStart(), /*IsStringLocation*/false,
3252 SpecRange, Hints);
3253 }
Jordan Roseec087352012-09-05 22:56:26 +00003254 }
Jordan Rose614a8652012-09-05 22:56:19 +00003255 } else {
3256 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3257 SpecifierLen);
3258 // Since the warning for passing non-POD types to variadic functions
3259 // was deferred until now, we emit a warning for non-POD
3260 // arguments here.
Richard Smith0e218972013-08-05 18:49:43 +00003261 switch (S.isValidVarArgType(ExprTy)) {
3262 case Sema::VAK_Valid:
3263 case Sema::VAK_ValidInCXX11:
Jordan Rose614a8652012-09-05 22:56:19 +00003264 EmitFormatDiagnostic(
Richard Smith0e218972013-08-05 18:49:43 +00003265 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3266 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3267 << CSR
3268 << E->getSourceRange(),
3269 E->getLocStart(), /*IsStringLocation*/false, CSR);
3270 break;
3271
3272 case Sema::VAK_Undefined:
3273 EmitFormatDiagnostic(
3274 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith80ad52f2013-01-02 11:42:31 +00003275 << S.getLangOpts().CPlusPlus11
Jordan Rose448ac3e2012-12-05 18:44:40 +00003276 << ExprTy
Jordan Rose614a8652012-09-05 22:56:19 +00003277 << CallType
3278 << AT.getRepresentativeTypeName(S.Context)
3279 << CSR
3280 << E->getSourceRange(),
3281 E->getLocStart(), /*IsStringLocation*/false, CSR);
Stephen Hines651f13c2014-04-23 16:59:28 -07003282 checkForCStrMembers(AT, E);
Richard Smith0e218972013-08-05 18:49:43 +00003283 break;
3284
3285 case Sema::VAK_Invalid:
3286 if (ExprTy->isObjCObjectType())
3287 EmitFormatDiagnostic(
3288 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3289 << S.getLangOpts().CPlusPlus11
3290 << ExprTy
3291 << CallType
3292 << AT.getRepresentativeTypeName(S.Context)
3293 << CSR
3294 << E->getSourceRange(),
3295 E->getLocStart(), /*IsStringLocation*/false, CSR);
3296 else
3297 // FIXME: If this is an initializer list, suggest removing the braces
3298 // or inserting a cast to the target type.
3299 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3300 << isa<InitListExpr>(E) << ExprTy << CallType
3301 << AT.getRepresentativeTypeName(S.Context)
3302 << E->getSourceRange();
3303 break;
3304 }
3305
3306 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3307 "format string specifier index out of range");
3308 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003309 }
3310
Ted Kremeneke0e53132010-01-28 23:39:18 +00003311 return true;
3312}
3313
Ted Kremenek826a3452010-07-16 02:11:22 +00003314//===--- CHECK: Scanf format string checking ------------------------------===//
3315
3316namespace {
3317class CheckScanfHandler : public CheckFormatHandler {
3318public:
3319 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3320 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003321 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003322 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003323 unsigned formatIdx, bool inFunctionCall,
Richard Smith0e218972013-08-05 18:49:43 +00003324 Sema::VariadicCallType CallType,
3325 llvm::SmallBitVector &CheckedVarArgs)
3326 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3327 numDataArgs, beg, hasVAListArg,
3328 Args, formatIdx, inFunctionCall, CallType,
3329 CheckedVarArgs)
Jordan Roseddcfbc92012-07-19 18:10:23 +00003330 {}
Ted Kremenek826a3452010-07-16 02:11:22 +00003331
3332 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3333 const char *startSpecifier,
Stephen Hines651f13c2014-04-23 16:59:28 -07003334 unsigned specifierLen) override;
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003335
3336 bool HandleInvalidScanfConversionSpecifier(
3337 const analyze_scanf::ScanfSpecifier &FS,
3338 const char *startSpecifier,
Stephen Hines651f13c2014-04-23 16:59:28 -07003339 unsigned specifierLen) override;
Ted Kremenekb7c21012010-07-16 18:28:03 +00003340
Stephen Hines651f13c2014-04-23 16:59:28 -07003341 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek826a3452010-07-16 02:11:22 +00003342};
Ted Kremenek07d161f2010-01-29 01:50:07 +00003343}
Ted Kremeneke0e53132010-01-28 23:39:18 +00003344
Ted Kremenekb7c21012010-07-16 18:28:03 +00003345void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3346 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00003347 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3348 getLocationOfByte(end), /*IsStringLocation*/true,
3349 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00003350}
3351
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003352bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3353 const analyze_scanf::ScanfSpecifier &FS,
3354 const char *startSpecifier,
3355 unsigned specifierLen) {
3356
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003357 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003358 FS.getConversionSpecifier();
3359
3360 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3361 getLocationOfByte(CS.getStart()),
3362 startSpecifier, specifierLen,
3363 CS.getStart(), CS.getLength());
3364}
3365
Ted Kremenek826a3452010-07-16 02:11:22 +00003366bool CheckScanfHandler::HandleScanfSpecifier(
3367 const analyze_scanf::ScanfSpecifier &FS,
3368 const char *startSpecifier,
3369 unsigned specifierLen) {
3370
3371 using namespace analyze_scanf;
3372 using namespace analyze_format_string;
3373
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003374 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00003375
Ted Kremenekbaa40062010-07-19 22:01:06 +00003376 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3377 // be used to decide if we are using positional arguments consistently.
3378 if (FS.consumesDataArgument()) {
3379 if (atFirstArg) {
3380 atFirstArg = false;
3381 usesPositionalArgs = FS.usesPositionalArg();
3382 }
3383 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003384 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3385 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00003386 return false;
3387 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003388 }
3389
3390 // Check if the field with is non-zero.
3391 const OptionalAmount &Amt = FS.getFieldWidth();
3392 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3393 if (Amt.getConstantAmount() == 0) {
3394 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3395 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00003396 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3397 getLocationOfByte(Amt.getStart()),
3398 /*IsStringLocation*/true, R,
3399 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00003400 }
3401 }
3402
3403 if (!FS.consumesDataArgument()) {
3404 // FIXME: Technically specifying a precision or field width here
3405 // makes no sense. Worth issuing a warning at some point.
3406 return true;
3407 }
3408
3409 // Consume the argument.
3410 unsigned argIndex = FS.getArgIndex();
3411 if (argIndex < NumDataArgs) {
3412 // The check to see if the argIndex is valid will come later.
3413 // We set the bit here because we may exit early from this
3414 // function if we encounter some other error.
3415 CoveredArgs.set(argIndex);
3416 }
3417
Ted Kremenek1e51c202010-07-20 20:04:47 +00003418 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003419 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00003420 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3421 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003422 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00003423 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003424 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00003425 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3426 diag::warn_format_non_standard_conversion_spec);
Hans Wennborg76517422012-02-22 10:17:01 +00003427
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003428 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3429 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3430
Ted Kremenek826a3452010-07-16 02:11:22 +00003431 // The remaining checks depend on the data arguments.
3432 if (HasVAListArg)
3433 return true;
3434
Ted Kremenek666a1972010-07-26 19:45:42 +00003435 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00003436 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00003437
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003438 // Check that the argument type matches the format specifier.
3439 const Expr *Ex = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00003440 if (!Ex)
3441 return true;
3442
Hans Wennborg58e1e542012-08-07 08:59:46 +00003443 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3444 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003445 ScanfSpecifier fixedFS = FS;
Stephen Hines651f13c2014-04-23 16:59:28 -07003446 bool success = fixedFS.fixType(Ex->getType(),
3447 Ex->IgnoreImpCasts()->getType(),
3448 S.getLangOpts(), S.Context);
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003449
3450 if (success) {
3451 // Get the fix string from the fixed format specifier.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003452 SmallString<128> buf;
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003453 llvm::raw_svector_ostream os(buf);
3454 fixedFS.toString(os);
3455
3456 EmitFormatDiagnostic(
3457 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003458 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003459 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003460 Ex->getLocStart(),
3461 /*IsStringLocation*/false,
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003462 getSpecifierRange(startSpecifier, specifierLen),
3463 FixItHint::CreateReplacement(
3464 getSpecifierRange(startSpecifier, specifierLen),
3465 os.str()));
3466 } else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003467 EmitFormatDiagnostic(
3468 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003469 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003470 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003471 Ex->getLocStart(),
3472 /*IsStringLocation*/false,
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003473 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003474 }
3475 }
3476
Ted Kremenek826a3452010-07-16 02:11:22 +00003477 return true;
3478}
3479
3480void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00003481 const Expr *OrigFormatExpr,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003482 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003483 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003484 unsigned firstDataArg, FormatStringType Type,
Richard Smith0e218972013-08-05 18:49:43 +00003485 bool inFunctionCall, VariadicCallType CallType,
3486 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003487
Ted Kremeneke0e53132010-01-28 23:39:18 +00003488 // CHECK: is the format string a wide literal?
Richard Smithdf9ef1b2012-06-13 05:37:23 +00003489 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003490 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003491 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003492 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3493 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003494 return;
3495 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003496
Ted Kremeneke0e53132010-01-28 23:39:18 +00003497 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00003498 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00003499 const char *Str = StrRef.data();
Stephen Hines651f13c2014-04-23 16:59:28 -07003500 // Account for cases where the string literal is truncated in a declaration.
3501 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
3502 assert(T && "String literal not of constant array type!");
3503 size_t TypeSize = T->getSize().getZExtValue();
3504 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003505 const unsigned numDataArgs = Args.size() - firstDataArg;
Stephen Hines651f13c2014-04-23 16:59:28 -07003506
3507 // Emit a warning if the string literal is truncated and does not contain an
3508 // embedded null character.
3509 if (TypeSize <= StrRef.size() &&
3510 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
3511 CheckFormatHandler::EmitFormatDiagnostic(
3512 *this, inFunctionCall, Args[format_idx],
3513 PDiag(diag::warn_printf_format_string_not_null_terminated),
3514 FExpr->getLocStart(),
3515 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
3516 return;
3517 }
3518
Ted Kremeneke0e53132010-01-28 23:39:18 +00003519 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00003520 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00003521 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003522 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003523 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3524 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003525 return;
3526 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003527
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003528 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003529 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003530 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003531 Str, HasVAListArg, Args, format_idx,
Richard Smith0e218972013-08-05 18:49:43 +00003532 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek826a3452010-07-16 02:11:22 +00003533
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003534 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003535 getLangOpts(),
3536 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003537 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003538 } else if (Type == FST_Scanf) {
Jordan Rose50687312012-06-04 23:52:23 +00003539 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003540 Str, HasVAListArg, Args, format_idx,
Richard Smith0e218972013-08-05 18:49:43 +00003541 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek826a3452010-07-16 02:11:22 +00003542
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003543 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003544 getLangOpts(),
3545 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003546 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003547 } // TODO: handle other formats
Ted Kremenekce7024e2010-01-28 01:18:22 +00003548}
3549
Stephen Hines651f13c2014-04-23 16:59:28 -07003550//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
3551
3552// Returns the related absolute value function that is larger, of 0 if one
3553// does not exist.
3554static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
3555 switch (AbsFunction) {
3556 default:
3557 return 0;
3558
3559 case Builtin::BI__builtin_abs:
3560 return Builtin::BI__builtin_labs;
3561 case Builtin::BI__builtin_labs:
3562 return Builtin::BI__builtin_llabs;
3563 case Builtin::BI__builtin_llabs:
3564 return 0;
3565
3566 case Builtin::BI__builtin_fabsf:
3567 return Builtin::BI__builtin_fabs;
3568 case Builtin::BI__builtin_fabs:
3569 return Builtin::BI__builtin_fabsl;
3570 case Builtin::BI__builtin_fabsl:
3571 return 0;
3572
3573 case Builtin::BI__builtin_cabsf:
3574 return Builtin::BI__builtin_cabs;
3575 case Builtin::BI__builtin_cabs:
3576 return Builtin::BI__builtin_cabsl;
3577 case Builtin::BI__builtin_cabsl:
3578 return 0;
3579
3580 case Builtin::BIabs:
3581 return Builtin::BIlabs;
3582 case Builtin::BIlabs:
3583 return Builtin::BIllabs;
3584 case Builtin::BIllabs:
3585 return 0;
3586
3587 case Builtin::BIfabsf:
3588 return Builtin::BIfabs;
3589 case Builtin::BIfabs:
3590 return Builtin::BIfabsl;
3591 case Builtin::BIfabsl:
3592 return 0;
3593
3594 case Builtin::BIcabsf:
3595 return Builtin::BIcabs;
3596 case Builtin::BIcabs:
3597 return Builtin::BIcabsl;
3598 case Builtin::BIcabsl:
3599 return 0;
3600 }
3601}
3602
3603// Returns the argument type of the absolute value function.
3604static QualType getAbsoluteValueArgumentType(ASTContext &Context,
3605 unsigned AbsType) {
3606 if (AbsType == 0)
3607 return QualType();
3608
3609 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3610 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
3611 if (Error != ASTContext::GE_None)
3612 return QualType();
3613
3614 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
3615 if (!FT)
3616 return QualType();
3617
3618 if (FT->getNumParams() != 1)
3619 return QualType();
3620
3621 return FT->getParamType(0);
3622}
3623
3624// Returns the best absolute value function, or zero, based on type and
3625// current absolute value function.
3626static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
3627 unsigned AbsFunctionKind) {
3628 unsigned BestKind = 0;
3629 uint64_t ArgSize = Context.getTypeSize(ArgType);
3630 for (unsigned Kind = AbsFunctionKind; Kind != 0;
3631 Kind = getLargerAbsoluteValueFunction(Kind)) {
3632 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
3633 if (Context.getTypeSize(ParamType) >= ArgSize) {
3634 if (BestKind == 0)
3635 BestKind = Kind;
3636 else if (Context.hasSameType(ParamType, ArgType)) {
3637 BestKind = Kind;
3638 break;
3639 }
3640 }
3641 }
3642 return BestKind;
3643}
3644
3645enum AbsoluteValueKind {
3646 AVK_Integer,
3647 AVK_Floating,
3648 AVK_Complex
3649};
3650
3651static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
3652 if (T->isIntegralOrEnumerationType())
3653 return AVK_Integer;
3654 if (T->isRealFloatingType())
3655 return AVK_Floating;
3656 if (T->isAnyComplexType())
3657 return AVK_Complex;
3658
3659 llvm_unreachable("Type not integer, floating, or complex");
3660}
3661
3662// Changes the absolute value function to a different type. Preserves whether
3663// the function is a builtin.
3664static unsigned changeAbsFunction(unsigned AbsKind,
3665 AbsoluteValueKind ValueKind) {
3666 switch (ValueKind) {
3667 case AVK_Integer:
3668 switch (AbsKind) {
3669 default:
3670 return 0;
3671 case Builtin::BI__builtin_fabsf:
3672 case Builtin::BI__builtin_fabs:
3673 case Builtin::BI__builtin_fabsl:
3674 case Builtin::BI__builtin_cabsf:
3675 case Builtin::BI__builtin_cabs:
3676 case Builtin::BI__builtin_cabsl:
3677 return Builtin::BI__builtin_abs;
3678 case Builtin::BIfabsf:
3679 case Builtin::BIfabs:
3680 case Builtin::BIfabsl:
3681 case Builtin::BIcabsf:
3682 case Builtin::BIcabs:
3683 case Builtin::BIcabsl:
3684 return Builtin::BIabs;
3685 }
3686 case AVK_Floating:
3687 switch (AbsKind) {
3688 default:
3689 return 0;
3690 case Builtin::BI__builtin_abs:
3691 case Builtin::BI__builtin_labs:
3692 case Builtin::BI__builtin_llabs:
3693 case Builtin::BI__builtin_cabsf:
3694 case Builtin::BI__builtin_cabs:
3695 case Builtin::BI__builtin_cabsl:
3696 return Builtin::BI__builtin_fabsf;
3697 case Builtin::BIabs:
3698 case Builtin::BIlabs:
3699 case Builtin::BIllabs:
3700 case Builtin::BIcabsf:
3701 case Builtin::BIcabs:
3702 case Builtin::BIcabsl:
3703 return Builtin::BIfabsf;
3704 }
3705 case AVK_Complex:
3706 switch (AbsKind) {
3707 default:
3708 return 0;
3709 case Builtin::BI__builtin_abs:
3710 case Builtin::BI__builtin_labs:
3711 case Builtin::BI__builtin_llabs:
3712 case Builtin::BI__builtin_fabsf:
3713 case Builtin::BI__builtin_fabs:
3714 case Builtin::BI__builtin_fabsl:
3715 return Builtin::BI__builtin_cabsf;
3716 case Builtin::BIabs:
3717 case Builtin::BIlabs:
3718 case Builtin::BIllabs:
3719 case Builtin::BIfabsf:
3720 case Builtin::BIfabs:
3721 case Builtin::BIfabsl:
3722 return Builtin::BIcabsf;
3723 }
3724 }
3725 llvm_unreachable("Unable to convert function");
3726}
3727
3728static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
3729 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
3730 if (!FnInfo)
3731 return 0;
3732
3733 switch (FDecl->getBuiltinID()) {
3734 default:
3735 return 0;
3736 case Builtin::BI__builtin_abs:
3737 case Builtin::BI__builtin_fabs:
3738 case Builtin::BI__builtin_fabsf:
3739 case Builtin::BI__builtin_fabsl:
3740 case Builtin::BI__builtin_labs:
3741 case Builtin::BI__builtin_llabs:
3742 case Builtin::BI__builtin_cabs:
3743 case Builtin::BI__builtin_cabsf:
3744 case Builtin::BI__builtin_cabsl:
3745 case Builtin::BIabs:
3746 case Builtin::BIlabs:
3747 case Builtin::BIllabs:
3748 case Builtin::BIfabs:
3749 case Builtin::BIfabsf:
3750 case Builtin::BIfabsl:
3751 case Builtin::BIcabs:
3752 case Builtin::BIcabsf:
3753 case Builtin::BIcabsl:
3754 return FDecl->getBuiltinID();
3755 }
3756 llvm_unreachable("Unknown Builtin type");
3757}
3758
3759// If the replacement is valid, emit a note with replacement function.
3760// Additionally, suggest including the proper header if not already included.
3761static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003762 unsigned AbsKind, QualType ArgType) {
3763 bool EmitHeaderHint = true;
3764 const char *HeaderName = nullptr;
3765 const char *FunctionName = nullptr;
3766 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
3767 FunctionName = "std::abs";
3768 if (ArgType->isIntegralOrEnumerationType()) {
3769 HeaderName = "cstdlib";
3770 } else if (ArgType->isRealFloatingType()) {
3771 HeaderName = "cmath";
3772 } else {
3773 llvm_unreachable("Invalid Type");
Stephen Hines651f13c2014-04-23 16:59:28 -07003774 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003775
3776 // Lookup all std::abs
3777 if (NamespaceDecl *Std = S.getStdNamespace()) {
3778 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
3779 R.suppressDiagnostics();
3780 S.LookupQualifiedName(R, Std);
3781
3782 for (const auto *I : R) {
3783 const FunctionDecl *FDecl = nullptr;
3784 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
3785 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
3786 } else {
3787 FDecl = dyn_cast<FunctionDecl>(I);
3788 }
3789 if (!FDecl)
3790 continue;
3791
3792 // Found std::abs(), check that they are the right ones.
3793 if (FDecl->getNumParams() != 1)
3794 continue;
3795
3796 // Check that the parameter type can handle the argument.
3797 QualType ParamType = FDecl->getParamDecl(0)->getType();
3798 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
3799 S.Context.getTypeSize(ArgType) <=
3800 S.Context.getTypeSize(ParamType)) {
3801 // Found a function, don't need the header hint.
3802 EmitHeaderHint = false;
3803 break;
3804 }
Stephen Hines651f13c2014-04-23 16:59:28 -07003805 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003806 }
3807 } else {
3808 FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
3809 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
3810
3811 if (HeaderName) {
3812 DeclarationName DN(&S.Context.Idents.get(FunctionName));
3813 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
3814 R.suppressDiagnostics();
3815 S.LookupName(R, S.getCurScope());
3816
3817 if (R.isSingleResult()) {
3818 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3819 if (FD && FD->getBuiltinID() == AbsKind) {
3820 EmitHeaderHint = false;
3821 } else {
3822 return;
3823 }
3824 } else if (!R.empty()) {
3825 return;
3826 }
Stephen Hines651f13c2014-04-23 16:59:28 -07003827 }
3828 }
3829
3830 S.Diag(Loc, diag::note_replace_abs_function)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003831 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Stephen Hines651f13c2014-04-23 16:59:28 -07003832
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003833 if (!HeaderName)
3834 return;
3835
3836 if (!EmitHeaderHint)
3837 return;
3838
3839 S.Diag(Loc, diag::note_please_include_header) << HeaderName << FunctionName;
3840}
3841
3842static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
3843 if (!FDecl)
3844 return false;
3845
3846 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
3847 return false;
3848
3849 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
3850
3851 while (ND && ND->isInlineNamespace()) {
3852 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Stephen Hines651f13c2014-04-23 16:59:28 -07003853 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003854
3855 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
3856 return false;
3857
3858 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
3859 return false;
3860
3861 return true;
Stephen Hines651f13c2014-04-23 16:59:28 -07003862}
3863
3864// Warn when using the wrong abs() function.
3865void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
3866 const FunctionDecl *FDecl,
3867 IdentifierInfo *FnInfo) {
3868 if (Call->getNumArgs() != 1)
3869 return;
3870
3871 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003872 bool IsStdAbs = IsFunctionStdAbs(FDecl);
3873 if (AbsKind == 0 && !IsStdAbs)
Stephen Hines651f13c2014-04-23 16:59:28 -07003874 return;
3875
3876 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
3877 QualType ParamType = Call->getArg(0)->getType();
3878
3879 // Unsigned types can not be negative. Suggest to drop the absolute value
3880 // function.
3881 if (ArgType->isUnsignedIntegerType()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003882 const char *FunctionName =
3883 IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
Stephen Hines651f13c2014-04-23 16:59:28 -07003884 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
3885 Diag(Call->getExprLoc(), diag::note_remove_abs)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003886 << FunctionName
Stephen Hines651f13c2014-04-23 16:59:28 -07003887 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
3888 return;
3889 }
3890
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003891 // std::abs has overloads which prevent most of the absolute value problems
3892 // from occurring.
3893 if (IsStdAbs)
3894 return;
3895
Stephen Hines651f13c2014-04-23 16:59:28 -07003896 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
3897 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
3898
3899 // The argument and parameter are the same kind. Check if they are the right
3900 // size.
3901 if (ArgValueKind == ParamValueKind) {
3902 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
3903 return;
3904
3905 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
3906 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
3907 << FDecl << ArgType << ParamType;
3908
3909 if (NewAbsKind == 0)
3910 return;
3911
3912 emitReplacement(*this, Call->getExprLoc(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003913 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Stephen Hines651f13c2014-04-23 16:59:28 -07003914 return;
3915 }
3916
3917 // ArgValueKind != ParamValueKind
3918 // The wrong type of absolute value function was used. Attempt to find the
3919 // proper one.
3920 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
3921 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
3922 if (NewAbsKind == 0)
3923 return;
3924
3925 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
3926 << FDecl << ParamValueKind << ArgValueKind;
3927
3928 emitReplacement(*this, Call->getExprLoc(),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003929 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Stephen Hines651f13c2014-04-23 16:59:28 -07003930 return;
3931}
3932
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003933//===--- CHECK: Standard memory functions ---------------------------------===//
3934
Stephen Hines651f13c2014-04-23 16:59:28 -07003935/// \brief Takes the expression passed to the size_t parameter of functions
3936/// such as memcmp, strncat, etc and warns if it's a comparison.
3937///
3938/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
3939static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
3940 IdentifierInfo *FnName,
3941 SourceLocation FnLoc,
3942 SourceLocation RParenLoc) {
3943 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
3944 if (!Size)
3945 return false;
3946
3947 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
3948 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
3949 return false;
3950
Stephen Hines651f13c2014-04-23 16:59:28 -07003951 SourceRange SizeRange = Size->getSourceRange();
3952 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
3953 << SizeRange << FnName;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003954 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
3955 << FnName << FixItHint::CreateInsertion(
3956 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Stephen Hines651f13c2014-04-23 16:59:28 -07003957 << FixItHint::CreateRemoval(RParenLoc);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003958 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Stephen Hines651f13c2014-04-23 16:59:28 -07003959 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003960 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
3961 ")");
Stephen Hines651f13c2014-04-23 16:59:28 -07003962
3963 return true;
3964}
3965
Douglas Gregor2a053a32011-05-03 20:05:22 +00003966/// \brief Determine whether the given type is a dynamic class type (e.g.,
3967/// whether it has a vtable).
3968static bool isDynamicClassType(QualType T) {
3969 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3970 if (CXXRecordDecl *Definition = Record->getDefinition())
3971 if (Definition->isDynamicClass())
3972 return true;
3973
3974 return false;
3975}
3976
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003977/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00003978/// otherwise returns NULL.
3979static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00003980 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00003981 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3982 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
3983 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003984
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003985 return nullptr;
Chandler Carruth000d4282011-06-16 09:09:40 +00003986}
3987
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003988/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00003989static QualType getSizeOfArgType(const Expr* E) {
3990 if (const UnaryExprOrTypeTraitExpr *SizeOf =
3991 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3992 if (SizeOf->getKind() == clang::UETT_SizeOf)
3993 return SizeOf->getTypeOfArgument();
3994
3995 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00003996}
3997
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003998/// \brief Check for dangerous or invalid arguments to memset().
3999///
Chandler Carruth929f0132011-06-03 06:23:57 +00004000/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00004001/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4002/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00004003///
4004/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00004005void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00004006 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00004007 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00004008 assert(BId != 0);
4009
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00004010 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00004011 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00004012 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00004013 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00004014 return;
4015
Anna Zaks0a151a12012-01-17 00:37:07 +00004016 unsigned LastArg = (BId == Builtin::BImemset ||
4017 BId == Builtin::BIstrndup ? 1 : 2);
4018 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00004019 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00004020
Stephen Hines651f13c2014-04-23 16:59:28 -07004021 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4022 Call->getLocStart(), Call->getRParenLoc()))
4023 return;
4024
Chandler Carruth000d4282011-06-16 09:09:40 +00004025 // We have special checking when the length is a sizeof expression.
4026 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4027 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4028 llvm::FoldingSetNodeID SizeOfArgID;
4029
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00004030 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4031 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00004032 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00004033
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00004034 QualType DestTy = Dest->getType();
4035 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
4036 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00004037
Chandler Carruth000d4282011-06-16 09:09:40 +00004038 // Never warn about void type pointers. This can be used to suppress
4039 // false positives.
4040 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00004041 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00004042
Chandler Carruth000d4282011-06-16 09:09:40 +00004043 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4044 // actually comparing the expressions for equality. Because computing the
4045 // expression IDs can be expensive, we only do this if the diagnostic is
4046 // enabled.
4047 if (SizeOfArg &&
4048 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
4049 SizeOfArg->getExprLoc())) {
4050 // We only compute IDs for expressions if the warning is enabled, and
4051 // cache the sizeof arg's ID.
4052 if (SizeOfArgID == llvm::FoldingSetNodeID())
4053 SizeOfArg->Profile(SizeOfArgID, Context, true);
4054 llvm::FoldingSetNodeID DestID;
4055 Dest->Profile(DestID, Context, true);
4056 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00004057 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4058 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00004059 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks6fcb3722012-05-30 00:34:21 +00004060 StringRef ReadableName = FnName->getName();
4061
Chandler Carruth000d4282011-06-16 09:09:40 +00004062 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaks90c78322012-05-30 23:14:52 +00004063 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth000d4282011-06-16 09:09:40 +00004064 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian7adf4172013-01-30 01:12:44 +00004065 if (!PointeeTy->isIncompleteType() &&
4066 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth000d4282011-06-16 09:09:40 +00004067 ActionIdx = 2; // If the pointee's size is sizeof(char),
4068 // suggest an explicit length.
Anna Zaks6fcb3722012-05-30 00:34:21 +00004069
4070 // If the function is defined as a builtin macro, do not show macro
4071 // expansion.
4072 SourceLocation SL = SizeOfArg->getExprLoc();
4073 SourceRange DSR = Dest->getSourceRange();
4074 SourceRange SSR = SizeOfArg->getSourceRange();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004075 SourceManager &SM = getSourceManager();
Anna Zaks6fcb3722012-05-30 00:34:21 +00004076
4077 if (SM.isMacroArgExpansion(SL)) {
4078 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4079 SL = SM.getSpellingLoc(SL);
4080 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4081 SM.getSpellingLoc(DSR.getEnd()));
4082 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4083 SM.getSpellingLoc(SSR.getEnd()));
4084 }
4085
Anna Zaks90c78322012-05-30 23:14:52 +00004086 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth000d4282011-06-16 09:09:40 +00004087 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks6fcb3722012-05-30 00:34:21 +00004088 << ReadableName
Anna Zaks90c78322012-05-30 23:14:52 +00004089 << PointeeTy
4090 << DestTy
Anna Zaks6fcb3722012-05-30 00:34:21 +00004091 << DSR
Anna Zaks90c78322012-05-30 23:14:52 +00004092 << SSR);
4093 DiagRuntimeBehavior(SL, SizeOfArg,
4094 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4095 << ActionIdx
4096 << SSR);
4097
Chandler Carruth000d4282011-06-16 09:09:40 +00004098 break;
4099 }
4100 }
4101
4102 // Also check for cases where the sizeof argument is the exact same
4103 // type as the memory argument, and where it points to a user-defined
4104 // record type.
4105 if (SizeOfArgTy != QualType()) {
4106 if (PointeeTy->isRecordType() &&
4107 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4108 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4109 PDiag(diag::warn_sizeof_pointer_type_memaccess)
4110 << FnName << SizeOfArgTy << ArgIdx
4111 << PointeeTy << Dest->getSourceRange()
4112 << LenExpr->getSourceRange());
4113 break;
4114 }
Nico Webere4a1c642011-06-14 16:14:58 +00004115 }
4116
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00004117 // Always complain about dynamic classes.
Anna Zaks0a151a12012-01-17 00:37:07 +00004118 if (isDynamicClassType(PointeeTy)) {
4119
4120 unsigned OperationType = 0;
4121 // "overwritten" if we're warning about the destination for any call
4122 // but memcmp; otherwise a verb appropriate to the call.
4123 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4124 if (BId == Builtin::BImemcpy)
4125 OperationType = 1;
4126 else if(BId == Builtin::BImemmove)
4127 OperationType = 2;
4128 else if (BId == Builtin::BImemcmp)
4129 OperationType = 3;
4130 }
4131
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00004132 DiagRuntimeBehavior(
4133 Dest->getExprLoc(), Dest,
4134 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks0a151a12012-01-17 00:37:07 +00004135 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaksd9b859a2012-01-13 21:52:01 +00004136 << FnName << PointeeTy
Anna Zaks0a151a12012-01-17 00:37:07 +00004137 << OperationType
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00004138 << Call->getCallee()->getSourceRange());
Anna Zaks0a151a12012-01-17 00:37:07 +00004139 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4140 BId != Builtin::BImemset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00004141 DiagRuntimeBehavior(
4142 Dest->getExprLoc(), Dest,
4143 PDiag(diag::warn_arc_object_memaccess)
4144 << ArgIdx << FnName << PointeeTy
4145 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00004146 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00004147 continue;
John McCallf85e1932011-06-15 23:02:42 +00004148
4149 DiagRuntimeBehavior(
4150 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00004151 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00004152 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4153 break;
4154 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00004155 }
4156}
4157
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00004158// A little helper routine: ignore addition and subtraction of integer literals.
4159// This intentionally does not ignore all integer constant expressions because
4160// we don't want to remove sizeof().
4161static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4162 Ex = Ex->IgnoreParenCasts();
4163
4164 for (;;) {
4165 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4166 if (!BO || !BO->isAdditiveOp())
4167 break;
4168
4169 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4170 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4171
4172 if (isa<IntegerLiteral>(RHS))
4173 Ex = LHS;
4174 else if (isa<IntegerLiteral>(LHS))
4175 Ex = RHS;
4176 else
4177 break;
4178 }
4179
4180 return Ex;
4181}
4182
Anna Zaks0f38ace2012-08-08 21:42:23 +00004183static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4184 ASTContext &Context) {
4185 // Only handle constant-sized or VLAs, but not flexible members.
4186 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4187 // Only issue the FIXIT for arrays of size > 1.
4188 if (CAT->getSize().getSExtValue() <= 1)
4189 return false;
4190 } else if (!Ty->isVariableArrayType()) {
4191 return false;
4192 }
4193 return true;
4194}
4195
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00004196// Warn if the user has made the 'size' argument to strlcpy or strlcat
4197// be the size of the source, instead of the destination.
4198void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4199 IdentifierInfo *FnName) {
4200
4201 // Don't crash if the user has the wrong number of arguments
4202 if (Call->getNumArgs() != 3)
4203 return;
4204
4205 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4206 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004207 const Expr *CompareWithSrc = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07004208
4209 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4210 Call->getLocStart(), Call->getRParenLoc()))
4211 return;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00004212
4213 // Look for 'strlcpy(dst, x, sizeof(x))'
4214 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4215 CompareWithSrc = Ex;
4216 else {
4217 // Look for 'strlcpy(dst, x, strlen(x))'
4218 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Stephen Hines651f13c2014-04-23 16:59:28 -07004219 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4220 SizeCall->getNumArgs() == 1)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00004221 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4222 }
4223 }
4224
4225 if (!CompareWithSrc)
4226 return;
4227
4228 // Determine if the argument to sizeof/strlen is equal to the source
4229 // argument. In principle there's all kinds of things you could do
4230 // here, for instance creating an == expression and evaluating it with
4231 // EvaluateAsBooleanCondition, but this uses a more direct technique:
4232 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4233 if (!SrcArgDRE)
4234 return;
4235
4236 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4237 if (!CompareWithSrcDRE ||
4238 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4239 return;
4240
4241 const Expr *OriginalSizeArg = Call->getArg(2);
4242 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4243 << OriginalSizeArg->getSourceRange() << FnName;
4244
4245 // Output a FIXIT hint if the destination is an array (rather than a
4246 // pointer to an array). This could be enhanced to handle some
4247 // pointers if we know the actual size, like if DstArg is 'array+2'
4248 // we could say 'sizeof(array)-2'.
4249 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks0f38ace2012-08-08 21:42:23 +00004250 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek8f746222011-08-18 22:48:41 +00004251 return;
Ted Kremenek8f746222011-08-18 22:48:41 +00004252
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00004253 SmallString<128> sizeString;
Ted Kremenek8f746222011-08-18 22:48:41 +00004254 llvm::raw_svector_ostream OS(sizeString);
4255 OS << "sizeof(";
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004256 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00004257 OS << ")";
4258
4259 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4260 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4261 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00004262}
4263
Anna Zaksc36bedc2012-02-01 19:08:57 +00004264/// Check if two expressions refer to the same declaration.
4265static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4266 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4267 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4268 return D1->getDecl() == D2->getDecl();
4269 return false;
4270}
4271
4272static const Expr *getStrlenExprArg(const Expr *E) {
4273 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
4274 const FunctionDecl *FD = CE->getDirectCallee();
4275 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004276 return nullptr;
Anna Zaksc36bedc2012-02-01 19:08:57 +00004277 return CE->getArg(0)->IgnoreParenCasts();
4278 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004279 return nullptr;
Anna Zaksc36bedc2012-02-01 19:08:57 +00004280}
4281
4282// Warn on anti-patterns as the 'size' argument to strncat.
4283// The correct size argument should look like following:
4284// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
4285void Sema::CheckStrncatArguments(const CallExpr *CE,
4286 IdentifierInfo *FnName) {
4287 // Don't crash if the user has the wrong number of arguments.
4288 if (CE->getNumArgs() < 3)
4289 return;
4290 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
4291 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
4292 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
4293
Stephen Hines651f13c2014-04-23 16:59:28 -07004294 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
4295 CE->getRParenLoc()))
4296 return;
4297
Anna Zaksc36bedc2012-02-01 19:08:57 +00004298 // Identify common expressions, which are wrongly used as the size argument
4299 // to strncat and may lead to buffer overflows.
4300 unsigned PatternType = 0;
4301 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
4302 // - sizeof(dst)
4303 if (referToTheSameDecl(SizeOfArg, DstArg))
4304 PatternType = 1;
4305 // - sizeof(src)
4306 else if (referToTheSameDecl(SizeOfArg, SrcArg))
4307 PatternType = 2;
4308 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
4309 if (BE->getOpcode() == BO_Sub) {
4310 const Expr *L = BE->getLHS()->IgnoreParenCasts();
4311 const Expr *R = BE->getRHS()->IgnoreParenCasts();
4312 // - sizeof(dst) - strlen(dst)
4313 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
4314 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
4315 PatternType = 1;
4316 // - sizeof(src) - (anything)
4317 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
4318 PatternType = 2;
4319 }
4320 }
4321
4322 if (PatternType == 0)
4323 return;
4324
Anna Zaksafdb0412012-02-03 01:27:37 +00004325 // Generate the diagnostic.
4326 SourceLocation SL = LenArg->getLocStart();
4327 SourceRange SR = LenArg->getSourceRange();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004328 SourceManager &SM = getSourceManager();
Anna Zaksafdb0412012-02-03 01:27:37 +00004329
4330 // If the function is defined as a builtin macro, do not show macro expansion.
4331 if (SM.isMacroArgExpansion(SL)) {
4332 SL = SM.getSpellingLoc(SL);
4333 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
4334 SM.getSpellingLoc(SR.getEnd()));
4335 }
4336
Anna Zaks0f38ace2012-08-08 21:42:23 +00004337 // Check if the destination is an array (rather than a pointer to an array).
4338 QualType DstTy = DstArg->getType();
4339 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
4340 Context);
4341 if (!isKnownSizeArray) {
4342 if (PatternType == 1)
4343 Diag(SL, diag::warn_strncat_wrong_size) << SR;
4344 else
4345 Diag(SL, diag::warn_strncat_src_size) << SR;
4346 return;
4347 }
4348
Anna Zaksc36bedc2012-02-01 19:08:57 +00004349 if (PatternType == 1)
Anna Zaksafdb0412012-02-03 01:27:37 +00004350 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00004351 else
Anna Zaksafdb0412012-02-03 01:27:37 +00004352 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00004353
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00004354 SmallString<128> sizeString;
Anna Zaksc36bedc2012-02-01 19:08:57 +00004355 llvm::raw_svector_ostream OS(sizeString);
4356 OS << "sizeof(";
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004357 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00004358 OS << ") - ";
4359 OS << "strlen(";
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004360 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00004361 OS << ") - 1";
4362
Anna Zaksafdb0412012-02-03 01:27:37 +00004363 Diag(SL, diag::note_strncat_wrong_size)
4364 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaksc36bedc2012-02-01 19:08:57 +00004365}
4366
Ted Kremenek06de2762007-08-17 16:46:58 +00004367//===--- CHECK: Return Address of Stack Variable --------------------------===//
4368
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004369static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4370 Decl *ParentDecl);
4371static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
4372 Decl *ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004373
4374/// CheckReturnStackAddr - Check if a return statement returns the address
4375/// of a stack variable.
Stephen Hines651f13c2014-04-23 16:59:28 -07004376static void
4377CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
4378 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00004379
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004380 Expr *stackE = nullptr;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004381 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004382
4383 // Perform checking for returned stack addresses, local blocks,
4384 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00004385 if (lhsType->isPointerType() ||
Stephen Hines651f13c2014-04-23 16:59:28 -07004386 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004387 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00004388 } else if (lhsType->isReferenceType()) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004389 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004390 }
4391
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004392 if (!stackE)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004393 return; // Nothing suspicious was found.
4394
4395 SourceLocation diagLoc;
4396 SourceRange diagRange;
4397 if (refVars.empty()) {
4398 diagLoc = stackE->getLocStart();
4399 diagRange = stackE->getSourceRange();
4400 } else {
4401 // We followed through a reference variable. 'stackE' contains the
4402 // problematic expression but we will warn at the return statement pointing
4403 // at the reference variable. We will later display the "trail" of
4404 // reference variables using notes.
4405 diagLoc = refVars[0]->getLocStart();
4406 diagRange = refVars[0]->getSourceRange();
4407 }
4408
4409 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Stephen Hines651f13c2014-04-23 16:59:28 -07004410 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004411 : diag::warn_ret_stack_addr)
4412 << DR->getDecl()->getDeclName() << diagRange;
4413 } else if (isa<BlockExpr>(stackE)) { // local block.
Stephen Hines651f13c2014-04-23 16:59:28 -07004414 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004415 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Stephen Hines651f13c2014-04-23 16:59:28 -07004416 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004417 } else { // local temporary.
Stephen Hines651f13c2014-04-23 16:59:28 -07004418 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
4419 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004420 << diagRange;
4421 }
4422
4423 // Display the "trail" of reference variables that we followed until we
4424 // found the problematic expression using notes.
4425 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4426 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4427 // If this var binds to another reference var, show the range of the next
4428 // var, otherwise the var binds to the problematic expression, in which case
4429 // show the range of the expression.
4430 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4431 : stackE->getSourceRange();
Stephen Hines651f13c2014-04-23 16:59:28 -07004432 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4433 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00004434 }
4435}
4436
4437/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4438/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004439/// to a location on the stack, a local block, an address of a label, or a
4440/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00004441/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004442/// encounter a subexpression that (1) clearly does not lead to one of the
4443/// above problematic expressions (2) is something we cannot determine leads to
4444/// a problematic expression based on such local checking.
4445///
4446/// Both EvalAddr and EvalVal follow through reference variables to evaluate
4447/// the expression that they point to. Such variables are added to the
4448/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00004449///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00004450/// EvalAddr processes expressions that are pointers that are used as
4451/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004452/// At the base case of the recursion is a check for the above problematic
4453/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00004454///
4455/// This implementation handles:
4456///
4457/// * pointer-to-pointer casts
4458/// * implicit conversions from array references to pointers
4459/// * taking the address of fields
4460/// * arbitrary interplay between "&" and "*" operators
4461/// * pointer arithmetic from an address of a stack variable
4462/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004463static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4464 Decl *ParentDecl) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004465 if (E->isTypeDependent())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004466 return nullptr;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004467
Ted Kremenek06de2762007-08-17 16:46:58 +00004468 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00004469 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00004470 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004471 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004472 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00004473
Peter Collingbournef111d932011-04-15 00:35:48 +00004474 E = E->IgnoreParens();
4475
Ted Kremenek06de2762007-08-17 16:46:58 +00004476 // Our "symbolic interpreter" is just a dispatch off the currently
4477 // viewed AST node. We then recursively traverse the AST by calling
4478 // EvalAddr and EvalVal appropriately.
4479 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004480 case Stmt::DeclRefExprClass: {
4481 DeclRefExpr *DR = cast<DeclRefExpr>(E);
4482
Stephen Hines651f13c2014-04-23 16:59:28 -07004483 // If we leave the immediate function, the lifetime isn't about to end.
4484 if (DR->refersToEnclosingLocal())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004485 return nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07004486
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004487 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
4488 // If this is a reference variable, follow through to the expression that
4489 // it points to.
4490 if (V->hasLocalStorage() &&
4491 V->getType()->isReferenceType() && V->hasInit()) {
4492 // Add the reference variable to the "trail".
4493 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004494 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004495 }
4496
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004497 return nullptr;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004498 }
Ted Kremenek06de2762007-08-17 16:46:58 +00004499
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004500 case Stmt::UnaryOperatorClass: {
4501 // The only unary operator that make sense to handle here
4502 // is AddrOf. All others don't make sense as pointers.
4503 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004504
John McCall2de56d12010-08-25 11:45:40 +00004505 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004506 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004507 else
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004508 return nullptr;
Ted Kremenek06de2762007-08-17 16:46:58 +00004509 }
Mike Stump1eb44332009-09-09 15:08:12 +00004510
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004511 case Stmt::BinaryOperatorClass: {
4512 // Handle pointer arithmetic. All other binary operators are not valid
4513 // in this context.
4514 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00004515 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00004516
John McCall2de56d12010-08-25 11:45:40 +00004517 if (op != BO_Add && op != BO_Sub)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004518 return nullptr;
Mike Stump1eb44332009-09-09 15:08:12 +00004519
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004520 Expr *Base = B->getLHS();
4521
4522 // Determine which argument is the real pointer base. It could be
4523 // the RHS argument instead of the LHS.
4524 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00004525
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004526 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004527 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004528 }
Steve Naroff61f40a22008-09-10 19:17:48 +00004529
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004530 // For conditional operators we need to see if either the LHS or RHS are
4531 // valid DeclRefExpr*s. If one of them is valid, we return it.
4532 case Stmt::ConditionalOperatorClass: {
4533 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004534
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004535 // Handle the GNU extension for missing LHS.
Stephen Hines651f13c2014-04-23 16:59:28 -07004536 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
4537 if (Expr *LHSExpr = C->getLHS()) {
4538 // In C++, we can have a throw-expression, which has 'void' type.
4539 if (!LHSExpr->getType()->isVoidType())
4540 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00004541 return LHS;
4542 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004543
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00004544 // In C++, we can have a throw-expression, which has 'void' type.
4545 if (C->getRHS()->getType()->isVoidType())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004546 return nullptr;
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00004547
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004548 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004549 }
Stephen Hines651f13c2014-04-23 16:59:28 -07004550
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004551 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00004552 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004553 return E; // local block.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004554 return nullptr;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004555
4556 case Stmt::AddrLabelExprClass:
4557 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00004558
John McCall80ee6e82011-11-10 05:35:25 +00004559 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004560 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4561 ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00004562
Ted Kremenek54b52742008-08-07 00:49:01 +00004563 // For casts, we need to handle conversions from arrays to
4564 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00004565 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00004566 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00004567 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8b9414e2012-02-23 23:04:32 +00004568 case Stmt::ObjCBridgedCastExprClass:
Mike Stump1eb44332009-09-09 15:08:12 +00004569 case Stmt::CXXStaticCastExprClass:
4570 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00004571 case Stmt::CXXConstCastExprClass:
4572 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8b9414e2012-02-23 23:04:32 +00004573 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4574 switch (cast<CastExpr>(E)->getCastKind()) {
4575 case CK_BitCast:
4576 case CK_LValueToRValue:
4577 case CK_NoOp:
4578 case CK_BaseToDerived:
4579 case CK_DerivedToBase:
4580 case CK_UncheckedDerivedToBase:
4581 case CK_Dynamic:
4582 case CK_CPointerToObjCPointerCast:
4583 case CK_BlockPointerToObjCPointerCast:
4584 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004585 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00004586
4587 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004588 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00004589
4590 default:
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004591 return nullptr;
Eli Friedman8b9414e2012-02-23 23:04:32 +00004592 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004593 }
Mike Stump1eb44332009-09-09 15:08:12 +00004594
Douglas Gregor03e80032011-06-21 17:03:29 +00004595 case Stmt::MaterializeTemporaryExprClass:
4596 if (Expr *Result = EvalAddr(
4597 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004598 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00004599 return Result;
4600
4601 return E;
4602
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004603 // Everything else: we simply don't reason about them.
4604 default:
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004605 return nullptr;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004606 }
Ted Kremenek06de2762007-08-17 16:46:58 +00004607}
Mike Stump1eb44332009-09-09 15:08:12 +00004608
Ted Kremenek06de2762007-08-17 16:46:58 +00004609
4610/// EvalVal - This function is complements EvalAddr in the mutual recursion.
4611/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004612static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4613 Decl *ParentDecl) {
Ted Kremenek68957a92010-08-04 20:01:07 +00004614do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00004615 // We should only be called for evaluating non-pointer expressions, or
4616 // expressions with a pointer type that are not used as references but instead
4617 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00004618
Ted Kremenek06de2762007-08-17 16:46:58 +00004619 // Our "symbolic interpreter" is just a dispatch off the currently
4620 // viewed AST node. We then recursively traverse the AST by calling
4621 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00004622
4623 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00004624 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00004625 case Stmt::ImplicitCastExprClass: {
4626 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00004627 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00004628 E = IE->getSubExpr();
4629 continue;
4630 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004631 return nullptr;
Ted Kremenek68957a92010-08-04 20:01:07 +00004632 }
4633
John McCall80ee6e82011-11-10 05:35:25 +00004634 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004635 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00004636
Douglas Gregora2813ce2009-10-23 18:54:35 +00004637 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004638 // When we hit a DeclRefExpr we are looking at code that refers to a
4639 // variable's name. If it's not a reference variable we check if it has
4640 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00004641 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004642
Stephen Hines651f13c2014-04-23 16:59:28 -07004643 // If we leave the immediate function, the lifetime isn't about to end.
4644 if (DR->refersToEnclosingLocal())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004645 return nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07004646
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004647 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
4648 // Check if it refers to itself, e.g. "int& i = i;".
4649 if (V == ParentDecl)
4650 return DR;
4651
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004652 if (V->hasLocalStorage()) {
4653 if (!V->getType()->isReferenceType())
4654 return DR;
4655
4656 // Reference variable, follow through to the expression that
4657 // it points to.
4658 if (V->hasInit()) {
4659 // Add the reference variable to the "trail".
4660 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004661 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004662 }
4663 }
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004664 }
Mike Stump1eb44332009-09-09 15:08:12 +00004665
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004666 return nullptr;
Ted Kremenek06de2762007-08-17 16:46:58 +00004667 }
Mike Stump1eb44332009-09-09 15:08:12 +00004668
Ted Kremenek06de2762007-08-17 16:46:58 +00004669 case Stmt::UnaryOperatorClass: {
4670 // The only unary operator that make sense to handle here
4671 // is Deref. All others don't resolve to a "name." This includes
4672 // handling all sorts of rvalues passed to a unary operator.
4673 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004674
John McCall2de56d12010-08-25 11:45:40 +00004675 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004676 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004677
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004678 return nullptr;
Ted Kremenek06de2762007-08-17 16:46:58 +00004679 }
Mike Stump1eb44332009-09-09 15:08:12 +00004680
Ted Kremenek06de2762007-08-17 16:46:58 +00004681 case Stmt::ArraySubscriptExprClass: {
4682 // Array subscripts are potential references to data on the stack. We
4683 // retrieve the DeclRefExpr* for the array variable if it indeed
4684 // has local storage.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004685 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004686 }
Mike Stump1eb44332009-09-09 15:08:12 +00004687
Ted Kremenek06de2762007-08-17 16:46:58 +00004688 case Stmt::ConditionalOperatorClass: {
4689 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004690 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00004691 ConditionalOperator *C = cast<ConditionalOperator>(E);
4692
Anders Carlsson39073232007-11-30 19:04:31 +00004693 // Handle the GNU extension for missing LHS.
Stephen Hines651f13c2014-04-23 16:59:28 -07004694 if (Expr *LHSExpr = C->getLHS()) {
4695 // In C++, we can have a throw-expression, which has 'void' type.
4696 if (!LHSExpr->getType()->isVoidType())
4697 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
4698 return LHS;
4699 }
4700
4701 // In C++, we can have a throw-expression, which has 'void' type.
4702 if (C->getRHS()->getType()->isVoidType())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004703 return nullptr;
Anders Carlsson39073232007-11-30 19:04:31 +00004704
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004705 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004706 }
Mike Stump1eb44332009-09-09 15:08:12 +00004707
Ted Kremenek06de2762007-08-17 16:46:58 +00004708 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00004709 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00004710 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004711
Ted Kremenek06de2762007-08-17 16:46:58 +00004712 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00004713 if (M->isArrow())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004714 return nullptr;
Ted Kremeneka423e812010-09-02 01:12:13 +00004715
4716 // Check whether the member type is itself a reference, in which case
4717 // we're not going to refer to the member, but to what the member refers to.
4718 if (M->getMemberDecl()->getType()->isReferenceType())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004719 return nullptr;
Ted Kremeneka423e812010-09-02 01:12:13 +00004720
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004721 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004722 }
Mike Stump1eb44332009-09-09 15:08:12 +00004723
Douglas Gregor03e80032011-06-21 17:03:29 +00004724 case Stmt::MaterializeTemporaryExprClass:
4725 if (Expr *Result = EvalVal(
4726 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004727 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00004728 return Result;
4729
4730 return E;
4731
Ted Kremenek06de2762007-08-17 16:46:58 +00004732 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004733 // Check that we don't return or take the address of a reference to a
4734 // temporary. This is only useful in C++.
4735 if (!E->isTypeDependent() && E->isRValue())
4736 return E;
4737
4738 // Everything else: we simply don't reason about them.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07004739 return nullptr;
Ted Kremenek06de2762007-08-17 16:46:58 +00004740 }
Ted Kremenek68957a92010-08-04 20:01:07 +00004741} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00004742}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004743
Stephen Hines651f13c2014-04-23 16:59:28 -07004744void
4745Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
4746 SourceLocation ReturnLoc,
4747 bool isObjCMethod,
4748 const AttrVec *Attrs,
4749 const FunctionDecl *FD) {
4750 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
4751
4752 // Check if the return value is null but should not be.
4753 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
4754 CheckNonNullExpr(*this, RetValExp))
4755 Diag(ReturnLoc, diag::warn_null_ret)
4756 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
4757
4758 // C++11 [basic.stc.dynamic.allocation]p4:
4759 // If an allocation function declared with a non-throwing
4760 // exception-specification fails to allocate storage, it shall return
4761 // a null pointer. Any other allocation function that fails to allocate
4762 // storage shall indicate failure only by throwing an exception [...]
4763 if (FD) {
4764 OverloadedOperatorKind Op = FD->getOverloadedOperator();
4765 if (Op == OO_New || Op == OO_Array_New) {
4766 const FunctionProtoType *Proto
4767 = FD->getType()->castAs<FunctionProtoType>();
4768 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
4769 CheckNonNullExpr(*this, RetValExp))
4770 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
4771 << FD << getLangOpts().CPlusPlus11;
4772 }
4773 }
4774}
4775
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004776//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
4777
4778/// Check for comparisons of floating point operands using != and ==.
4779/// Issue a warning if these are no self-comparisons, as they are not likely
4780/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00004781void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieudd225092011-09-15 21:56:47 +00004782 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
4783 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004784
4785 // Special case: check for x == x (which is OK).
4786 // Do not emit warnings for such cases.
4787 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
4788 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
4789 if (DRL->getDecl() == DRR->getDecl())
David Blaikie980343b2012-07-16 20:47:22 +00004790 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004791
4792
Ted Kremenek1b500bb2007-11-29 00:59:04 +00004793 // Special case: check for comparisons against literals that can be exactly
4794 // represented by APFloat. In such cases, do not emit a warning. This
4795 // is a heuristic: often comparison against such literals are used to
4796 // detect if a value in a variable has not changed. This clearly can
4797 // lead to false negatives.
David Blaikie980343b2012-07-16 20:47:22 +00004798 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
4799 if (FLL->isExact())
4800 return;
4801 } else
4802 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
4803 if (FLR->isExact())
4804 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004805
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004806 // Check for comparisons with builtin types.
David Blaikie980343b2012-07-16 20:47:22 +00004807 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Stephen Hines651f13c2014-04-23 16:59:28 -07004808 if (CL->getBuiltinCallee())
David Blaikie980343b2012-07-16 20:47:22 +00004809 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004810
David Blaikie980343b2012-07-16 20:47:22 +00004811 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Stephen Hines651f13c2014-04-23 16:59:28 -07004812 if (CR->getBuiltinCallee())
David Blaikie980343b2012-07-16 20:47:22 +00004813 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004814
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004815 // Emit the diagnostic.
David Blaikie980343b2012-07-16 20:47:22 +00004816 Diag(Loc, diag::warn_floatingpoint_eq)
4817 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004818}
John McCallba26e582010-01-04 23:21:16 +00004819
John McCallf2370c92010-01-06 05:24:50 +00004820//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
4821//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00004822
John McCallf2370c92010-01-06 05:24:50 +00004823namespace {
John McCallba26e582010-01-04 23:21:16 +00004824
John McCallf2370c92010-01-06 05:24:50 +00004825/// Structure recording the 'active' range of an integer-valued
4826/// expression.
4827struct IntRange {
4828 /// The number of bits active in the int.
4829 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00004830
John McCallf2370c92010-01-06 05:24:50 +00004831 /// True if the int is known not to have negative values.
4832 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00004833
John McCallf2370c92010-01-06 05:24:50 +00004834 IntRange(unsigned Width, bool NonNegative)
4835 : Width(Width), NonNegative(NonNegative)
4836 {}
John McCallba26e582010-01-04 23:21:16 +00004837
John McCall1844a6e2010-11-10 23:38:19 +00004838 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00004839 static IntRange forBoolType() {
4840 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00004841 }
4842
John McCall1844a6e2010-11-10 23:38:19 +00004843 /// Returns the range of an opaque value of the given integral type.
4844 static IntRange forValueOfType(ASTContext &C, QualType T) {
4845 return forValueOfCanonicalType(C,
4846 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00004847 }
4848
John McCall1844a6e2010-11-10 23:38:19 +00004849 /// Returns the range of an opaque value of a canonical integral type.
4850 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00004851 assert(T->isCanonicalUnqualified());
4852
4853 if (const VectorType *VT = dyn_cast<VectorType>(T))
4854 T = VT->getElementType().getTypePtr();
4855 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4856 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00004857
David Majnemerf9eaf982013-06-07 22:07:20 +00004858 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00004859 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemerf9eaf982013-06-07 22:07:20 +00004860 EnumDecl *Enum = ET->getDecl();
4861 if (!Enum->isCompleteDefinition())
4862 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall091f23f2010-11-09 22:22:12 +00004863
David Majnemerf9eaf982013-06-07 22:07:20 +00004864 unsigned NumPositive = Enum->getNumPositiveBits();
4865 unsigned NumNegative = Enum->getNumNegativeBits();
John McCall323ed742010-05-06 08:58:33 +00004866
David Majnemerf9eaf982013-06-07 22:07:20 +00004867 if (NumNegative == 0)
4868 return IntRange(NumPositive, true/*NonNegative*/);
4869 else
4870 return IntRange(std::max(NumPositive + 1, NumNegative),
4871 false/*NonNegative*/);
John McCall323ed742010-05-06 08:58:33 +00004872 }
John McCallf2370c92010-01-06 05:24:50 +00004873
4874 const BuiltinType *BT = cast<BuiltinType>(T);
4875 assert(BT->isInteger());
4876
4877 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4878 }
4879
John McCall1844a6e2010-11-10 23:38:19 +00004880 /// Returns the "target" range of a canonical integral type, i.e.
4881 /// the range of values expressible in the type.
4882 ///
4883 /// This matches forValueOfCanonicalType except that enums have the
4884 /// full range of their type, not the range of their enumerators.
4885 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4886 assert(T->isCanonicalUnqualified());
4887
4888 if (const VectorType *VT = dyn_cast<VectorType>(T))
4889 T = VT->getElementType().getTypePtr();
4890 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4891 T = CT->getElementType().getTypePtr();
4892 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00004893 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00004894
4895 const BuiltinType *BT = cast<BuiltinType>(T);
4896 assert(BT->isInteger());
4897
4898 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4899 }
4900
4901 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00004902 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00004903 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00004904 L.NonNegative && R.NonNegative);
4905 }
4906
John McCall1844a6e2010-11-10 23:38:19 +00004907 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00004908 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00004909 return IntRange(std::min(L.Width, R.Width),
4910 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00004911 }
4912};
4913
Ted Kremenek0692a192012-01-31 05:37:37 +00004914static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4915 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004916 if (value.isSigned() && value.isNegative())
4917 return IntRange(value.getMinSignedBits(), false);
4918
4919 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00004920 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004921
4922 // isNonNegative() just checks the sign bit without considering
4923 // signedness.
4924 return IntRange(value.getActiveBits(), true);
4925}
4926
Ted Kremenek0692a192012-01-31 05:37:37 +00004927static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4928 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004929 if (result.isInt())
4930 return GetValueRange(C, result.getInt(), MaxWidth);
4931
4932 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00004933 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4934 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4935 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4936 R = IntRange::join(R, El);
4937 }
John McCallf2370c92010-01-06 05:24:50 +00004938 return R;
4939 }
4940
4941 if (result.isComplexInt()) {
4942 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4943 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4944 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00004945 }
4946
4947 // This can happen with lossless casts to intptr_t of "based" lvalues.
4948 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00004949 // FIXME: The only reason we need to pass the type in here is to get
4950 // the sign right on this one case. It would be nice if APValue
4951 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00004952 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004953 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00004954}
John McCallf2370c92010-01-06 05:24:50 +00004955
Eli Friedman09bddcf2013-07-08 20:20:06 +00004956static QualType GetExprType(Expr *E) {
4957 QualType Ty = E->getType();
4958 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
4959 Ty = AtomicRHS->getValueType();
4960 return Ty;
4961}
4962
John McCallf2370c92010-01-06 05:24:50 +00004963/// Pseudo-evaluate the given integer expression, estimating the
4964/// range of values it might take.
4965///
4966/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek0692a192012-01-31 05:37:37 +00004967static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004968 E = E->IgnoreParens();
4969
4970 // Try a full evaluation first.
4971 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004972 if (E->EvaluateAsRValue(result, C))
Eli Friedman09bddcf2013-07-08 20:20:06 +00004973 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004974
4975 // I think we only want to look through implicit casts here; if the
4976 // user has an explicit widening cast, we should treat the value as
4977 // being of the new, wider type.
4978 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00004979 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00004980 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4981
Eli Friedman09bddcf2013-07-08 20:20:06 +00004982 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCallf2370c92010-01-06 05:24:50 +00004983
John McCall2de56d12010-08-25 11:45:40 +00004984 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00004985
John McCallf2370c92010-01-06 05:24:50 +00004986 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00004987 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00004988 return OutputTypeRange;
4989
4990 IntRange SubRange
4991 = GetExprRange(C, CE->getSubExpr(),
4992 std::min(MaxWidth, OutputTypeRange.Width));
4993
4994 // Bail out if the subexpr's range is as wide as the cast type.
4995 if (SubRange.Width >= OutputTypeRange.Width)
4996 return OutputTypeRange;
4997
4998 // Otherwise, we take the smaller width, and we're non-negative if
4999 // either the output type or the subexpr is.
5000 return IntRange(SubRange.Width,
5001 SubRange.NonNegative || OutputTypeRange.NonNegative);
5002 }
5003
5004 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5005 // If we can fold the condition, just take that operand.
5006 bool CondResult;
5007 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5008 return GetExprRange(C, CondResult ? CO->getTrueExpr()
5009 : CO->getFalseExpr(),
5010 MaxWidth);
5011
5012 // Otherwise, conservatively merge.
5013 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5014 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5015 return IntRange::join(L, R);
5016 }
5017
5018 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5019 switch (BO->getOpcode()) {
5020
5021 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00005022 case BO_LAnd:
5023 case BO_LOr:
5024 case BO_LT:
5025 case BO_GT:
5026 case BO_LE:
5027 case BO_GE:
5028 case BO_EQ:
5029 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00005030 return IntRange::forBoolType();
5031
John McCall862ff872011-07-13 06:35:24 +00005032 // The type of the assignments is the type of the LHS, so the RHS
5033 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00005034 case BO_MulAssign:
5035 case BO_DivAssign:
5036 case BO_RemAssign:
5037 case BO_AddAssign:
5038 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00005039 case BO_XorAssign:
5040 case BO_OrAssign:
5041 // TODO: bitfields?
Eli Friedman09bddcf2013-07-08 20:20:06 +00005042 return IntRange::forValueOfType(C, GetExprType(E));
John McCallc0cd21d2010-02-23 19:22:29 +00005043
John McCall862ff872011-07-13 06:35:24 +00005044 // Simple assignments just pass through the RHS, which will have
5045 // been coerced to the LHS type.
5046 case BO_Assign:
5047 // TODO: bitfields?
5048 return GetExprRange(C, BO->getRHS(), MaxWidth);
5049
John McCallf2370c92010-01-06 05:24:50 +00005050 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00005051 case BO_PtrMemD:
5052 case BO_PtrMemI:
Eli Friedman09bddcf2013-07-08 20:20:06 +00005053 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00005054
John McCall60fad452010-01-06 22:07:33 +00005055 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00005056 case BO_And:
5057 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00005058 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5059 GetExprRange(C, BO->getRHS(), MaxWidth));
5060
John McCallf2370c92010-01-06 05:24:50 +00005061 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00005062 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00005063 // ...except that we want to treat '1 << (blah)' as logically
5064 // positive. It's an important idiom.
5065 if (IntegerLiteral *I
5066 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5067 if (I->getValue() == 1) {
Eli Friedman09bddcf2013-07-08 20:20:06 +00005068 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall3aae6092010-04-07 01:14:35 +00005069 return IntRange(R.Width, /*NonNegative*/ true);
5070 }
5071 }
5072 // fallthrough
5073
John McCall2de56d12010-08-25 11:45:40 +00005074 case BO_ShlAssign:
Eli Friedman09bddcf2013-07-08 20:20:06 +00005075 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00005076
John McCall60fad452010-01-06 22:07:33 +00005077 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00005078 case BO_Shr:
5079 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00005080 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5081
5082 // If the shift amount is a positive constant, drop the width by
5083 // that much.
5084 llvm::APSInt shift;
5085 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5086 shift.isNonNegative()) {
5087 unsigned zext = shift.getZExtValue();
5088 if (zext >= L.Width)
5089 L.Width = (L.NonNegative ? 0 : 1);
5090 else
5091 L.Width -= zext;
5092 }
5093
5094 return L;
5095 }
5096
5097 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00005098 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00005099 return GetExprRange(C, BO->getRHS(), MaxWidth);
5100
John McCall60fad452010-01-06 22:07:33 +00005101 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00005102 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00005103 if (BO->getLHS()->getType()->isPointerType())
Eli Friedman09bddcf2013-07-08 20:20:06 +00005104 return IntRange::forValueOfType(C, GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00005105 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00005106
John McCall00fe7612011-07-14 22:39:48 +00005107 // The width of a division result is mostly determined by the size
5108 // of the LHS.
5109 case BO_Div: {
5110 // Don't 'pre-truncate' the operands.
Eli Friedman09bddcf2013-07-08 20:20:06 +00005111 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00005112 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5113
5114 // If the divisor is constant, use that.
5115 llvm::APSInt divisor;
5116 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5117 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5118 if (log2 >= L.Width)
5119 L.Width = (L.NonNegative ? 0 : 1);
5120 else
5121 L.Width = std::min(L.Width - log2, MaxWidth);
5122 return L;
5123 }
5124
5125 // Otherwise, just use the LHS's width.
5126 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5127 return IntRange(L.Width, L.NonNegative && R.NonNegative);
5128 }
5129
5130 // The result of a remainder can't be larger than the result of
5131 // either side.
5132 case BO_Rem: {
5133 // Don't 'pre-truncate' the operands.
Eli Friedman09bddcf2013-07-08 20:20:06 +00005134 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00005135 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5136 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5137
5138 IntRange meet = IntRange::meet(L, R);
5139 meet.Width = std::min(meet.Width, MaxWidth);
5140 return meet;
5141 }
5142
5143 // The default behavior is okay for these.
5144 case BO_Mul:
5145 case BO_Add:
5146 case BO_Xor:
5147 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00005148 break;
5149 }
5150
John McCall00fe7612011-07-14 22:39:48 +00005151 // The default case is to treat the operation as if it were closed
5152 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00005153 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5154 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5155 return IntRange::join(L, R);
5156 }
5157
5158 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5159 switch (UO->getOpcode()) {
5160 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00005161 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00005162 return IntRange::forBoolType();
5163
5164 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00005165 case UO_Deref:
5166 case UO_AddrOf: // should be impossible
Eli Friedman09bddcf2013-07-08 20:20:06 +00005167 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00005168
5169 default:
5170 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5171 }
5172 }
5173
Ted Kremenek728a1fb2013-10-14 18:55:27 +00005174 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5175 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5176
John McCall993f43f2013-05-06 21:39:12 +00005177 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005178 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00005179 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00005180
Eli Friedman09bddcf2013-07-08 20:20:06 +00005181 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00005182}
John McCall51313c32010-01-04 23:31:57 +00005183
Ted Kremenek0692a192012-01-31 05:37:37 +00005184static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedman09bddcf2013-07-08 20:20:06 +00005185 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCall323ed742010-05-06 08:58:33 +00005186}
5187
John McCall51313c32010-01-04 23:31:57 +00005188/// Checks whether the given value, which currently has the given
5189/// source semantics, has the same value when coerced through the
5190/// target semantics.
Ted Kremenek0692a192012-01-31 05:37:37 +00005191static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5192 const llvm::fltSemantics &Src,
5193 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00005194 llvm::APFloat truncated = value;
5195
5196 bool ignored;
5197 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5198 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5199
5200 return truncated.bitwiseIsEqual(value);
5201}
5202
5203/// Checks whether the given value, which currently has the given
5204/// source semantics, has the same value when coerced through the
5205/// target semantics.
5206///
5207/// The value might be a vector of floats (or a complex number).
Ted Kremenek0692a192012-01-31 05:37:37 +00005208static bool IsSameFloatAfterCast(const APValue &value,
5209 const llvm::fltSemantics &Src,
5210 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00005211 if (value.isFloat())
5212 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5213
5214 if (value.isVector()) {
5215 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5216 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5217 return false;
5218 return true;
5219 }
5220
5221 assert(value.isComplexFloat());
5222 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5223 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5224}
5225
Ted Kremenek0692a192012-01-31 05:37:37 +00005226static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00005227
Ted Kremeneke3b159c2010-09-23 21:43:44 +00005228static bool IsZero(Sema &S, Expr *E) {
5229 // Suppress cases where we are comparing against an enum constant.
5230 if (const DeclRefExpr *DR =
5231 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5232 if (isa<EnumConstantDecl>(DR->getDecl()))
5233 return false;
5234
5235 // Suppress cases where the '0' value is expanded from a macro.
5236 if (E->getLocStart().isMacroID())
5237 return false;
5238
John McCall323ed742010-05-06 08:58:33 +00005239 llvm::APSInt Value;
5240 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5241}
5242
John McCall372e1032010-10-06 00:25:24 +00005243static bool HasEnumType(Expr *E) {
5244 // Strip off implicit integral promotions.
5245 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00005246 if (ICE->getCastKind() != CK_IntegralCast &&
5247 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00005248 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00005249 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00005250 }
5251
5252 return E->getType()->isEnumeralType();
5253}
5254
Ted Kremenek0692a192012-01-31 05:37:37 +00005255static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieucbc19872013-11-01 21:47:19 +00005256 // Disable warning in template instantiations.
5257 if (!S.ActiveTemplateInstantiations.empty())
5258 return;
5259
John McCall2de56d12010-08-25 11:45:40 +00005260 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00005261 if (E->isValueDependent())
5262 return;
5263
John McCall2de56d12010-08-25 11:45:40 +00005264 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00005265 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00005266 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00005267 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005268 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00005269 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00005270 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00005271 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005272 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00005273 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00005274 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00005275 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00005276 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00005277 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00005278 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00005279 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5280 }
5281}
5282
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005283static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00005284 Expr *Constant, Expr *Other,
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005285 llvm::APSInt Value,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00005286 bool RhsConstant) {
Richard Trieu311cb2b2013-11-01 21:19:43 +00005287 // Disable warning in template instantiations.
5288 if (!S.ActiveTemplateInstantiations.empty())
5289 return;
5290
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005291 // TODO: Investigate using GetExprRange() to get tighter bounds
5292 // on the bit ranges.
5293 QualType OtherT = Other->getType();
5294 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
5295 unsigned OtherWidth = OtherRange.Width;
5296
5297 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
5298
Richard Trieu526e6272012-11-14 22:50:24 +00005299 // 0 values are handled later by CheckTrivialUnsignedComparison().
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005300 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu526e6272012-11-14 22:50:24 +00005301 return;
5302
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005303 BinaryOperatorKind op = E->getOpcode();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005304 bool IsTrue = true;
Richard Trieu526e6272012-11-14 22:50:24 +00005305
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005306 // Used for diagnostic printout.
5307 enum {
5308 LiteralConstant = 0,
5309 CXXBoolLiteralTrue,
5310 CXXBoolLiteralFalse
5311 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu526e6272012-11-14 22:50:24 +00005312
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005313 if (!OtherIsBooleanType) {
5314 QualType ConstantT = Constant->getType();
5315 QualType CommonT = E->getLHS()->getType();
Richard Trieu526e6272012-11-14 22:50:24 +00005316
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005317 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
5318 return;
5319 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
5320 "comparison with non-integer type");
5321
5322 bool ConstantSigned = ConstantT->isSignedIntegerType();
5323 bool CommonSigned = CommonT->isSignedIntegerType();
5324
5325 bool EqualityOnly = false;
5326
5327 if (CommonSigned) {
5328 // The common type is signed, therefore no signed to unsigned conversion.
5329 if (!OtherRange.NonNegative) {
5330 // Check that the constant is representable in type OtherT.
5331 if (ConstantSigned) {
5332 if (OtherWidth >= Value.getMinSignedBits())
5333 return;
5334 } else { // !ConstantSigned
5335 if (OtherWidth >= Value.getActiveBits() + 1)
5336 return;
5337 }
5338 } else { // !OtherSigned
5339 // Check that the constant is representable in type OtherT.
5340 // Negative values are out of range.
5341 if (ConstantSigned) {
5342 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
5343 return;
5344 } else { // !ConstantSigned
5345 if (OtherWidth >= Value.getActiveBits())
5346 return;
5347 }
Richard Trieu526e6272012-11-14 22:50:24 +00005348 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005349 } else { // !CommonSigned
5350 if (OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00005351 if (OtherWidth >= Value.getActiveBits())
5352 return;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005353 } else if (!OtherRange.NonNegative && !ConstantSigned) {
5354 // Check to see if the constant is representable in OtherT.
5355 if (OtherWidth > Value.getActiveBits())
5356 return;
5357 // Check to see if the constant is equivalent to a negative value
5358 // cast to CommonT.
5359 if (S.Context.getIntWidth(ConstantT) ==
5360 S.Context.getIntWidth(CommonT) &&
5361 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
5362 return;
5363 // The constant value rests between values that OtherT can represent
5364 // after conversion. Relational comparison still works, but equality
5365 // comparisons will be tautological.
5366 EqualityOnly = true;
5367 } else { // OtherSigned && ConstantSigned
5368 assert(0 && "Two signed types converted to unsigned types.");
Richard Trieu526e6272012-11-14 22:50:24 +00005369 }
5370 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005371
5372 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
5373
5374 if (op == BO_EQ || op == BO_NE) {
5375 IsTrue = op == BO_NE;
5376 } else if (EqualityOnly) {
5377 return;
5378 } else if (RhsConstant) {
5379 if (op == BO_GT || op == BO_GE)
5380 IsTrue = !PositiveConstant;
5381 else // op == BO_LT || op == BO_LE
5382 IsTrue = PositiveConstant;
5383 } else {
5384 if (op == BO_LT || op == BO_LE)
5385 IsTrue = !PositiveConstant;
5386 else // op == BO_GT || op == BO_GE
5387 IsTrue = PositiveConstant;
Richard Trieu526e6272012-11-14 22:50:24 +00005388 }
Fariborz Jahaniana193f202012-09-20 19:36:41 +00005389 } else {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005390 // Other isKnownToHaveBooleanValue
5391 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
5392 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
5393 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
5394
5395 static const struct LinkedConditions {
5396 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
5397 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
5398 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
5399 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
5400 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
5401 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
5402
5403 } TruthTable = {
5404 // Constant on LHS. | Constant on RHS. |
5405 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
5406 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
5407 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
5408 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
5409 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
5410 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
5411 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
5412 };
5413
5414 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
5415
5416 enum ConstantValue ConstVal = Zero;
5417 if (Value.isUnsigned() || Value.isNonNegative()) {
5418 if (Value == 0) {
5419 LiteralOrBoolConstant =
5420 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
5421 ConstVal = Zero;
5422 } else if (Value == 1) {
5423 LiteralOrBoolConstant =
5424 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
5425 ConstVal = One;
5426 } else {
5427 LiteralOrBoolConstant = LiteralConstant;
5428 ConstVal = GT_One;
5429 }
5430 } else {
5431 ConstVal = LT_Zero;
5432 }
5433
5434 CompareBoolWithConstantResult CmpRes;
5435
5436 switch (op) {
5437 case BO_LT:
5438 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
5439 break;
5440 case BO_GT:
5441 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
5442 break;
5443 case BO_LE:
5444 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
5445 break;
5446 case BO_GE:
5447 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
5448 break;
5449 case BO_EQ:
5450 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
5451 break;
5452 case BO_NE:
5453 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
5454 break;
5455 default:
5456 CmpRes = Unkwn;
5457 break;
5458 }
5459
5460 if (CmpRes == AFals) {
5461 IsTrue = false;
5462 } else if (CmpRes == ATrue) {
5463 IsTrue = true;
5464 } else {
5465 return;
5466 }
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005467 }
Ted Kremenek7adf3a92013-03-15 21:50:10 +00005468
5469 // If this is a comparison to an enum constant, include that
5470 // constant in the diagnostic.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005471 const EnumConstantDecl *ED = nullptr;
Ted Kremenek7adf3a92013-03-15 21:50:10 +00005472 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
5473 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
5474
5475 SmallString<64> PrettySourceValue;
5476 llvm::raw_svector_ostream OS(PrettySourceValue);
5477 if (ED)
Ted Kremenek9de50942013-03-15 22:02:46 +00005478 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenek7adf3a92013-03-15 21:50:10 +00005479 else
5480 OS << Value;
5481
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005482 S.DiagRuntimeBehavior(
5483 E->getOperatorLoc(), E,
5484 S.PDiag(diag::warn_out_of_range_compare)
5485 << OS.str() << LiteralOrBoolConstant
5486 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
5487 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005488}
5489
John McCall323ed742010-05-06 08:58:33 +00005490/// Analyze the operands of the given comparison. Implements the
5491/// fallback case from AnalyzeComparison.
Ted Kremenek0692a192012-01-31 05:37:37 +00005492static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00005493 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5494 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00005495}
John McCall51313c32010-01-04 23:31:57 +00005496
John McCallba26e582010-01-04 23:21:16 +00005497/// \brief Implements -Wsign-compare.
5498///
Richard Trieudd225092011-09-15 21:56:47 +00005499/// \param E the binary operator to check for warnings
Ted Kremenek0692a192012-01-31 05:37:37 +00005500static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCall323ed742010-05-06 08:58:33 +00005501 // The type the comparison is being performed in.
5502 QualType T = E->getLHS()->getType();
5503 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
5504 && "comparison with mismatched types");
Fariborz Jahanianab4702f2012-09-18 17:46:26 +00005505 if (E->isValueDependent())
5506 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00005507
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005508 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
5509 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005510
5511 bool IsComparisonConstant = false;
5512
Fariborz Jahaniana193f202012-09-20 19:36:41 +00005513 // Check whether an integer constant comparison results in a value
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005514 // of 'true' or 'false'.
5515 if (T->isIntegralType(S.Context)) {
5516 llvm::APSInt RHSValue;
5517 bool IsRHSIntegralLiteral =
5518 RHS->isIntegerConstantExpr(RHSValue, S.Context);
5519 llvm::APSInt LHSValue;
5520 bool IsLHSIntegralLiteral =
5521 LHS->isIntegerConstantExpr(LHSValue, S.Context);
5522 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
5523 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
5524 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
5525 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
5526 else
5527 IsComparisonConstant =
5528 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahaniana193f202012-09-20 19:36:41 +00005529 } else if (!T->hasUnsignedIntegerRepresentation())
5530 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005531
John McCall323ed742010-05-06 08:58:33 +00005532 // We don't do anything special if this isn't an unsigned integral
5533 // comparison: we're only interested in integral comparisons, and
5534 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00005535 //
5536 // We also don't care about value-dependent expressions or expressions
5537 // whose result is a constant.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005538 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCall323ed742010-05-06 08:58:33 +00005539 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00005540
John McCall323ed742010-05-06 08:58:33 +00005541 // Check to see if one of the (unmodified) operands is of different
5542 // signedness.
5543 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00005544 if (LHS->getType()->hasSignedIntegerRepresentation()) {
5545 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00005546 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00005547 signedOperand = LHS;
5548 unsignedOperand = RHS;
5549 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
5550 signedOperand = RHS;
5551 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00005552 } else {
John McCall323ed742010-05-06 08:58:33 +00005553 CheckTrivialUnsignedComparison(S, E);
5554 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00005555 }
5556
John McCall323ed742010-05-06 08:58:33 +00005557 // Otherwise, calculate the effective range of the signed operand.
5558 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00005559
John McCall323ed742010-05-06 08:58:33 +00005560 // Go ahead and analyze implicit conversions in the operands. Note
5561 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00005562 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
5563 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00005564
John McCall323ed742010-05-06 08:58:33 +00005565 // If the signed range is non-negative, -Wsign-compare won't fire,
5566 // but we should still check for comparisons which are always true
5567 // or false.
5568 if (signedRange.NonNegative)
5569 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00005570
5571 // For (in)equality comparisons, if the unsigned operand is a
5572 // constant which cannot collide with a overflowed signed operand,
5573 // then reinterpreting the signed operand as unsigned will not
5574 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00005575 if (E->isEqualityOp()) {
5576 unsigned comparisonWidth = S.Context.getIntWidth(T);
5577 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00005578
John McCall323ed742010-05-06 08:58:33 +00005579 // We should never be unable to prove that the unsigned operand is
5580 // non-negative.
5581 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
5582
5583 if (unsignedRange.Width < comparisonWidth)
5584 return;
5585 }
5586
Douglas Gregor6d3b93d2012-05-01 01:53:49 +00005587 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5588 S.PDiag(diag::warn_mixed_sign_comparison)
5589 << LHS->getType() << RHS->getType()
5590 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallba26e582010-01-04 23:21:16 +00005591}
5592
John McCall15d7d122010-11-11 03:21:53 +00005593/// Analyzes an attempt to assign the given value to a bitfield.
5594///
5595/// Returns true if there was something fishy about the attempt.
Ted Kremenek0692a192012-01-31 05:37:37 +00005596static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
5597 SourceLocation InitLoc) {
John McCall15d7d122010-11-11 03:21:53 +00005598 assert(Bitfield->isBitField());
5599 if (Bitfield->isInvalidDecl())
5600 return false;
5601
John McCall91b60142010-11-11 05:33:51 +00005602 // White-list bool bitfields.
5603 if (Bitfield->getType()->isBooleanType())
5604 return false;
5605
Douglas Gregor46ff3032011-02-04 13:09:01 +00005606 // Ignore value- or type-dependent expressions.
5607 if (Bitfield->getBitWidth()->isValueDependent() ||
5608 Bitfield->getBitWidth()->isTypeDependent() ||
5609 Init->isValueDependent() ||
5610 Init->isTypeDependent())
5611 return false;
5612
John McCall15d7d122010-11-11 03:21:53 +00005613 Expr *OriginalInit = Init->IgnoreParenImpCasts();
5614
Richard Smith80d4b552011-12-28 19:48:30 +00005615 llvm::APSInt Value;
5616 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00005617 return false;
5618
John McCall15d7d122010-11-11 03:21:53 +00005619 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005620 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00005621
5622 if (OriginalWidth <= FieldWidth)
5623 return false;
5624
Eli Friedman3a643af2012-01-26 23:11:39 +00005625 // Compute the value which the bitfield will contain.
Jay Foad9f71a8f2010-12-07 08:25:34 +00005626 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedman3a643af2012-01-26 23:11:39 +00005627 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall15d7d122010-11-11 03:21:53 +00005628
Eli Friedman3a643af2012-01-26 23:11:39 +00005629 // Check whether the stored value is equal to the original value.
5630 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieue1ecdc12012-07-23 20:21:35 +00005631 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall15d7d122010-11-11 03:21:53 +00005632 return false;
5633
Eli Friedman3a643af2012-01-26 23:11:39 +00005634 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedman34ff0622012-02-02 00:40:20 +00005635 // therefore don't strictly fit into a signed bitfield of width 1.
5636 if (FieldWidth == 1 && Value == 1)
Eli Friedman3a643af2012-01-26 23:11:39 +00005637 return false;
5638
John McCall15d7d122010-11-11 03:21:53 +00005639 std::string PrettyValue = Value.toString(10);
5640 std::string PrettyTrunc = TruncatedValue.toString(10);
5641
5642 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
5643 << PrettyValue << PrettyTrunc << OriginalInit->getType()
5644 << Init->getSourceRange();
5645
5646 return true;
5647}
5648
John McCallbeb22aa2010-11-09 23:24:47 +00005649/// Analyze the given simple or compound assignment for warning-worthy
5650/// operations.
Ted Kremenek0692a192012-01-31 05:37:37 +00005651static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCallbeb22aa2010-11-09 23:24:47 +00005652 // Just recurse on the LHS.
5653 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5654
5655 // We want to recurse on the RHS as normal unless we're assigning to
5656 // a bitfield.
John McCall993f43f2013-05-06 21:39:12 +00005657 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005658 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall15d7d122010-11-11 03:21:53 +00005659 E->getOperatorLoc())) {
5660 // Recurse, ignoring any implicit conversions on the RHS.
5661 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
5662 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00005663 }
5664 }
5665
5666 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
5667}
5668
John McCall51313c32010-01-04 23:31:57 +00005669/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00005670static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00005671 SourceLocation CContext, unsigned diag,
5672 bool pruneControlFlow = false) {
5673 if (pruneControlFlow) {
5674 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5675 S.PDiag(diag)
5676 << SourceType << T << E->getSourceRange()
5677 << SourceRange(CContext));
5678 return;
5679 }
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005680 S.Diag(E->getExprLoc(), diag)
5681 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
5682}
5683
Chandler Carruthe1b02e02011-04-05 06:47:57 +00005684/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00005685static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00005686 SourceLocation CContext, unsigned diag,
5687 bool pruneControlFlow = false) {
5688 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruthe1b02e02011-04-05 06:47:57 +00005689}
5690
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005691/// Diagnose an implicit cast from a literal expression. Does not warn when the
5692/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00005693void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
5694 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005695 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00005696 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005697 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00005698 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
5699 T->hasUnsignedIntegerRepresentation());
5700 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00005701 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005702 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00005703 return;
5704
Eli Friedman4e1a82c2013-08-29 23:44:43 +00005705 // FIXME: Force the precision of the source value down so we don't print
5706 // digits which are usually useless (we don't really care here if we
5707 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
5708 // would automatically print the shortest representation, but it's a bit
5709 // tricky to implement.
David Blaikiebe0ee872012-05-15 16:56:36 +00005710 SmallString<16> PrettySourceValue;
Eli Friedman4e1a82c2013-08-29 23:44:43 +00005711 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
5712 precision = (precision * 59 + 195) / 196;
5713 Value.toString(PrettySourceValue, precision);
5714
David Blaikiede7e7b82012-05-15 17:18:27 +00005715 SmallString<16> PrettyTargetValue;
David Blaikiebe0ee872012-05-15 16:56:36 +00005716 if (T->isSpecificBuiltinType(BuiltinType::Bool))
5717 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
5718 else
David Blaikiede7e7b82012-05-15 17:18:27 +00005719 IntegerValue.toString(PrettyTargetValue);
David Blaikiebe0ee872012-05-15 16:56:36 +00005720
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005721 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikiebe0ee872012-05-15 16:56:36 +00005722 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
5723 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00005724}
5725
John McCall091f23f2010-11-09 22:22:12 +00005726std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
5727 if (!Range.Width) return "0";
5728
5729 llvm::APSInt ValueInRange = Value;
5730 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00005731 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00005732 return ValueInRange.toString(10);
5733}
5734
Hans Wennborg88617a22012-08-28 15:44:30 +00005735static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
5736 if (!isa<ImplicitCastExpr>(Ex))
5737 return false;
5738
5739 Expr *InnerE = Ex->IgnoreParenImpCasts();
5740 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
5741 const Type *Source =
5742 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5743 if (Target->isDependentType())
5744 return false;
5745
5746 const BuiltinType *FloatCandidateBT =
5747 dyn_cast<BuiltinType>(ToBool ? Source : Target);
5748 const Type *BoolCandidateType = ToBool ? Target : Source;
5749
5750 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
5751 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
5752}
5753
5754void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
5755 SourceLocation CC) {
5756 unsigned NumArgs = TheCall->getNumArgs();
5757 for (unsigned i = 0; i < NumArgs; ++i) {
5758 Expr *CurrA = TheCall->getArg(i);
5759 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
5760 continue;
5761
5762 bool IsSwapped = ((i > 0) &&
5763 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
5764 IsSwapped |= ((i < (NumArgs - 1)) &&
5765 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
5766 if (IsSwapped) {
5767 // Warn on this floating-point to bool conversion.
5768 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
5769 CurrA->getType(), CC,
5770 diag::warn_impcast_floating_point_to_bool);
5771 }
5772 }
5773}
5774
John McCall323ed742010-05-06 08:58:33 +00005775void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07005776 SourceLocation CC, bool *ICContext = nullptr) {
John McCall323ed742010-05-06 08:58:33 +00005777 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00005778
John McCall323ed742010-05-06 08:58:33 +00005779 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
5780 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
5781 if (Source == Target) return;
5782 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00005783
Chandler Carruth108f7562011-07-26 05:40:03 +00005784 // If the conversion context location is invalid don't complain. We also
5785 // don't want to emit a warning if the issue occurs from the expansion of
5786 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
5787 // delay this check as long as possible. Once we detect we are in that
5788 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00005789 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00005790 return;
5791
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005792 // Diagnose implicit casts to bool.
5793 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
5794 if (isa<StringLiteral>(E))
5795 // Warn on string literal to bool. Checks for string literals in logical
Stephen Hines651f13c2014-04-23 16:59:28 -07005796 // and expressions, for instance, assert(0 && "error here"), are
5797 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005798 return DiagnoseImpCast(S, E, T, CC,
5799 diag::warn_impcast_string_literal_to_bool);
Stephen Hines651f13c2014-04-23 16:59:28 -07005800 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
5801 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
5802 // This covers the literal expressions that evaluate to Objective-C
5803 // objects.
5804 return DiagnoseImpCast(S, E, T, CC,
5805 diag::warn_impcast_objective_c_literal_to_bool);
5806 }
5807 if (Source->isPointerType() || Source->canDecayToPointerType()) {
5808 // Warn on pointer to bool conversion that is always true.
5809 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
5810 SourceRange(CC));
Lang Hamese14ca9f2011-12-05 20:49:50 +00005811 }
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005812 }
John McCall51313c32010-01-04 23:31:57 +00005813
5814 // Strip vector types.
5815 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00005816 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005817 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005818 return;
John McCallb4eb64d2010-10-08 02:01:28 +00005819 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005820 }
Chris Lattnerb792b302011-06-14 04:51:15 +00005821
5822 // If the vector cast is cast between two vectors of the same size, it is
5823 // a bitcast, not a conversion.
5824 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
5825 return;
John McCall51313c32010-01-04 23:31:57 +00005826
5827 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
5828 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
5829 }
Stephen Hines651f13c2014-04-23 16:59:28 -07005830 if (auto VecTy = dyn_cast<VectorType>(Target))
5831 Target = VecTy->getElementType().getTypePtr();
John McCall51313c32010-01-04 23:31:57 +00005832
5833 // Strip complex types.
5834 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00005835 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005836 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005837 return;
5838
John McCallb4eb64d2010-10-08 02:01:28 +00005839 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005840 }
John McCall51313c32010-01-04 23:31:57 +00005841
5842 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
5843 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
5844 }
5845
5846 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
5847 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
5848
5849 // If the source is floating point...
5850 if (SourceBT && SourceBT->isFloatingPoint()) {
5851 // ...and the target is floating point...
5852 if (TargetBT && TargetBT->isFloatingPoint()) {
5853 // ...then warn if we're dropping FP rank.
5854
5855 // Builtin FP kinds are ordered by increasing FP rank.
5856 if (SourceBT->getKind() > TargetBT->getKind()) {
5857 // Don't warn about float constants that are precisely
5858 // representable in the target type.
5859 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00005860 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00005861 // Value might be a float, a float vector, or a float complex.
5862 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00005863 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
5864 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00005865 return;
5866 }
5867
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005868 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005869 return;
5870
John McCallb4eb64d2010-10-08 02:01:28 +00005871 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00005872 }
5873 return;
5874 }
5875
Ted Kremenekef9ff882011-03-10 20:03:42 +00005876 // If the target is integral, always warn.
David Blaikiebe0ee872012-05-15 16:56:36 +00005877 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005878 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005879 return;
5880
Chandler Carrutha5b93322011-02-17 11:05:49 +00005881 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00005882 // We also want to warn on, e.g., "int i = -1.234"
5883 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
5884 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
5885 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
5886
Chandler Carruthf65076e2011-04-10 08:36:24 +00005887 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
5888 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00005889 } else {
5890 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
5891 }
5892 }
John McCall51313c32010-01-04 23:31:57 +00005893
Hans Wennborg88617a22012-08-28 15:44:30 +00005894 // If the target is bool, warn if expr is a function or method call.
5895 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
5896 isa<CallExpr>(E)) {
5897 // Check last argument of function call to see if it is an
5898 // implicit cast from a type matching the type the result
5899 // is being cast to.
5900 CallExpr *CEx = cast<CallExpr>(E);
5901 unsigned NumArgs = CEx->getNumArgs();
5902 if (NumArgs > 0) {
5903 Expr *LastA = CEx->getArg(NumArgs - 1);
5904 Expr *InnerE = LastA->IgnoreParenImpCasts();
5905 const Type *InnerType =
5906 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5907 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
5908 // Warn on this floating-point to bool conversion
5909 DiagnoseImpCast(S, E, T, CC,
5910 diag::warn_impcast_floating_point_to_bool);
5911 }
5912 }
5913 }
John McCall51313c32010-01-04 23:31:57 +00005914 return;
5915 }
5916
Richard Trieu1838ca52011-05-29 19:59:02 +00005917 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikieb26331b2012-06-19 21:19:06 +00005918 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiee81b43b2012-11-08 00:41:20 +00005919 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikie896c7dd2013-02-16 00:56:22 +00005920 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieb1360492012-03-16 20:30:12 +00005921 SourceLocation Loc = E->getSourceRange().getBegin();
5922 if (Loc.isMacroID())
5923 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie9fb1ac52012-05-15 21:57:38 +00005924 if (!Loc.isMacroID() || CC.isMacroID())
5925 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
5926 << T << clang::SourceRange(CC)
Richard Smith8adf8372013-09-20 00:27:40 +00005927 << FixItHint::CreateReplacement(Loc,
5928 S.getFixItZeroLiteralForType(T, Loc));
Richard Trieu1838ca52011-05-29 19:59:02 +00005929 }
5930
David Blaikieb26331b2012-06-19 21:19:06 +00005931 if (!Source->isIntegerType() || !Target->isIntegerType())
5932 return;
5933
David Blaikiebe0ee872012-05-15 16:56:36 +00005934 // TODO: remove this early return once the false positives for constant->bool
5935 // in templates, macros, etc, are reduced or removed.
5936 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
5937 return;
5938
John McCall323ed742010-05-06 08:58:33 +00005939 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00005940 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00005941
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005942 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer25ffbef2013-03-28 19:07:11 +00005943 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005944 // TODO: this should happen for bitfield stores, too.
5945 llvm::APSInt Value(32);
5946 if (E->isIntegerConstantExpr(Value, S.Context)) {
5947 if (S.SourceMgr.isInSystemMacro(CC))
5948 return;
5949
John McCall091f23f2010-11-09 22:22:12 +00005950 std::string PrettySourceValue = Value.toString(10);
5951 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005952
Ted Kremenek5e745da2011-10-22 02:37:33 +00005953 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5954 S.PDiag(diag::warn_impcast_integer_precision_constant)
5955 << PrettySourceValue << PrettyTargetValue
5956 << E->getType() << T << E->getSourceRange()
5957 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00005958 return;
5959 }
5960
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005961 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
5962 if (S.SourceMgr.isInSystemMacro(CC))
5963 return;
5964
David Blaikie37050842012-04-12 22:40:54 +00005965 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaksc36bedc2012-02-01 19:08:57 +00005966 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
5967 /* pruneControlFlow */ true);
John McCallb4eb64d2010-10-08 02:01:28 +00005968 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00005969 }
5970
5971 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
5972 (!TargetRange.NonNegative && SourceRange.NonNegative &&
5973 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00005974
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005975 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005976 return;
5977
John McCall323ed742010-05-06 08:58:33 +00005978 unsigned DiagID = diag::warn_impcast_integer_sign;
5979
5980 // Traditionally, gcc has warned about this under -Wsign-compare.
5981 // We also want to warn about it in -Wconversion.
5982 // So if -Wconversion is off, use a completely identical diagnostic
5983 // in the sign-compare group.
5984 // The conditional-checking code will
5985 if (ICContext) {
5986 DiagID = diag::warn_impcast_integer_sign_conditional;
5987 *ICContext = true;
5988 }
5989
John McCallb4eb64d2010-10-08 02:01:28 +00005990 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00005991 }
5992
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005993 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005994 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
5995 // type, to give us better diagnostics.
5996 QualType SourceType = E->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +00005997 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005998 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5999 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
6000 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
6001 SourceType = S.Context.getTypeDeclType(Enum);
6002 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
6003 }
6004 }
6005
Douglas Gregor284cc8d2011-02-22 02:45:07 +00006006 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
6007 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall83972f12013-03-09 00:54:27 +00006008 if (SourceEnum->getDecl()->hasNameForLinkage() &&
6009 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00006010 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00006011 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00006012 return;
6013
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00006014 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00006015 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00006016 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00006017
John McCall51313c32010-01-04 23:31:57 +00006018 return;
6019}
6020
David Blaikie9fb1ac52012-05-15 21:57:38 +00006021void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6022 SourceLocation CC, QualType T);
John McCall323ed742010-05-06 08:58:33 +00006023
6024void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00006025 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00006026 E = E->IgnoreParenImpCasts();
6027
6028 if (isa<ConditionalOperator>(E))
David Blaikie9fb1ac52012-05-15 21:57:38 +00006029 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCall323ed742010-05-06 08:58:33 +00006030
John McCallb4eb64d2010-10-08 02:01:28 +00006031 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00006032 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00006033 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00006034 return;
6035}
6036
David Blaikie9fb1ac52012-05-15 21:57:38 +00006037void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6038 SourceLocation CC, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00006039 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00006040
6041 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00006042 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
6043 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00006044
6045 // If -Wconversion would have warned about either of the candidates
6046 // for a signedness conversion to the context type...
6047 if (!Suspicious) return;
6048
6049 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00006050 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
6051 CC))
John McCall323ed742010-05-06 08:58:33 +00006052 return;
6053
John McCall323ed742010-05-06 08:58:33 +00006054 // ...then check whether it would have warned about either of the
6055 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00006056 if (E->getType() == T) return;
6057
6058 Suspicious = false;
6059 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
6060 E->getType(), CC, &Suspicious);
6061 if (!Suspicious)
6062 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00006063 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00006064}
6065
6066/// AnalyzeImplicitConversions - Find and report any interesting
6067/// implicit conversions in the given expression. There are a couple
6068/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00006069void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00006070 QualType T = OrigE->getType();
6071 Expr *E = OrigE->IgnoreParenImpCasts();
6072
Douglas Gregorf8b6e152011-10-10 17:38:18 +00006073 if (E->isTypeDependent() || E->isValueDependent())
6074 return;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006075
John McCall323ed742010-05-06 08:58:33 +00006076 // For conditional operators, we analyze the arguments as if they
6077 // were being fed directly into the output.
6078 if (isa<ConditionalOperator>(E)) {
6079 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie9fb1ac52012-05-15 21:57:38 +00006080 CheckConditionalOperator(S, CO, CC, T);
John McCall323ed742010-05-06 08:58:33 +00006081 return;
6082 }
6083
Hans Wennborg88617a22012-08-28 15:44:30 +00006084 // Check implicit argument conversions for function calls.
6085 if (CallExpr *Call = dyn_cast<CallExpr>(E))
6086 CheckImplicitArgumentConversions(S, Call, CC);
6087
John McCall323ed742010-05-06 08:58:33 +00006088 // Go ahead and check any implicit conversions we might have skipped.
6089 // The non-canonical typecheck is just an optimization;
6090 // CheckImplicitConversion will filter out dead implicit conversions.
6091 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00006092 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00006093
6094 // Now continue drilling into this expression.
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00006095
6096 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00006097 if (POE->getResultExpr())
6098 E = POE->getResultExpr();
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00006099 }
6100
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00006101 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6102 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6103
John McCall323ed742010-05-06 08:58:33 +00006104 // Skip past explicit casts.
6105 if (isa<ExplicitCastExpr>(E)) {
6106 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00006107 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00006108 }
6109
John McCallbeb22aa2010-11-09 23:24:47 +00006110 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6111 // Do a somewhat different check with comparison operators.
6112 if (BO->isComparisonOp())
6113 return AnalyzeComparison(S, BO);
6114
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00006115 // And with simple assignments.
6116 if (BO->getOpcode() == BO_Assign)
John McCallbeb22aa2010-11-09 23:24:47 +00006117 return AnalyzeAssignment(S, BO);
6118 }
John McCall323ed742010-05-06 08:58:33 +00006119
6120 // These break the otherwise-useful invariant below. Fortunately,
6121 // we don't really need to recurse into them, because any internal
6122 // expressions should have been analyzed already when they were
6123 // built into statements.
6124 if (isa<StmtExpr>(E)) return;
6125
6126 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006127 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00006128
6129 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00006130 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00006131 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Stephen Hines651f13c2014-04-23 16:59:28 -07006132 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00006133 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor54042f12012-02-09 10:18:50 +00006134 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor503384f2012-02-09 00:47:04 +00006135 if (!ChildExpr)
6136 continue;
6137
Stephen Hines651f13c2014-04-23 16:59:28 -07006138 if (IsLogicalAndOperator &&
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00006139 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Stephen Hines651f13c2014-04-23 16:59:28 -07006140 // Ignore checking string literals that are in logical and operators.
6141 // This is a common pattern for asserts.
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00006142 continue;
6143 AnalyzeImplicitConversions(S, ChildExpr, CC);
6144 }
John McCall323ed742010-05-06 08:58:33 +00006145}
6146
6147} // end anonymous namespace
6148
Stephen Hines651f13c2014-04-23 16:59:28 -07006149enum {
6150 AddressOf,
6151 FunctionPointer,
6152 ArrayPointer
6153};
6154
6155/// \brief Diagnose pointers that are always non-null.
6156/// \param E the expression containing the pointer
6157/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6158/// compared to a null pointer
6159/// \param IsEqual True when the comparison is equal to a null pointer
6160/// \param Range Extra SourceRange to highlight in the diagnostic
6161void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
6162 Expr::NullPointerConstantKind NullKind,
6163 bool IsEqual, SourceRange Range) {
6164
6165 // Don't warn inside macros.
6166 if (E->getExprLoc().isMacroID())
6167 return;
6168 E = E->IgnoreImpCasts();
6169
6170 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
6171
6172 bool IsAddressOf = false;
6173
6174 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6175 if (UO->getOpcode() != UO_AddrOf)
6176 return;
6177 IsAddressOf = true;
6178 E = UO->getSubExpr();
6179 }
6180
6181 // Expect to find a single Decl. Skip anything more complicated.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006182 ValueDecl *D = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07006183 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
6184 D = R->getDecl();
6185 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6186 D = M->getMemberDecl();
6187 }
6188
6189 // Weak Decls can be null.
6190 if (!D || D->isWeak())
6191 return;
6192
6193 QualType T = D->getType();
6194 const bool IsArray = T->isArrayType();
6195 const bool IsFunction = T->isFunctionType();
6196
6197 if (IsAddressOf) {
6198 // Address of function is used to silence the function warning.
6199 if (IsFunction)
6200 return;
6201 // Address of reference can be null.
6202 if (T->isReferenceType())
6203 return;
6204 }
6205
6206 // Found nothing.
6207 if (!IsAddressOf && !IsFunction && !IsArray)
6208 return;
6209
6210 // Pretty print the expression for the diagnostic.
6211 std::string Str;
6212 llvm::raw_string_ostream S(Str);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006213 E->printPretty(S, nullptr, getPrintingPolicy());
Stephen Hines651f13c2014-04-23 16:59:28 -07006214
6215 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
6216 : diag::warn_impcast_pointer_to_bool;
6217 unsigned DiagType;
6218 if (IsAddressOf)
6219 DiagType = AddressOf;
6220 else if (IsFunction)
6221 DiagType = FunctionPointer;
6222 else if (IsArray)
6223 DiagType = ArrayPointer;
6224 else
6225 llvm_unreachable("Could not determine diagnostic.");
6226 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
6227 << Range << IsEqual;
6228
6229 if (!IsFunction)
6230 return;
6231
6232 // Suggest '&' to silence the function warning.
6233 Diag(E->getExprLoc(), diag::note_function_warning_silence)
6234 << FixItHint::CreateInsertion(E->getLocStart(), "&");
6235
6236 // Check to see if '()' fixit should be emitted.
6237 QualType ReturnType;
6238 UnresolvedSet<4> NonTemplateOverloads;
6239 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
6240 if (ReturnType.isNull())
6241 return;
6242
6243 if (IsCompare) {
6244 // There are two cases here. If there is null constant, the only suggest
6245 // for a pointer return type. If the null is 0, then suggest if the return
6246 // type is a pointer or an integer type.
6247 if (!ReturnType->isPointerType()) {
6248 if (NullKind == Expr::NPCK_ZeroExpression ||
6249 NullKind == Expr::NPCK_ZeroLiteral) {
6250 if (!ReturnType->isIntegerType())
6251 return;
6252 } else {
6253 return;
6254 }
6255 }
6256 } else { // !IsCompare
6257 // For function to bool, only suggest if the function pointer has bool
6258 // return type.
6259 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
6260 return;
6261 }
6262 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006263 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Stephen Hines651f13c2014-04-23 16:59:28 -07006264}
6265
6266
John McCall323ed742010-05-06 08:58:33 +00006267/// Diagnoses "dangerous" implicit conversions within the given
6268/// expression (which is a full expression). Implements -Wconversion
6269/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00006270///
6271/// \param CC the "context" location of the implicit conversion, i.e.
6272/// the most location of the syntactic entity requiring the implicit
6273/// conversion
6274void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00006275 // Don't diagnose in unevaluated contexts.
David Blaikie71f55f72012-08-06 22:47:24 +00006276 if (isUnevaluatedContext())
John McCall323ed742010-05-06 08:58:33 +00006277 return;
6278
6279 // Don't diagnose for value- or type-dependent expressions.
6280 if (E->isTypeDependent() || E->isValueDependent())
6281 return;
6282
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006283 // Check for array bounds violations in cases where the check isn't triggered
6284 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
6285 // ArraySubscriptExpr is on the RHS of a variable initialization.
6286 CheckArrayAccess(E);
6287
John McCallb4eb64d2010-10-08 02:01:28 +00006288 // This is not the right CC for (e.g.) a variable initialization.
6289 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00006290}
6291
Fariborz Jahanianad48a502013-01-24 22:11:45 +00006292/// Diagnose when expression is an integer constant expression and its evaluation
6293/// results in integer overflow
6294void Sema::CheckForIntOverflow (Expr *E) {
Richard Smith00043292013-11-05 22:23:30 +00006295 if (isa<BinaryOperator>(E->IgnoreParens()))
6296 E->EvaluateForOverflow(Context);
Fariborz Jahanianad48a502013-01-24 22:11:45 +00006297}
6298
Richard Smith6c3af3d2013-01-17 01:17:56 +00006299namespace {
6300/// \brief Visitor for expressions which looks for unsequenced operations on the
6301/// same object.
6302class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smith0c0b3902013-06-30 10:40:20 +00006303 typedef EvaluatedExprVisitor<SequenceChecker> Base;
6304
Richard Smith6c3af3d2013-01-17 01:17:56 +00006305 /// \brief A tree of sequenced regions within an expression. Two regions are
6306 /// unsequenced if one is an ancestor or a descendent of the other. When we
6307 /// finish processing an expression with sequencing, such as a comma
6308 /// expression, we fold its tree nodes into its parent, since they are
6309 /// unsequenced with respect to nodes we will visit later.
6310 class SequenceTree {
6311 struct Value {
6312 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
6313 unsigned Parent : 31;
6314 bool Merged : 1;
6315 };
Robert Wilhelme7205c02013-08-10 12:33:24 +00006316 SmallVector<Value, 8> Values;
Richard Smith6c3af3d2013-01-17 01:17:56 +00006317
6318 public:
6319 /// \brief A region within an expression which may be sequenced with respect
6320 /// to some other region.
6321 class Seq {
6322 explicit Seq(unsigned N) : Index(N) {}
6323 unsigned Index;
6324 friend class SequenceTree;
6325 public:
6326 Seq() : Index(0) {}
6327 };
6328
6329 SequenceTree() { Values.push_back(Value(0)); }
6330 Seq root() const { return Seq(0); }
6331
6332 /// \brief Create a new sequence of operations, which is an unsequenced
6333 /// subset of \p Parent. This sequence of operations is sequenced with
6334 /// respect to other children of \p Parent.
6335 Seq allocate(Seq Parent) {
6336 Values.push_back(Value(Parent.Index));
6337 return Seq(Values.size() - 1);
6338 }
6339
6340 /// \brief Merge a sequence of operations into its parent.
6341 void merge(Seq S) {
6342 Values[S.Index].Merged = true;
6343 }
6344
6345 /// \brief Determine whether two operations are unsequenced. This operation
6346 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
6347 /// should have been merged into its parent as appropriate.
6348 bool isUnsequenced(Seq Cur, Seq Old) {
6349 unsigned C = representative(Cur.Index);
6350 unsigned Target = representative(Old.Index);
6351 while (C >= Target) {
6352 if (C == Target)
6353 return true;
6354 C = Values[C].Parent;
6355 }
6356 return false;
6357 }
6358
6359 private:
6360 /// \brief Pick a representative for a sequence.
6361 unsigned representative(unsigned K) {
6362 if (Values[K].Merged)
6363 // Perform path compression as we go.
6364 return Values[K].Parent = representative(Values[K].Parent);
6365 return K;
6366 }
6367 };
6368
6369 /// An object for which we can track unsequenced uses.
6370 typedef NamedDecl *Object;
6371
6372 /// Different flavors of object usage which we track. We only track the
6373 /// least-sequenced usage of each kind.
6374 enum UsageKind {
6375 /// A read of an object. Multiple unsequenced reads are OK.
6376 UK_Use,
6377 /// A modification of an object which is sequenced before the value
Richard Smith418dd3e2013-06-26 23:16:51 +00006378 /// computation of the expression, such as ++n in C++.
Richard Smith6c3af3d2013-01-17 01:17:56 +00006379 UK_ModAsValue,
6380 /// A modification of an object which is not sequenced before the value
6381 /// computation of the expression, such as n++.
6382 UK_ModAsSideEffect,
6383
6384 UK_Count = UK_ModAsSideEffect + 1
6385 };
6386
6387 struct Usage {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006388 Usage() : Use(nullptr), Seq() {}
Richard Smith6c3af3d2013-01-17 01:17:56 +00006389 Expr *Use;
6390 SequenceTree::Seq Seq;
6391 };
6392
6393 struct UsageInfo {
6394 UsageInfo() : Diagnosed(false) {}
6395 Usage Uses[UK_Count];
6396 /// Have we issued a diagnostic for this variable already?
6397 bool Diagnosed;
6398 };
6399 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
6400
6401 Sema &SemaRef;
6402 /// Sequenced regions within the expression.
6403 SequenceTree Tree;
6404 /// Declaration modifications and references which we have seen.
6405 UsageInfoMap UsageMap;
6406 /// The region we are currently within.
6407 SequenceTree::Seq Region;
6408 /// Filled in with declarations which were modified as a side-effect
6409 /// (that is, post-increment operations).
Robert Wilhelme7205c02013-08-10 12:33:24 +00006410 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smith1a2dcd52013-01-17 23:18:09 +00006411 /// Expressions to check later. We defer checking these to reduce
6412 /// stack usage.
Robert Wilhelme7205c02013-08-10 12:33:24 +00006413 SmallVectorImpl<Expr *> &WorkList;
Richard Smith6c3af3d2013-01-17 01:17:56 +00006414
6415 /// RAII object wrapping the visitation of a sequenced subexpression of an
6416 /// expression. At the end of this process, the side-effects of the evaluation
6417 /// become sequenced with respect to the value computation of the result, so
6418 /// we downgrade any UK_ModAsSideEffect within the evaluation to
6419 /// UK_ModAsValue.
6420 struct SequencedSubexpression {
6421 SequencedSubexpression(SequenceChecker &Self)
6422 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
6423 Self.ModAsSideEffect = &ModAsSideEffect;
6424 }
6425 ~SequencedSubexpression() {
6426 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
6427 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
6428 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
6429 Self.addUsage(U, ModAsSideEffect[I].first,
6430 ModAsSideEffect[I].second.Use, UK_ModAsValue);
6431 }
6432 Self.ModAsSideEffect = OldModAsSideEffect;
6433 }
6434
6435 SequenceChecker &Self;
Robert Wilhelme7205c02013-08-10 12:33:24 +00006436 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
6437 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smith6c3af3d2013-01-17 01:17:56 +00006438 };
6439
Richard Smith67470052013-06-20 22:21:56 +00006440 /// RAII object wrapping the visitation of a subexpression which we might
6441 /// choose to evaluate as a constant. If any subexpression is evaluated and
6442 /// found to be non-constant, this allows us to suppress the evaluation of
6443 /// the outer expression.
6444 class EvaluationTracker {
6445 public:
6446 EvaluationTracker(SequenceChecker &Self)
6447 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
6448 Self.EvalTracker = this;
6449 }
6450 ~EvaluationTracker() {
6451 Self.EvalTracker = Prev;
6452 if (Prev)
6453 Prev->EvalOK &= EvalOK;
6454 }
6455
6456 bool evaluate(const Expr *E, bool &Result) {
6457 if (!EvalOK || E->isValueDependent())
6458 return false;
6459 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
6460 return EvalOK;
6461 }
6462
6463 private:
6464 SequenceChecker &Self;
6465 EvaluationTracker *Prev;
6466 bool EvalOK;
6467 } *EvalTracker;
6468
Richard Smith6c3af3d2013-01-17 01:17:56 +00006469 /// \brief Find the object which is produced by the specified expression,
6470 /// if any.
6471 Object getObject(Expr *E, bool Mod) const {
6472 E = E->IgnoreParenCasts();
6473 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6474 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
6475 return getObject(UO->getSubExpr(), Mod);
6476 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6477 if (BO->getOpcode() == BO_Comma)
6478 return getObject(BO->getRHS(), Mod);
6479 if (Mod && BO->isAssignmentOp())
6480 return getObject(BO->getLHS(), Mod);
6481 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
6482 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
6483 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
6484 return ME->getMemberDecl();
6485 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6486 // FIXME: If this is a reference, map through to its value.
6487 return DRE->getDecl();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006488 return nullptr;
Richard Smith6c3af3d2013-01-17 01:17:56 +00006489 }
6490
6491 /// \brief Note that an object was modified or used by an expression.
6492 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
6493 Usage &U = UI.Uses[UK];
6494 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
6495 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
6496 ModAsSideEffect->push_back(std::make_pair(O, U));
6497 U.Use = Ref;
6498 U.Seq = Region;
6499 }
6500 }
6501 /// \brief Check whether a modification or use conflicts with a prior usage.
6502 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
6503 bool IsModMod) {
6504 if (UI.Diagnosed)
6505 return;
6506
6507 const Usage &U = UI.Uses[OtherKind];
6508 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
6509 return;
6510
6511 Expr *Mod = U.Use;
6512 Expr *ModOrUse = Ref;
6513 if (OtherKind == UK_Use)
6514 std::swap(Mod, ModOrUse);
6515
6516 SemaRef.Diag(Mod->getExprLoc(),
6517 IsModMod ? diag::warn_unsequenced_mod_mod
6518 : diag::warn_unsequenced_mod_use)
6519 << O << SourceRange(ModOrUse->getExprLoc());
6520 UI.Diagnosed = true;
6521 }
6522
6523 void notePreUse(Object O, Expr *Use) {
6524 UsageInfo &U = UsageMap[O];
6525 // Uses conflict with other modifications.
6526 checkUsage(O, U, Use, UK_ModAsValue, false);
6527 }
6528 void notePostUse(Object O, Expr *Use) {
6529 UsageInfo &U = UsageMap[O];
6530 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
6531 addUsage(U, O, Use, UK_Use);
6532 }
6533
6534 void notePreMod(Object O, Expr *Mod) {
6535 UsageInfo &U = UsageMap[O];
6536 // Modifications conflict with other modifications and with uses.
6537 checkUsage(O, U, Mod, UK_ModAsValue, true);
6538 checkUsage(O, U, Mod, UK_Use, false);
6539 }
6540 void notePostMod(Object O, Expr *Use, UsageKind UK) {
6541 UsageInfo &U = UsageMap[O];
6542 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
6543 addUsage(U, O, Use, UK);
6544 }
6545
6546public:
Robert Wilhelme7205c02013-08-10 12:33:24 +00006547 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006548 : Base(S.Context), SemaRef(S), Region(Tree.root()),
6549 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00006550 Visit(E);
6551 }
6552
6553 void VisitStmt(Stmt *S) {
6554 // Skip all statements which aren't expressions for now.
6555 }
6556
6557 void VisitExpr(Expr *E) {
6558 // By default, just recurse to evaluated subexpressions.
Richard Smith0c0b3902013-06-30 10:40:20 +00006559 Base::VisitStmt(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00006560 }
6561
6562 void VisitCastExpr(CastExpr *E) {
6563 Object O = Object();
6564 if (E->getCastKind() == CK_LValueToRValue)
6565 O = getObject(E->getSubExpr(), false);
6566
6567 if (O)
6568 notePreUse(O, E);
6569 VisitExpr(E);
6570 if (O)
6571 notePostUse(O, E);
6572 }
6573
6574 void VisitBinComma(BinaryOperator *BO) {
6575 // C++11 [expr.comma]p1:
6576 // Every value computation and side effect associated with the left
6577 // expression is sequenced before every value computation and side
6578 // effect associated with the right expression.
6579 SequenceTree::Seq LHS = Tree.allocate(Region);
6580 SequenceTree::Seq RHS = Tree.allocate(Region);
6581 SequenceTree::Seq OldRegion = Region;
6582
6583 {
6584 SequencedSubexpression SeqLHS(*this);
6585 Region = LHS;
6586 Visit(BO->getLHS());
6587 }
6588
6589 Region = RHS;
6590 Visit(BO->getRHS());
6591
6592 Region = OldRegion;
6593
6594 // Forget that LHS and RHS are sequenced. They are both unsequenced
6595 // with respect to other stuff.
6596 Tree.merge(LHS);
6597 Tree.merge(RHS);
6598 }
6599
6600 void VisitBinAssign(BinaryOperator *BO) {
6601 // The modification is sequenced after the value computation of the LHS
6602 // and RHS, so check it before inspecting the operands and update the
6603 // map afterwards.
6604 Object O = getObject(BO->getLHS(), true);
6605 if (!O)
6606 return VisitExpr(BO);
6607
6608 notePreMod(O, BO);
6609
6610 // C++11 [expr.ass]p7:
6611 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
6612 // only once.
6613 //
6614 // Therefore, for a compound assignment operator, O is considered used
6615 // everywhere except within the evaluation of E1 itself.
6616 if (isa<CompoundAssignOperator>(BO))
6617 notePreUse(O, BO);
6618
6619 Visit(BO->getLHS());
6620
6621 if (isa<CompoundAssignOperator>(BO))
6622 notePostUse(O, BO);
6623
6624 Visit(BO->getRHS());
6625
Richard Smith418dd3e2013-06-26 23:16:51 +00006626 // C++11 [expr.ass]p1:
6627 // the assignment is sequenced [...] before the value computation of the
6628 // assignment expression.
6629 // C11 6.5.16/3 has no such rule.
6630 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6631 : UK_ModAsSideEffect);
Richard Smith6c3af3d2013-01-17 01:17:56 +00006632 }
6633 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
6634 VisitBinAssign(CAO);
6635 }
6636
6637 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6638 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6639 void VisitUnaryPreIncDec(UnaryOperator *UO) {
6640 Object O = getObject(UO->getSubExpr(), true);
6641 if (!O)
6642 return VisitExpr(UO);
6643
6644 notePreMod(O, UO);
6645 Visit(UO->getSubExpr());
Richard Smith418dd3e2013-06-26 23:16:51 +00006646 // C++11 [expr.pre.incr]p1:
6647 // the expression ++x is equivalent to x+=1
6648 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6649 : UK_ModAsSideEffect);
Richard Smith6c3af3d2013-01-17 01:17:56 +00006650 }
6651
6652 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6653 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6654 void VisitUnaryPostIncDec(UnaryOperator *UO) {
6655 Object O = getObject(UO->getSubExpr(), true);
6656 if (!O)
6657 return VisitExpr(UO);
6658
6659 notePreMod(O, UO);
6660 Visit(UO->getSubExpr());
6661 notePostMod(O, UO, UK_ModAsSideEffect);
6662 }
6663
6664 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
6665 void VisitBinLOr(BinaryOperator *BO) {
6666 // The side-effects of the LHS of an '&&' are sequenced before the
6667 // value computation of the RHS, and hence before the value computation
6668 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
6669 // as if they were unconditionally sequenced.
Richard Smith67470052013-06-20 22:21:56 +00006670 EvaluationTracker Eval(*this);
Richard Smith6c3af3d2013-01-17 01:17:56 +00006671 {
6672 SequencedSubexpression Sequenced(*this);
6673 Visit(BO->getLHS());
6674 }
6675
6676 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00006677 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith995e4a72013-01-17 22:06:26 +00006678 if (!Result)
6679 Visit(BO->getRHS());
6680 } else {
6681 // Check for unsequenced operations in the RHS, treating it as an
6682 // entirely separate evaluation.
6683 //
6684 // FIXME: If there are operations in the RHS which are unsequenced
6685 // with respect to operations outside the RHS, and those operations
6686 // are unconditionally evaluated, diagnose them.
Richard Smith1a2dcd52013-01-17 23:18:09 +00006687 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00006688 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00006689 }
6690 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith67470052013-06-20 22:21:56 +00006691 EvaluationTracker Eval(*this);
Richard Smith6c3af3d2013-01-17 01:17:56 +00006692 {
6693 SequencedSubexpression Sequenced(*this);
6694 Visit(BO->getLHS());
6695 }
6696
6697 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00006698 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith995e4a72013-01-17 22:06:26 +00006699 if (Result)
6700 Visit(BO->getRHS());
6701 } else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00006702 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00006703 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00006704 }
6705
6706 // Only visit the condition, unless we can be sure which subexpression will
6707 // be chosen.
6708 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith67470052013-06-20 22:21:56 +00006709 EvaluationTracker Eval(*this);
Richard Smith418dd3e2013-06-26 23:16:51 +00006710 {
6711 SequencedSubexpression Sequenced(*this);
6712 Visit(CO->getCond());
6713 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00006714
6715 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00006716 if (Eval.evaluate(CO->getCond(), Result))
Richard Smith6c3af3d2013-01-17 01:17:56 +00006717 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00006718 else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00006719 WorkList.push_back(CO->getTrueExpr());
6720 WorkList.push_back(CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00006721 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00006722 }
6723
Richard Smith0c0b3902013-06-30 10:40:20 +00006724 void VisitCallExpr(CallExpr *CE) {
6725 // C++11 [intro.execution]p15:
6726 // When calling a function [...], every value computation and side effect
6727 // associated with any argument expression, or with the postfix expression
6728 // designating the called function, is sequenced before execution of every
6729 // expression or statement in the body of the function [and thus before
6730 // the value computation of its result].
6731 SequencedSubexpression Sequenced(*this);
6732 Base::VisitCallExpr(CE);
6733
6734 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
6735 }
6736
Richard Smith6c3af3d2013-01-17 01:17:56 +00006737 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smith0c0b3902013-06-30 10:40:20 +00006738 // This is a call, so all subexpressions are sequenced before the result.
6739 SequencedSubexpression Sequenced(*this);
6740
Richard Smith6c3af3d2013-01-17 01:17:56 +00006741 if (!CCE->isListInitialization())
6742 return VisitExpr(CCE);
6743
6744 // In C++11, list initializations are sequenced.
Robert Wilhelme7205c02013-08-10 12:33:24 +00006745 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smith6c3af3d2013-01-17 01:17:56 +00006746 SequenceTree::Seq Parent = Region;
6747 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
6748 E = CCE->arg_end();
6749 I != E; ++I) {
6750 Region = Tree.allocate(Parent);
6751 Elts.push_back(Region);
6752 Visit(*I);
6753 }
6754
6755 // Forget that the initializers are sequenced.
6756 Region = Parent;
6757 for (unsigned I = 0; I < Elts.size(); ++I)
6758 Tree.merge(Elts[I]);
6759 }
6760
6761 void VisitInitListExpr(InitListExpr *ILE) {
6762 if (!SemaRef.getLangOpts().CPlusPlus11)
6763 return VisitExpr(ILE);
6764
6765 // In C++11, list initializations are sequenced.
Robert Wilhelme7205c02013-08-10 12:33:24 +00006766 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smith6c3af3d2013-01-17 01:17:56 +00006767 SequenceTree::Seq Parent = Region;
6768 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
6769 Expr *E = ILE->getInit(I);
6770 if (!E) continue;
6771 Region = Tree.allocate(Parent);
6772 Elts.push_back(Region);
6773 Visit(E);
6774 }
6775
6776 // Forget that the initializers are sequenced.
6777 Region = Parent;
6778 for (unsigned I = 0; I < Elts.size(); ++I)
6779 Tree.merge(Elts[I]);
6780 }
6781};
6782}
6783
6784void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelme7205c02013-08-10 12:33:24 +00006785 SmallVector<Expr *, 8> WorkList;
Richard Smith1a2dcd52013-01-17 23:18:09 +00006786 WorkList.push_back(E);
6787 while (!WorkList.empty()) {
Robert Wilhelm344472e2013-08-23 16:11:15 +00006788 Expr *Item = WorkList.pop_back_val();
Richard Smith1a2dcd52013-01-17 23:18:09 +00006789 SequenceChecker(*this, Item, WorkList);
6790 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00006791}
6792
Fariborz Jahanianad48a502013-01-24 22:11:45 +00006793void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
6794 bool IsConstexpr) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00006795 CheckImplicitConversions(E, CheckLoc);
6796 CheckUnsequencedOperations(E);
Fariborz Jahanianad48a502013-01-24 22:11:45 +00006797 if (!IsConstexpr && !E->isValueDependent())
6798 CheckForIntOverflow(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00006799}
6800
John McCall15d7d122010-11-11 03:21:53 +00006801void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
6802 FieldDecl *BitField,
6803 Expr *Init) {
6804 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
6805}
6806
Mike Stumpf8c49212010-01-21 03:59:47 +00006807/// CheckParmsForFunctionDef - Check that the parameters of the given
6808/// function are appropriate for the definition of a function. This
6809/// takes care of any checks that cannot be performed on the
6810/// declaration itself, e.g., that the types of each of the function
6811/// parameters are complete.
Reid Kleckner8c0501c2013-06-24 14:38:26 +00006812bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
6813 ParmVarDecl *const *PEnd,
Douglas Gregor82aa7132010-11-01 18:37:59 +00006814 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00006815 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00006816 for (; P != PEnd; ++P) {
6817 ParmVarDecl *Param = *P;
6818
Mike Stumpf8c49212010-01-21 03:59:47 +00006819 // C99 6.7.5.3p4: the parameters in a parameter type list in a
6820 // function declarator that is part of a function definition of
6821 // that function shall not have incomplete type.
6822 //
6823 // This is also C++ [dcl.fct]p6.
6824 if (!Param->isInvalidDecl() &&
6825 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00006826 diag::err_typecheck_decl_incomplete_type)) {
Mike Stumpf8c49212010-01-21 03:59:47 +00006827 Param->setInvalidDecl();
6828 HasInvalidParm = true;
6829 }
6830
6831 // C99 6.9.1p5: If the declarator includes a parameter type list, the
6832 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00006833 if (CheckParameterNames &&
Stephen Hines6bcf27b2014-05-29 04:14:42 -07006834 Param->getIdentifier() == nullptr &&
Mike Stumpf8c49212010-01-21 03:59:47 +00006835 !Param->isImplicit() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006836 !getLangOpts().CPlusPlus)
Mike Stumpf8c49212010-01-21 03:59:47 +00006837 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00006838
6839 // C99 6.7.5.3p12:
6840 // If the function declarator is not part of a definition of that
6841 // function, parameters may have incomplete type and may use the [*]
6842 // notation in their sequences of declarator specifiers to specify
6843 // variable length array types.
6844 QualType PType = Param->getOriginalType();
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00006845 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigd17e3402010-02-01 05:02:49 +00006846 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitfc093362013-03-01 21:41:22 +00006847 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigd17e3402010-02-01 05:02:49 +00006848 // information is added for it.
6849 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00006850 break;
Sam Weinigd17e3402010-02-01 05:02:49 +00006851 }
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00006852 PType= AT->getElementType();
Sam Weinigd17e3402010-02-01 05:02:49 +00006853 }
Reid Kleckner9b601952013-06-21 12:45:15 +00006854
6855 // MSVC destroys objects passed by value in the callee. Therefore a
6856 // function definition which takes such a parameter must be able to call the
Stephen Hines651f13c2014-04-23 16:59:28 -07006857 // object's destructor. However, we don't perform any direct access check
6858 // on the dtor.
6859 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
6860 .getCXXABI()
6861 .areArgsDestroyedLeftToRightInCallee()) {
6862 if (!Param->isInvalidDecl()) {
6863 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
6864 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
6865 if (!ClassDecl->isInvalidDecl() &&
6866 !ClassDecl->hasIrrelevantDestructor() &&
6867 !ClassDecl->isDependentContext()) {
6868 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
6869 MarkFunctionReferenced(Param->getLocation(), Destructor);
6870 DiagnoseUseOfDecl(Destructor, Param->getLocation());
6871 }
6872 }
6873 }
Reid Kleckner9b601952013-06-21 12:45:15 +00006874 }
Mike Stumpf8c49212010-01-21 03:59:47 +00006875 }
6876
6877 return HasInvalidParm;
6878}
John McCallb7f4ffe2010-08-12 21:44:57 +00006879
6880/// CheckCastAlign - Implements -Wcast-align, which warns when a
6881/// pointer cast increases the alignment requirements.
6882void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
6883 // This is actually a lot of work to potentially be doing on every
6884 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00006885 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
6886 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00006887 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00006888 return;
6889
6890 // Ignore dependent types.
6891 if (T->isDependentType() || Op->getType()->isDependentType())
6892 return;
6893
6894 // Require that the destination be a pointer type.
6895 const PointerType *DestPtr = T->getAs<PointerType>();
6896 if (!DestPtr) return;
6897
6898 // If the destination has alignment 1, we're done.
6899 QualType DestPointee = DestPtr->getPointeeType();
6900 if (DestPointee->isIncompleteType()) return;
6901 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
6902 if (DestAlign.isOne()) return;
6903
6904 // Require that the source be a pointer type.
6905 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
6906 if (!SrcPtr) return;
6907 QualType SrcPointee = SrcPtr->getPointeeType();
6908
6909 // Whitelist casts from cv void*. We already implicitly
6910 // whitelisted casts to cv void*, since they have alignment 1.
6911 // Also whitelist casts involving incomplete types, which implicitly
6912 // includes 'void'.
6913 if (SrcPointee->isIncompleteType()) return;
6914
6915 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
6916 if (SrcAlign >= DestAlign) return;
6917
6918 Diag(TRange.getBegin(), diag::warn_cast_align)
6919 << Op->getType() << T
6920 << static_cast<unsigned>(SrcAlign.getQuantity())
6921 << static_cast<unsigned>(DestAlign.getQuantity())
6922 << TRange << Op->getSourceRange();
6923}
6924
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006925static const Type* getElementType(const Expr *BaseExpr) {
6926 const Type* EltType = BaseExpr->getType().getTypePtr();
6927 if (EltType->isAnyPointerType())
6928 return EltType->getPointeeType().getTypePtr();
6929 else if (EltType->isArrayType())
6930 return EltType->getBaseElementTypeUnsafe();
6931 return EltType;
6932}
6933
Chandler Carruthc2684342011-08-05 09:10:50 +00006934/// \brief Check whether this array fits the idiom of a size-one tail padded
6935/// array member of a struct.
6936///
6937/// We avoid emitting out-of-bounds access warnings for such arrays as they are
6938/// commonly used to emulate flexible arrays in C89 code.
6939static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
6940 const NamedDecl *ND) {
6941 if (Size != 1 || !ND) return false;
6942
6943 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
6944 if (!FD) return false;
6945
6946 // Don't consider sizes resulting from macro expansions or template argument
6947 // substitution to form C89 tail-padded arrays.
Sean Callanand2cf3482012-05-04 18:22:53 +00006948
6949 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00006950 while (TInfo) {
6951 TypeLoc TL = TInfo->getTypeLoc();
6952 // Look through typedefs.
David Blaikie39e6ab42013-02-18 22:06:02 +00006953 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
6954 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00006955 TInfo = TDL->getTypeSourceInfo();
6956 continue;
6957 }
David Blaikie39e6ab42013-02-18 22:06:02 +00006958 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
6959 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier5e253012013-02-06 00:58:34 +00006960 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
6961 return false;
6962 }
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00006963 break;
Sean Callanand2cf3482012-05-04 18:22:53 +00006964 }
Chandler Carruthc2684342011-08-05 09:10:50 +00006965
6966 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00006967 if (!RD) return false;
6968 if (RD->isUnion()) return false;
6969 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
6970 if (!CRD->isStandardLayout()) return false;
6971 }
Chandler Carruthc2684342011-08-05 09:10:50 +00006972
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00006973 // See if this is the last field decl in the record.
6974 const Decl *D = FD;
6975 while ((D = D->getNextDeclInContext()))
6976 if (isa<FieldDecl>(D))
6977 return false;
6978 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00006979}
6980
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006981void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006982 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00006983 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman92b670e2012-02-27 21:21:40 +00006984 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006985 if (IndexExpr->isValueDependent())
6986 return;
6987
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00006988 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006989 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00006990 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006991 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00006992 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00006993 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00006994
Chandler Carruth34064582011-02-17 20:55:08 +00006995 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006996 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00006997 return;
Richard Smith25b009a2011-12-16 19:31:14 +00006998 if (IndexNegated)
6999 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00007000
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007001 const NamedDecl *ND = nullptr;
Chandler Carruthba447122011-08-05 08:07:29 +00007002 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7003 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00007004 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00007005 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00007006
Ted Kremenek9e060ca2011-02-23 23:06:04 +00007007 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00007008 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00007009 if (!size.isStrictlyPositive())
7010 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007011
7012 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00007013 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007014 // Make sure we're comparing apples to apples when comparing index to size
7015 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
7016 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00007017 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00007018 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007019 if (ptrarith_typesize != array_typesize) {
7020 // There's a cast to a different size type involved
7021 uint64_t ratio = array_typesize / ptrarith_typesize;
7022 // TODO: Be smarter about handling cases where array_typesize is not a
7023 // multiple of ptrarith_typesize
7024 if (ptrarith_typesize * ratio == array_typesize)
7025 size *= llvm::APInt(size.getBitWidth(), ratio);
7026 }
7027 }
7028
Chandler Carruth34064582011-02-17 20:55:08 +00007029 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00007030 index = index.zext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00007031 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00007032 size = size.zext(index.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00007033
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007034 // For array subscripting the index must be less than size, but for pointer
7035 // arithmetic also allow the index (offset) to be equal to size since
7036 // computing the next address after the end of the array is legal and
7037 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman92b670e2012-02-27 21:21:40 +00007038 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruthba447122011-08-05 08:07:29 +00007039 return;
7040
7041 // Also don't warn for arrays of size 1 which are members of some
7042 // structure. These are often used to approximate flexible arrays in C89
7043 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007044 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00007045 return;
Chandler Carruth34064582011-02-17 20:55:08 +00007046
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00007047 // Suppress the warning if the subscript expression (as identified by the
7048 // ']' location) and the index expression are both from macro expansions
7049 // within a system header.
7050 if (ASE) {
7051 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
7052 ASE->getRBracketLoc());
7053 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
7054 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
7055 IndexExpr->getLocStart());
Eli Friedman24146972013-08-22 00:27:10 +00007056 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00007057 return;
7058 }
7059 }
7060
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007061 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00007062 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007063 DiagID = diag::warn_array_index_exceeds_bounds;
7064
7065 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7066 PDiag(DiagID) << index.toString(10, true)
7067 << size.toString(10, true)
7068 << (unsigned)size.getLimitedValue(~0U)
7069 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00007070 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007071 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00007072 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007073 DiagID = diag::warn_ptr_arith_precedes_bounds;
7074 if (index.isNegative()) index = -index;
7075 }
7076
7077 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7078 PDiag(DiagID) << index.toString(10, true)
7079 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00007080 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00007081
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00007082 if (!ND) {
7083 // Try harder to find a NamedDecl to point at in the note.
7084 while (const ArraySubscriptExpr *ASE =
7085 dyn_cast<ArraySubscriptExpr>(BaseExpr))
7086 BaseExpr = ASE->getBase()->IgnoreParenCasts();
7087 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7088 ND = dyn_cast<NamedDecl>(DRE->getDecl());
7089 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7090 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7091 }
7092
Chandler Carruth35001ca2011-02-17 21:10:52 +00007093 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007094 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
7095 PDiag(diag::note_array_index_out_of_bounds)
7096 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00007097}
7098
Ted Kremenek3aea4da2011-03-01 18:41:00 +00007099void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007100 int AllowOnePastEnd = 0;
7101 while (expr) {
7102 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00007103 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007104 case Stmt::ArraySubscriptExprClass: {
7105 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00007106 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007107 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00007108 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00007109 }
7110 case Stmt::UnaryOperatorClass: {
7111 // Only unwrap the * and & unary operators
7112 const UnaryOperator *UO = cast<UnaryOperator>(expr);
7113 expr = UO->getSubExpr();
7114 switch (UO->getOpcode()) {
7115 case UO_AddrOf:
7116 AllowOnePastEnd++;
7117 break;
7118 case UO_Deref:
7119 AllowOnePastEnd--;
7120 break;
7121 default:
7122 return;
7123 }
7124 break;
7125 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00007126 case Stmt::ConditionalOperatorClass: {
7127 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
7128 if (const Expr *lhs = cond->getLHS())
7129 CheckArrayAccess(lhs);
7130 if (const Expr *rhs = cond->getRHS())
7131 CheckArrayAccess(rhs);
7132 return;
7133 }
7134 default:
7135 return;
7136 }
Peter Collingbournef111d932011-04-15 00:35:48 +00007137 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00007138}
John McCallf85e1932011-06-15 23:02:42 +00007139
7140//===--- CHECK: Objective-C retain cycles ----------------------------------//
7141
7142namespace {
7143 struct RetainCycleOwner {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007144 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCallf85e1932011-06-15 23:02:42 +00007145 VarDecl *Variable;
7146 SourceRange Range;
7147 SourceLocation Loc;
7148 bool Indirect;
7149
7150 void setLocsFrom(Expr *e) {
7151 Loc = e->getExprLoc();
7152 Range = e->getSourceRange();
7153 }
7154 };
7155}
7156
7157/// Consider whether capturing the given variable can possibly lead to
7158/// a retain cycle.
7159static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00007160 // In ARC, it's captured strongly iff the variable has __strong
John McCallf85e1932011-06-15 23:02:42 +00007161 // lifetime. In MRR, it's captured strongly if the variable is
7162 // __block and has an appropriate type.
7163 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7164 return false;
7165
7166 owner.Variable = var;
Jordan Rosee10f4d32012-09-15 02:48:31 +00007167 if (ref)
7168 owner.setLocsFrom(ref);
John McCallf85e1932011-06-15 23:02:42 +00007169 return true;
7170}
7171
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00007172static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00007173 while (true) {
7174 e = e->IgnoreParens();
7175 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
7176 switch (cast->getCastKind()) {
7177 case CK_BitCast:
7178 case CK_LValueBitCast:
7179 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00007180 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00007181 e = cast->getSubExpr();
7182 continue;
7183
John McCallf85e1932011-06-15 23:02:42 +00007184 default:
7185 return false;
7186 }
7187 }
7188
7189 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
7190 ObjCIvarDecl *ivar = ref->getDecl();
7191 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7192 return false;
7193
7194 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00007195 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00007196 return false;
7197
7198 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
7199 owner.Indirect = true;
7200 return true;
7201 }
7202
7203 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
7204 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
7205 if (!var) return false;
7206 return considerVariable(var, ref, owner);
7207 }
7208
John McCallf85e1932011-06-15 23:02:42 +00007209 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
7210 if (member->isArrow()) return false;
7211
7212 // Don't count this as an indirect ownership.
7213 e = member->getBase();
7214 continue;
7215 }
7216
John McCall4b9c2d22011-11-06 09:01:30 +00007217 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
7218 // Only pay attention to pseudo-objects on property references.
7219 ObjCPropertyRefExpr *pre
7220 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
7221 ->IgnoreParens());
7222 if (!pre) return false;
7223 if (pre->isImplicitProperty()) return false;
7224 ObjCPropertyDecl *property = pre->getExplicitProperty();
7225 if (!property->isRetaining() &&
7226 !(property->getPropertyIvarDecl() &&
7227 property->getPropertyIvarDecl()->getType()
7228 .getObjCLifetime() == Qualifiers::OCL_Strong))
7229 return false;
7230
7231 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00007232 if (pre->isSuperReceiver()) {
7233 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
7234 if (!owner.Variable)
7235 return false;
7236 owner.Loc = pre->getLocation();
7237 owner.Range = pre->getSourceRange();
7238 return true;
7239 }
John McCall4b9c2d22011-11-06 09:01:30 +00007240 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
7241 ->getSourceExpr());
7242 continue;
7243 }
7244
John McCallf85e1932011-06-15 23:02:42 +00007245 // Array ivars?
7246
7247 return false;
7248 }
7249}
7250
7251namespace {
7252 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
7253 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
7254 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007255 Variable(variable), Capturer(nullptr) {}
John McCallf85e1932011-06-15 23:02:42 +00007256
7257 VarDecl *Variable;
7258 Expr *Capturer;
7259
7260 void VisitDeclRefExpr(DeclRefExpr *ref) {
7261 if (ref->getDecl() == Variable && !Capturer)
7262 Capturer = ref;
7263 }
7264
John McCallf85e1932011-06-15 23:02:42 +00007265 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
7266 if (Capturer) return;
7267 Visit(ref->getBase());
7268 if (Capturer && ref->isFreeIvar())
7269 Capturer = ref;
7270 }
7271
7272 void VisitBlockExpr(BlockExpr *block) {
7273 // Look inside nested blocks
7274 if (block->getBlockDecl()->capturesVariable(Variable))
7275 Visit(block->getBlockDecl()->getBody());
7276 }
Fariborz Jahanian7e2e4c32012-08-31 20:04:47 +00007277
7278 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
7279 if (Capturer) return;
7280 if (OVE->getSourceExpr())
7281 Visit(OVE->getSourceExpr());
7282 }
John McCallf85e1932011-06-15 23:02:42 +00007283 };
7284}
7285
7286/// Check whether the given argument is a block which captures a
7287/// variable.
7288static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
7289 assert(owner.Variable && owner.Loc.isValid());
7290
7291 e = e->IgnoreParenCasts();
Jordan Rose1fac58a2012-09-17 17:54:30 +00007292
7293 // Look through [^{...} copy] and Block_copy(^{...}).
7294 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
7295 Selector Cmd = ME->getSelector();
7296 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
7297 e = ME->getInstanceReceiver();
7298 if (!e)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007299 return nullptr;
Jordan Rose1fac58a2012-09-17 17:54:30 +00007300 e = e->IgnoreParenCasts();
7301 }
7302 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
7303 if (CE->getNumArgs() == 1) {
7304 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekd13eff62012-10-02 04:36:54 +00007305 if (Fn) {
7306 const IdentifierInfo *FnI = Fn->getIdentifier();
7307 if (FnI && FnI->isStr("_Block_copy")) {
7308 e = CE->getArg(0)->IgnoreParenCasts();
7309 }
7310 }
Jordan Rose1fac58a2012-09-17 17:54:30 +00007311 }
7312 }
7313
John McCallf85e1932011-06-15 23:02:42 +00007314 BlockExpr *block = dyn_cast<BlockExpr>(e);
7315 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007316 return nullptr;
John McCallf85e1932011-06-15 23:02:42 +00007317
7318 FindCaptureVisitor visitor(S.Context, owner.Variable);
7319 visitor.Visit(block->getBlockDecl()->getBody());
7320 return visitor.Capturer;
7321}
7322
7323static void diagnoseRetainCycle(Sema &S, Expr *capturer,
7324 RetainCycleOwner &owner) {
7325 assert(capturer);
7326 assert(owner.Variable && owner.Loc.isValid());
7327
7328 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
7329 << owner.Variable << capturer->getSourceRange();
7330 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
7331 << owner.Indirect << owner.Range;
7332}
7333
7334/// Check for a keyword selector that starts with the word 'add' or
7335/// 'set'.
7336static bool isSetterLikeSelector(Selector sel) {
7337 if (sel.isUnarySelector()) return false;
7338
Chris Lattner5f9e2722011-07-23 10:55:15 +00007339 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00007340 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00007341 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00007342 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00007343 else if (str.startswith("add")) {
7344 // Specially whitelist 'addOperationWithBlock:'.
7345 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
7346 return false;
7347 str = str.substr(3);
7348 }
John McCallf85e1932011-06-15 23:02:42 +00007349 else
7350 return false;
7351
7352 if (str.empty()) return true;
Jordan Rose3f6f51e2013-02-08 22:30:41 +00007353 return !isLowercase(str.front());
John McCallf85e1932011-06-15 23:02:42 +00007354}
7355
7356/// Check a message send to see if it's likely to cause a retain cycle.
7357void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
7358 // Only check instance methods whose selector looks like a setter.
7359 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
7360 return;
7361
7362 // Try to find a variable that the receiver is strongly owned by.
7363 RetainCycleOwner owner;
7364 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00007365 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00007366 return;
7367 } else {
7368 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
7369 owner.Variable = getCurMethodDecl()->getSelfDecl();
7370 owner.Loc = msg->getSuperLoc();
7371 owner.Range = msg->getSuperLoc();
7372 }
7373
7374 // Check whether the receiver is captured by any of the arguments.
7375 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
7376 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
7377 return diagnoseRetainCycle(*this, capturer, owner);
7378}
7379
7380/// Check a property assign to see if it's likely to cause a retain cycle.
7381void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
7382 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00007383 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00007384 return;
7385
7386 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
7387 diagnoseRetainCycle(*this, capturer, owner);
7388}
7389
Jordan Rosee10f4d32012-09-15 02:48:31 +00007390void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
7391 RetainCycleOwner Owner;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007392 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosee10f4d32012-09-15 02:48:31 +00007393 return;
7394
7395 // Because we don't have an expression for the variable, we have to set the
7396 // location explicitly here.
7397 Owner.Loc = Var->getLocation();
7398 Owner.Range = Var->getSourceRange();
7399
7400 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
7401 diagnoseRetainCycle(*this, Capturer, Owner);
7402}
7403
Ted Kremenek9d084012012-12-21 08:04:28 +00007404static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
7405 Expr *RHS, bool isProperty) {
7406 // Check if RHS is an Objective-C object literal, which also can get
7407 // immediately zapped in a weak reference. Note that we explicitly
7408 // allow ObjCStringLiterals, since those are designed to never really die.
7409 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenekf530ff72012-12-21 21:59:39 +00007410
Ted Kremenekd3292c82012-12-21 22:46:35 +00007411 // This enum needs to match with the 'select' in
7412 // warn_objc_arc_literal_assign (off-by-1).
7413 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
7414 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
7415 return false;
Ted Kremenekf530ff72012-12-21 21:59:39 +00007416
7417 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenekd3292c82012-12-21 22:46:35 +00007418 << (unsigned) Kind
Ted Kremenek9d084012012-12-21 08:04:28 +00007419 << (isProperty ? 0 : 1)
7420 << RHS->getSourceRange();
Ted Kremenekf530ff72012-12-21 21:59:39 +00007421
7422 return true;
Ted Kremenek9d084012012-12-21 08:04:28 +00007423}
7424
Ted Kremenekb29b30f2012-12-21 19:45:30 +00007425static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
7426 Qualifiers::ObjCLifetime LT,
7427 Expr *RHS, bool isProperty) {
7428 // Strip off any implicit cast added to get to the one ARC-specific.
7429 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
7430 if (cast->getCastKind() == CK_ARCConsumeObject) {
7431 S.Diag(Loc, diag::warn_arc_retained_assign)
7432 << (LT == Qualifiers::OCL_ExplicitNone)
7433 << (isProperty ? 0 : 1)
7434 << RHS->getSourceRange();
7435 return true;
7436 }
7437 RHS = cast->getSubExpr();
7438 }
7439
7440 if (LT == Qualifiers::OCL_Weak &&
7441 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
7442 return true;
7443
7444 return false;
7445}
7446
Ted Kremenekb1ea5102012-12-21 08:04:20 +00007447bool Sema::checkUnsafeAssigns(SourceLocation Loc,
7448 QualType LHS, Expr *RHS) {
7449 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
7450
7451 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
7452 return false;
7453
7454 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
7455 return true;
7456
7457 return false;
7458}
7459
Fariborz Jahanian921c1432011-06-24 18:25:34 +00007460void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
7461 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00007462 QualType LHSType;
7463 // PropertyRef on LHS type need be directly obtained from
Stephen Hines651f13c2014-04-23 16:59:28 -07007464 // its declaration as it has a PseudoType.
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00007465 ObjCPropertyRefExpr *PRE
7466 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
7467 if (PRE && !PRE->isImplicitProperty()) {
7468 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7469 if (PD)
7470 LHSType = PD->getType();
7471 }
7472
7473 if (LHSType.isNull())
7474 LHSType = LHS->getType();
Jordan Rose7a270482012-09-28 22:21:35 +00007475
7476 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
7477
7478 if (LT == Qualifiers::OCL_Weak) {
7479 DiagnosticsEngine::Level Level =
7480 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
7481 if (Level != DiagnosticsEngine::Ignored)
7482 getCurFunction()->markSafeWeakUse(LHS);
7483 }
7484
Fariborz Jahanian921c1432011-06-24 18:25:34 +00007485 if (checkUnsafeAssigns(Loc, LHSType, RHS))
7486 return;
Jordan Rose7a270482012-09-28 22:21:35 +00007487
Fariborz Jahanian921c1432011-06-24 18:25:34 +00007488 // FIXME. Check for other life times.
7489 if (LT != Qualifiers::OCL_None)
7490 return;
7491
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00007492 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00007493 if (PRE->isImplicitProperty())
7494 return;
7495 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7496 if (!PD)
7497 return;
7498
Bill Wendlingad017fa2012-12-20 19:22:21 +00007499 unsigned Attributes = PD->getPropertyAttributes();
7500 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00007501 // when 'assign' attribute was not explicitly specified
7502 // by user, ignore it and rely on property type itself
7503 // for lifetime info.
7504 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
7505 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
7506 LHSType->isObjCRetainableType())
7507 return;
7508
Fariborz Jahanian921c1432011-06-24 18:25:34 +00007509 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00007510 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00007511 Diag(Loc, diag::warn_arc_retained_property_assign)
7512 << RHS->getSourceRange();
7513 return;
7514 }
7515 RHS = cast->getSubExpr();
7516 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00007517 }
Bill Wendlingad017fa2012-12-20 19:22:21 +00007518 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb1ea5102012-12-21 08:04:20 +00007519 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
7520 return;
Fariborz Jahanianbd2e27e2012-07-06 21:09:27 +00007521 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00007522 }
7523}
Dmitri Gribenko625bb562012-02-14 22:14:32 +00007524
7525//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
7526
7527namespace {
7528bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
7529 SourceLocation StmtLoc,
7530 const NullStmt *Body) {
7531 // Do not warn if the body is a macro that expands to nothing, e.g:
7532 //
7533 // #define CALL(x)
7534 // if (condition)
7535 // CALL(0);
7536 //
7537 if (Body->hasLeadingEmptyMacro())
7538 return false;
7539
7540 // Get line numbers of statement and body.
7541 bool StmtLineInvalid;
7542 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
7543 &StmtLineInvalid);
7544 if (StmtLineInvalid)
7545 return false;
7546
7547 bool BodyLineInvalid;
7548 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
7549 &BodyLineInvalid);
7550 if (BodyLineInvalid)
7551 return false;
7552
7553 // Warn if null statement and body are on the same line.
7554 if (StmtLine != BodyLine)
7555 return false;
7556
7557 return true;
7558}
7559} // Unnamed namespace
7560
7561void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
7562 const Stmt *Body,
7563 unsigned DiagID) {
7564 // Since this is a syntactic check, don't emit diagnostic for template
7565 // instantiations, this just adds noise.
7566 if (CurrentInstantiationScope)
7567 return;
7568
7569 // The body should be a null statement.
7570 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7571 if (!NBody)
7572 return;
7573
7574 // Do the usual checks.
7575 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7576 return;
7577
7578 Diag(NBody->getSemiLoc(), DiagID);
7579 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7580}
7581
7582void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
7583 const Stmt *PossibleBody) {
7584 assert(!CurrentInstantiationScope); // Ensured by caller
7585
7586 SourceLocation StmtLoc;
7587 const Stmt *Body;
7588 unsigned DiagID;
7589 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
7590 StmtLoc = FS->getRParenLoc();
7591 Body = FS->getBody();
7592 DiagID = diag::warn_empty_for_body;
7593 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
7594 StmtLoc = WS->getCond()->getSourceRange().getEnd();
7595 Body = WS->getBody();
7596 DiagID = diag::warn_empty_while_body;
7597 } else
7598 return; // Neither `for' nor `while'.
7599
7600 // The body should be a null statement.
7601 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7602 if (!NBody)
7603 return;
7604
7605 // Skip expensive checks if diagnostic is disabled.
7606 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
7607 DiagnosticsEngine::Ignored)
7608 return;
7609
7610 // Do the usual checks.
7611 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7612 return;
7613
7614 // `for(...);' and `while(...);' are popular idioms, so in order to keep
7615 // noise level low, emit diagnostics only if for/while is followed by a
7616 // CompoundStmt, e.g.:
7617 // for (int i = 0; i < n; i++);
7618 // {
7619 // a(i);
7620 // }
7621 // or if for/while is followed by a statement with more indentation
7622 // than for/while itself:
7623 // for (int i = 0; i < n; i++);
7624 // a(i);
7625 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
7626 if (!ProbableTypo) {
7627 bool BodyColInvalid;
7628 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
7629 PossibleBody->getLocStart(),
7630 &BodyColInvalid);
7631 if (BodyColInvalid)
7632 return;
7633
7634 bool StmtColInvalid;
7635 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
7636 S->getLocStart(),
7637 &StmtColInvalid);
7638 if (StmtColInvalid)
7639 return;
7640
7641 if (BodyCol > StmtCol)
7642 ProbableTypo = true;
7643 }
7644
7645 if (ProbableTypo) {
7646 Diag(NBody->getSemiLoc(), DiagID);
7647 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7648 }
7649}
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00007650
7651//===--- Layout compatibility ----------------------------------------------//
7652
7653namespace {
7654
7655bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
7656
7657/// \brief Check if two enumeration types are layout-compatible.
7658bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
7659 // C++11 [dcl.enum] p8:
7660 // Two enumeration types are layout-compatible if they have the same
7661 // underlying type.
7662 return ED1->isComplete() && ED2->isComplete() &&
7663 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
7664}
7665
7666/// \brief Check if two fields are layout-compatible.
7667bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
7668 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
7669 return false;
7670
7671 if (Field1->isBitField() != Field2->isBitField())
7672 return false;
7673
7674 if (Field1->isBitField()) {
7675 // Make sure that the bit-fields are the same length.
7676 unsigned Bits1 = Field1->getBitWidthValue(C);
7677 unsigned Bits2 = Field2->getBitWidthValue(C);
7678
7679 if (Bits1 != Bits2)
7680 return false;
7681 }
7682
7683 return true;
7684}
7685
7686/// \brief Check if two standard-layout structs are layout-compatible.
7687/// (C++11 [class.mem] p17)
7688bool isLayoutCompatibleStruct(ASTContext &C,
7689 RecordDecl *RD1,
7690 RecordDecl *RD2) {
7691 // If both records are C++ classes, check that base classes match.
7692 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
7693 // If one of records is a CXXRecordDecl we are in C++ mode,
7694 // thus the other one is a CXXRecordDecl, too.
7695 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
7696 // Check number of base classes.
7697 if (D1CXX->getNumBases() != D2CXX->getNumBases())
7698 return false;
7699
7700 // Check the base classes.
7701 for (CXXRecordDecl::base_class_const_iterator
7702 Base1 = D1CXX->bases_begin(),
7703 BaseEnd1 = D1CXX->bases_end(),
7704 Base2 = D2CXX->bases_begin();
7705 Base1 != BaseEnd1;
7706 ++Base1, ++Base2) {
7707 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
7708 return false;
7709 }
7710 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
7711 // If only RD2 is a C++ class, it should have zero base classes.
7712 if (D2CXX->getNumBases() > 0)
7713 return false;
7714 }
7715
7716 // Check the fields.
7717 RecordDecl::field_iterator Field2 = RD2->field_begin(),
7718 Field2End = RD2->field_end(),
7719 Field1 = RD1->field_begin(),
7720 Field1End = RD1->field_end();
7721 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
7722 if (!isLayoutCompatible(C, *Field1, *Field2))
7723 return false;
7724 }
7725 if (Field1 != Field1End || Field2 != Field2End)
7726 return false;
7727
7728 return true;
7729}
7730
7731/// \brief Check if two standard-layout unions are layout-compatible.
7732/// (C++11 [class.mem] p18)
7733bool isLayoutCompatibleUnion(ASTContext &C,
7734 RecordDecl *RD1,
7735 RecordDecl *RD2) {
7736 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Stephen Hines651f13c2014-04-23 16:59:28 -07007737 for (auto *Field2 : RD2->fields())
7738 UnmatchedFields.insert(Field2);
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00007739
Stephen Hines651f13c2014-04-23 16:59:28 -07007740 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00007741 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
7742 I = UnmatchedFields.begin(),
7743 E = UnmatchedFields.end();
7744
7745 for ( ; I != E; ++I) {
Stephen Hines651f13c2014-04-23 16:59:28 -07007746 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00007747 bool Result = UnmatchedFields.erase(*I);
7748 (void) Result;
7749 assert(Result);
7750 break;
7751 }
7752 }
7753 if (I == E)
7754 return false;
7755 }
7756
7757 return UnmatchedFields.empty();
7758}
7759
7760bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
7761 if (RD1->isUnion() != RD2->isUnion())
7762 return false;
7763
7764 if (RD1->isUnion())
7765 return isLayoutCompatibleUnion(C, RD1, RD2);
7766 else
7767 return isLayoutCompatibleStruct(C, RD1, RD2);
7768}
7769
7770/// \brief Check if two types are layout-compatible in C++11 sense.
7771bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
7772 if (T1.isNull() || T2.isNull())
7773 return false;
7774
7775 // C++11 [basic.types] p11:
7776 // If two types T1 and T2 are the same type, then T1 and T2 are
7777 // layout-compatible types.
7778 if (C.hasSameType(T1, T2))
7779 return true;
7780
7781 T1 = T1.getCanonicalType().getUnqualifiedType();
7782 T2 = T2.getCanonicalType().getUnqualifiedType();
7783
7784 const Type::TypeClass TC1 = T1->getTypeClass();
7785 const Type::TypeClass TC2 = T2->getTypeClass();
7786
7787 if (TC1 != TC2)
7788 return false;
7789
7790 if (TC1 == Type::Enum) {
7791 return isLayoutCompatible(C,
7792 cast<EnumType>(T1)->getDecl(),
7793 cast<EnumType>(T2)->getDecl());
7794 } else if (TC1 == Type::Record) {
7795 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
7796 return false;
7797
7798 return isLayoutCompatible(C,
7799 cast<RecordType>(T1)->getDecl(),
7800 cast<RecordType>(T2)->getDecl());
7801 }
7802
7803 return false;
7804}
7805}
7806
7807//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
7808
7809namespace {
7810/// \brief Given a type tag expression find the type tag itself.
7811///
7812/// \param TypeExpr Type tag expression, as it appears in user's code.
7813///
7814/// \param VD Declaration of an identifier that appears in a type tag.
7815///
7816/// \param MagicValue Type tag magic value.
7817bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
7818 const ValueDecl **VD, uint64_t *MagicValue) {
7819 while(true) {
7820 if (!TypeExpr)
7821 return false;
7822
7823 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
7824
7825 switch (TypeExpr->getStmtClass()) {
7826 case Stmt::UnaryOperatorClass: {
7827 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
7828 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
7829 TypeExpr = UO->getSubExpr();
7830 continue;
7831 }
7832 return false;
7833 }
7834
7835 case Stmt::DeclRefExprClass: {
7836 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
7837 *VD = DRE->getDecl();
7838 return true;
7839 }
7840
7841 case Stmt::IntegerLiteralClass: {
7842 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
7843 llvm::APInt MagicValueAPInt = IL->getValue();
7844 if (MagicValueAPInt.getActiveBits() <= 64) {
7845 *MagicValue = MagicValueAPInt.getZExtValue();
7846 return true;
7847 } else
7848 return false;
7849 }
7850
7851 case Stmt::BinaryConditionalOperatorClass:
7852 case Stmt::ConditionalOperatorClass: {
7853 const AbstractConditionalOperator *ACO =
7854 cast<AbstractConditionalOperator>(TypeExpr);
7855 bool Result;
7856 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
7857 if (Result)
7858 TypeExpr = ACO->getTrueExpr();
7859 else
7860 TypeExpr = ACO->getFalseExpr();
7861 continue;
7862 }
7863 return false;
7864 }
7865
7866 case Stmt::BinaryOperatorClass: {
7867 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
7868 if (BO->getOpcode() == BO_Comma) {
7869 TypeExpr = BO->getRHS();
7870 continue;
7871 }
7872 return false;
7873 }
7874
7875 default:
7876 return false;
7877 }
7878 }
7879}
7880
7881/// \brief Retrieve the C type corresponding to type tag TypeExpr.
7882///
7883/// \param TypeExpr Expression that specifies a type tag.
7884///
7885/// \param MagicValues Registered magic values.
7886///
7887/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
7888/// kind.
7889///
7890/// \param TypeInfo Information about the corresponding C type.
7891///
7892/// \returns true if the corresponding C type was found.
7893bool GetMatchingCType(
7894 const IdentifierInfo *ArgumentKind,
7895 const Expr *TypeExpr, const ASTContext &Ctx,
7896 const llvm::DenseMap<Sema::TypeTagMagicValue,
7897 Sema::TypeTagData> *MagicValues,
7898 bool &FoundWrongKind,
7899 Sema::TypeTagData &TypeInfo) {
7900 FoundWrongKind = false;
7901
7902 // Variable declaration that has type_tag_for_datatype attribute.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07007903 const ValueDecl *VD = nullptr;
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00007904
7905 uint64_t MagicValue;
7906
7907 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
7908 return false;
7909
7910 if (VD) {
Stephen Hines651f13c2014-04-23 16:59:28 -07007911 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00007912 if (I->getArgumentKind() != ArgumentKind) {
7913 FoundWrongKind = true;
7914 return false;
7915 }
7916 TypeInfo.Type = I->getMatchingCType();
7917 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
7918 TypeInfo.MustBeNull = I->getMustBeNull();
7919 return true;
7920 }
7921 return false;
7922 }
7923
7924 if (!MagicValues)
7925 return false;
7926
7927 llvm::DenseMap<Sema::TypeTagMagicValue,
7928 Sema::TypeTagData>::const_iterator I =
7929 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
7930 if (I == MagicValues->end())
7931 return false;
7932
7933 TypeInfo = I->second;
7934 return true;
7935}
7936} // unnamed namespace
7937
7938void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
7939 uint64_t MagicValue, QualType Type,
7940 bool LayoutCompatible,
7941 bool MustBeNull) {
7942 if (!TypeTagForDatatypeMagicValues)
7943 TypeTagForDatatypeMagicValues.reset(
7944 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
7945
7946 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
7947 (*TypeTagForDatatypeMagicValues)[Magic] =
7948 TypeTagData(Type, LayoutCompatible, MustBeNull);
7949}
7950
7951namespace {
7952bool IsSameCharType(QualType T1, QualType T2) {
7953 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
7954 if (!BT1)
7955 return false;
7956
7957 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
7958 if (!BT2)
7959 return false;
7960
7961 BuiltinType::Kind T1Kind = BT1->getKind();
7962 BuiltinType::Kind T2Kind = BT2->getKind();
7963
7964 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
7965 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
7966 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
7967 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
7968}
7969} // unnamed namespace
7970
7971void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
7972 const Expr * const *ExprArgs) {
7973 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
7974 bool IsPointerAttr = Attr->getIsPointer();
7975
7976 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
7977 bool FoundWrongKind;
7978 TypeTagData TypeInfo;
7979 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
7980 TypeTagForDatatypeMagicValues.get(),
7981 FoundWrongKind, TypeInfo)) {
7982 if (FoundWrongKind)
7983 Diag(TypeTagExpr->getExprLoc(),
7984 diag::warn_type_tag_for_datatype_wrong_kind)
7985 << TypeTagExpr->getSourceRange();
7986 return;
7987 }
7988
7989 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
7990 if (IsPointerAttr) {
7991 // Skip implicit cast of pointer to `void *' (as a function argument).
7992 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5a249802012-11-03 16:07:49 +00007993 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkob57ce4e2012-11-03 22:10:18 +00007994 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00007995 ArgumentExpr = ICE->getSubExpr();
7996 }
7997 QualType ArgumentType = ArgumentExpr->getType();
7998
7999 // Passing a `void*' pointer shouldn't trigger a warning.
8000 if (IsPointerAttr && ArgumentType->isVoidPointerType())
8001 return;
8002
8003 if (TypeInfo.MustBeNull) {
8004 // Type tag with matching void type requires a null pointer.
8005 if (!ArgumentExpr->isNullPointerConstant(Context,
8006 Expr::NPC_ValueDependentIsNotNull)) {
8007 Diag(ArgumentExpr->getExprLoc(),
8008 diag::warn_type_safety_null_pointer_required)
8009 << ArgumentKind->getName()
8010 << ArgumentExpr->getSourceRange()
8011 << TypeTagExpr->getSourceRange();
8012 }
8013 return;
8014 }
8015
8016 QualType RequiredType = TypeInfo.Type;
8017 if (IsPointerAttr)
8018 RequiredType = Context.getPointerType(RequiredType);
8019
8020 bool mismatch = false;
8021 if (!TypeInfo.LayoutCompatible) {
8022 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
8023
8024 // C++11 [basic.fundamental] p1:
8025 // Plain char, signed char, and unsigned char are three distinct types.
8026 //
8027 // But we treat plain `char' as equivalent to `signed char' or `unsigned
8028 // char' depending on the current char signedness mode.
8029 if (mismatch)
8030 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
8031 RequiredType->getPointeeType())) ||
8032 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
8033 mismatch = false;
8034 } else
8035 if (IsPointerAttr)
8036 mismatch = !isLayoutCompatible(Context,
8037 ArgumentType->getPointeeType(),
8038 RequiredType->getPointeeType());
8039 else
8040 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
8041
8042 if (mismatch)
8043 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Stephen Hines651f13c2014-04-23 16:59:28 -07008044 << ArgumentType << ArgumentKind
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00008045 << TypeInfo.LayoutCompatible << RequiredType
8046 << ArgumentExpr->getSourceRange()
8047 << TypeTagExpr->getSourceRange();
8048}
Stephen Hines651f13c2014-04-23 16:59:28 -07008049