blob: d059001f9bbd0c77b5c914a456b2c316a735c8b7 [file] [log] [blame]
Chris Lattner59907c42007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner59907c42007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump1eb44332009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattner59907c42007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
John McCall2d887082010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Chris Lattner59907c42007-08-10 20:18:51 +000016#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000017#include "clang/AST/CharUnits.h"
John McCall384aff82010-08-25 07:42:41 +000018#include "clang/AST/DeclCXX.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikiebe0ee872012-05-15 16:56:36 +000021#include "clang/AST/Expr.h"
Ted Kremenek23245122007-08-20 16:18:38 +000022#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000023#include "clang/AST/ExprObjC.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000024#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtObjC.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000026#include "clang/Analysis/Analyses/FormatString.h"
Jordan Rose3f6f51e2013-02-08 22:30:41 +000027#include "clang/Basic/CharInfo.h"
Eric Christopher691ebc32010-04-17 02:26:23 +000028#include "clang/Basic/TargetBuiltins.h"
Nate Begeman26a31422010-06-08 02:47:44 +000029#include "clang/Basic/TargetInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000030#include "clang/Lex/Preprocessor.h"
31#include "clang/Sema/Initialization.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000032#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/Sema.h"
Richard Smith0e218972013-08-05 18:49:43 +000035#include "llvm/ADT/SmallBitVector.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000036#include "llvm/ADT/SmallString.h"
Richard Smith0e218972013-08-05 18:49:43 +000037#include "llvm/ADT/STLExtras.h"
Dmitri Gribenkocb5620c2013-01-30 12:06:08 +000038#include "llvm/Support/ConvertUTF.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000039#include "llvm/Support/raw_ostream.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000040#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000041using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000042using namespace sema;
Chris Lattner59907c42007-08-10 20:18:51 +000043
Chris Lattner60800082009-02-18 17:49:48 +000044SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
45 unsigned ByteNo) const {
Chris Lattner08f92e32010-11-17 07:37:15 +000046 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
David Blaikie4e4d0842012-03-11 07:00:24 +000047 PP.getLangOpts(), PP.getTargetInfo());
Chris Lattner60800082009-02-18 17:49:48 +000048}
49
John McCall8e10f3b2011-02-26 05:39:39 +000050/// Checks that a call expression's argument count is the desired number.
51/// This is useful when doing custom type-checking. Returns true on error.
52static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
53 unsigned argCount = call->getNumArgs();
54 if (argCount == desiredArgCount) return false;
55
56 if (argCount < desiredArgCount)
57 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
58 << 0 /*function call*/ << desiredArgCount << argCount
59 << call->getSourceRange();
60
61 // Highlight all the excess arguments.
62 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
63 call->getArg(argCount - 1)->getLocEnd());
64
65 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
66 << 0 /*function call*/ << desiredArgCount << argCount
67 << call->getArg(1)->getSourceRange();
68}
69
Julien Lerougee5939212012-04-28 17:39:16 +000070/// Check that the first argument to __builtin_annotation is an integer
71/// and the second argument is a non-wide string literal.
72static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
73 if (checkArgCount(S, TheCall, 2))
74 return true;
75
76 // First argument should be an integer.
77 Expr *ValArg = TheCall->getArg(0);
78 QualType Ty = ValArg->getType();
79 if (!Ty->isIntegerType()) {
80 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
81 << ValArg->getSourceRange();
Julien Lerouge77f68bb2011-09-09 22:41:49 +000082 return true;
83 }
Julien Lerougee5939212012-04-28 17:39:16 +000084
85 // Second argument should be a constant string.
86 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
87 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
88 if (!Literal || !Literal->isAscii()) {
89 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
90 << StrArg->getSourceRange();
91 return true;
92 }
93
94 TheCall->setType(Ty);
Julien Lerouge77f68bb2011-09-09 22:41:49 +000095 return false;
96}
97
Richard Smith5154dce2013-07-11 02:27:57 +000098/// Check that the argument to __builtin_addressof is a glvalue, and set the
99/// result type to the corresponding pointer type.
100static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
101 if (checkArgCount(S, TheCall, 1))
102 return true;
103
104 ExprResult Arg(S.Owned(TheCall->getArg(0)));
105 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
106 if (ResultType.isNull())
107 return true;
108
109 TheCall->setArg(0, Arg.take());
110 TheCall->setType(ResultType);
111 return false;
112}
113
John McCall60d7b3a2010-08-24 06:29:42 +0000114ExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +0000115Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCall60d7b3a2010-08-24 06:29:42 +0000116 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +0000117
Chris Lattner946928f2010-10-01 23:23:24 +0000118 // Find out if any arguments are required to be integer constant expressions.
119 unsigned ICEArguments = 0;
120 ASTContext::GetBuiltinTypeError Error;
121 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
122 if (Error != ASTContext::GE_None)
123 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
124
125 // If any arguments are required to be ICE's, check and diagnose.
126 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
127 // Skip arguments not required to be ICE's.
128 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
129
130 llvm::APSInt Result;
131 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
132 return true;
133 ICEArguments &= ~(1 << ArgNo);
134 }
135
Anders Carlssond406bf02009-08-16 01:56:34 +0000136 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000137 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000138 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000139 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000140 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000141 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000142 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000143 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000144 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000145 if (SemaBuiltinVAStart(TheCall))
146 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000147 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000148 case Builtin::BI__builtin_isgreater:
149 case Builtin::BI__builtin_isgreaterequal:
150 case Builtin::BI__builtin_isless:
151 case Builtin::BI__builtin_islessequal:
152 case Builtin::BI__builtin_islessgreater:
153 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000154 if (SemaBuiltinUnorderedCompare(TheCall))
155 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000156 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000157 case Builtin::BI__builtin_fpclassify:
158 if (SemaBuiltinFPClassification(TheCall, 6))
159 return ExprError();
160 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000161 case Builtin::BI__builtin_isfinite:
162 case Builtin::BI__builtin_isinf:
163 case Builtin::BI__builtin_isinf_sign:
164 case Builtin::BI__builtin_isnan:
165 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000166 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000167 return ExprError();
168 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000169 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000170 return SemaBuiltinShuffleVector(TheCall);
171 // TheCall will be freed by the smart pointer here, but that's fine, since
172 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000173 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000174 if (SemaBuiltinPrefetch(TheCall))
175 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000176 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000177 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000178 if (SemaBuiltinObjectSize(TheCall))
179 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000180 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000181 case Builtin::BI__builtin_longjmp:
182 if (SemaBuiltinLongjmp(TheCall))
183 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000184 break;
John McCall8e10f3b2011-02-26 05:39:39 +0000185
186 case Builtin::BI__builtin_classify_type:
187 if (checkArgCount(*this, TheCall, 1)) return true;
188 TheCall->setType(Context.IntTy);
189 break;
Chris Lattner75c29a02010-10-12 17:47:42 +0000190 case Builtin::BI__builtin_constant_p:
John McCall8e10f3b2011-02-26 05:39:39 +0000191 if (checkArgCount(*this, TheCall, 1)) return true;
192 TheCall->setType(Context.IntTy);
Chris Lattner75c29a02010-10-12 17:47:42 +0000193 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000194 case Builtin::BI__sync_fetch_and_add:
Douglas Gregora9766412011-11-28 16:30:08 +0000195 case Builtin::BI__sync_fetch_and_add_1:
196 case Builtin::BI__sync_fetch_and_add_2:
197 case Builtin::BI__sync_fetch_and_add_4:
198 case Builtin::BI__sync_fetch_and_add_8:
199 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000200 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregora9766412011-11-28 16:30:08 +0000201 case Builtin::BI__sync_fetch_and_sub_1:
202 case Builtin::BI__sync_fetch_and_sub_2:
203 case Builtin::BI__sync_fetch_and_sub_4:
204 case Builtin::BI__sync_fetch_and_sub_8:
205 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000206 case Builtin::BI__sync_fetch_and_or:
Douglas Gregora9766412011-11-28 16:30:08 +0000207 case Builtin::BI__sync_fetch_and_or_1:
208 case Builtin::BI__sync_fetch_and_or_2:
209 case Builtin::BI__sync_fetch_and_or_4:
210 case Builtin::BI__sync_fetch_and_or_8:
211 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000212 case Builtin::BI__sync_fetch_and_and:
Douglas Gregora9766412011-11-28 16:30:08 +0000213 case Builtin::BI__sync_fetch_and_and_1:
214 case Builtin::BI__sync_fetch_and_and_2:
215 case Builtin::BI__sync_fetch_and_and_4:
216 case Builtin::BI__sync_fetch_and_and_8:
217 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000218 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregora9766412011-11-28 16:30:08 +0000219 case Builtin::BI__sync_fetch_and_xor_1:
220 case Builtin::BI__sync_fetch_and_xor_2:
221 case Builtin::BI__sync_fetch_and_xor_4:
222 case Builtin::BI__sync_fetch_and_xor_8:
223 case Builtin::BI__sync_fetch_and_xor_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000224 case Builtin::BI__sync_add_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000225 case Builtin::BI__sync_add_and_fetch_1:
226 case Builtin::BI__sync_add_and_fetch_2:
227 case Builtin::BI__sync_add_and_fetch_4:
228 case Builtin::BI__sync_add_and_fetch_8:
229 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000230 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000231 case Builtin::BI__sync_sub_and_fetch_1:
232 case Builtin::BI__sync_sub_and_fetch_2:
233 case Builtin::BI__sync_sub_and_fetch_4:
234 case Builtin::BI__sync_sub_and_fetch_8:
235 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000236 case Builtin::BI__sync_and_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000237 case Builtin::BI__sync_and_and_fetch_1:
238 case Builtin::BI__sync_and_and_fetch_2:
239 case Builtin::BI__sync_and_and_fetch_4:
240 case Builtin::BI__sync_and_and_fetch_8:
241 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000242 case Builtin::BI__sync_or_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000243 case Builtin::BI__sync_or_and_fetch_1:
244 case Builtin::BI__sync_or_and_fetch_2:
245 case Builtin::BI__sync_or_and_fetch_4:
246 case Builtin::BI__sync_or_and_fetch_8:
247 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000248 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregora9766412011-11-28 16:30:08 +0000249 case Builtin::BI__sync_xor_and_fetch_1:
250 case Builtin::BI__sync_xor_and_fetch_2:
251 case Builtin::BI__sync_xor_and_fetch_4:
252 case Builtin::BI__sync_xor_and_fetch_8:
253 case Builtin::BI__sync_xor_and_fetch_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000254 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000255 case Builtin::BI__sync_val_compare_and_swap_1:
256 case Builtin::BI__sync_val_compare_and_swap_2:
257 case Builtin::BI__sync_val_compare_and_swap_4:
258 case Builtin::BI__sync_val_compare_and_swap_8:
259 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000260 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000261 case Builtin::BI__sync_bool_compare_and_swap_1:
262 case Builtin::BI__sync_bool_compare_and_swap_2:
263 case Builtin::BI__sync_bool_compare_and_swap_4:
264 case Builtin::BI__sync_bool_compare_and_swap_8:
265 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000266 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregora9766412011-11-28 16:30:08 +0000267 case Builtin::BI__sync_lock_test_and_set_1:
268 case Builtin::BI__sync_lock_test_and_set_2:
269 case Builtin::BI__sync_lock_test_and_set_4:
270 case Builtin::BI__sync_lock_test_and_set_8:
271 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattner5caa3702009-05-08 06:58:22 +0000272 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +0000273 case Builtin::BI__sync_lock_release_1:
274 case Builtin::BI__sync_lock_release_2:
275 case Builtin::BI__sync_lock_release_4:
276 case Builtin::BI__sync_lock_release_8:
277 case Builtin::BI__sync_lock_release_16:
Chris Lattner23aa9c82011-04-09 03:57:26 +0000278 case Builtin::BI__sync_swap:
Douglas Gregora9766412011-11-28 16:30:08 +0000279 case Builtin::BI__sync_swap_1:
280 case Builtin::BI__sync_swap_2:
281 case Builtin::BI__sync_swap_4:
282 case Builtin::BI__sync_swap_8:
283 case Builtin::BI__sync_swap_16:
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000284 return SemaBuiltinAtomicOverloaded(TheCallResult);
Richard Smithff34d402012-04-12 05:08:17 +0000285#define BUILTIN(ID, TYPE, ATTRS)
286#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
287 case Builtin::BI##ID: \
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000288 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithff34d402012-04-12 05:08:17 +0000289#include "clang/Basic/Builtins.def"
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000290 case Builtin::BI__builtin_annotation:
Julien Lerougee5939212012-04-28 17:39:16 +0000291 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000292 return ExprError();
293 break;
Richard Smith5154dce2013-07-11 02:27:57 +0000294 case Builtin::BI__builtin_addressof:
295 if (SemaBuiltinAddressof(*this, TheCall))
296 return ExprError();
297 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000298 }
299
300 // Since the target specific builtins for each arch overlap, only check those
301 // of the arch we are compiling for.
302 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000303 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman26a31422010-06-08 02:47:44 +0000304 case llvm::Triple::arm:
305 case llvm::Triple::thumb:
306 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
307 return ExprError();
308 break;
Tim Northoverb793f0d2013-08-01 09:23:19 +0000309 case llvm::Triple::aarch64:
310 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
311 return ExprError();
312 break;
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000313 case llvm::Triple::mips:
314 case llvm::Triple::mipsel:
315 case llvm::Triple::mips64:
316 case llvm::Triple::mips64el:
317 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
318 return ExprError();
319 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000320 default:
321 break;
322 }
323 }
324
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000325 return TheCallResult;
Nate Begeman26a31422010-06-08 02:47:44 +0000326}
327
Nate Begeman61eecf52010-06-14 05:21:25 +0000328// Get the valid immediate range for the specified NEON type code.
329static unsigned RFT(unsigned t, bool shift = false) {
Bob Wilsonda95f732011-11-08 01:16:11 +0000330 NeonTypeFlags Type(t);
331 int IsQuad = Type.isQuad();
332 switch (Type.getEltType()) {
333 case NeonTypeFlags::Int8:
334 case NeonTypeFlags::Poly8:
335 return shift ? 7 : (8 << IsQuad) - 1;
336 case NeonTypeFlags::Int16:
337 case NeonTypeFlags::Poly16:
338 return shift ? 15 : (4 << IsQuad) - 1;
339 case NeonTypeFlags::Int32:
340 return shift ? 31 : (2 << IsQuad) - 1;
341 case NeonTypeFlags::Int64:
342 return shift ? 63 : (1 << IsQuad) - 1;
343 case NeonTypeFlags::Float16:
344 assert(!shift && "cannot shift float types!");
345 return (4 << IsQuad) - 1;
346 case NeonTypeFlags::Float32:
347 assert(!shift && "cannot shift float types!");
348 return (2 << IsQuad) - 1;
Tim Northoverb793f0d2013-08-01 09:23:19 +0000349 case NeonTypeFlags::Float64:
350 assert(!shift && "cannot shift float types!");
351 return (1 << IsQuad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000352 }
David Blaikie7530c032012-01-17 06:56:22 +0000353 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman61eecf52010-06-14 05:21:25 +0000354}
355
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000356/// getNeonEltType - Return the QualType corresponding to the elements of
357/// the vector type specified by the NeonTypeFlags. This is used to check
358/// the pointer arguments for Neon load/store intrinsics.
359static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
360 switch (Flags.getEltType()) {
361 case NeonTypeFlags::Int8:
362 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
363 case NeonTypeFlags::Int16:
364 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
365 case NeonTypeFlags::Int32:
366 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
367 case NeonTypeFlags::Int64:
368 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
369 case NeonTypeFlags::Poly8:
370 return Context.SignedCharTy;
371 case NeonTypeFlags::Poly16:
372 return Context.ShortTy;
373 case NeonTypeFlags::Float16:
374 return Context.UnsignedShortTy;
375 case NeonTypeFlags::Float32:
376 return Context.FloatTy;
Tim Northoverb793f0d2013-08-01 09:23:19 +0000377 case NeonTypeFlags::Float64:
378 return Context.DoubleTy;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000379 }
David Blaikie7530c032012-01-17 06:56:22 +0000380 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000381}
382
Tim Northoverb793f0d2013-08-01 09:23:19 +0000383bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
384 CallExpr *TheCall) {
385
386 llvm::APSInt Result;
387
388 uint64_t mask = 0;
389 unsigned TV = 0;
390 int PtrArgNum = -1;
391 bool HasConstPtr = false;
392 switch (BuiltinID) {
393#define GET_NEON_AARCH64_OVERLOAD_CHECK
394#include "clang/Basic/arm_neon.inc"
395#undef GET_NEON_AARCH64_OVERLOAD_CHECK
396 }
397
398 // For NEON intrinsics which are overloaded on vector element type, validate
399 // the immediate which specifies which variant to emit.
400 unsigned ImmArg = TheCall->getNumArgs() - 1;
401 if (mask) {
402 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
403 return true;
404
405 TV = Result.getLimitedValue(64);
406 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
407 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
408 << TheCall->getArg(ImmArg)->getSourceRange();
409 }
410
411 if (PtrArgNum >= 0) {
412 // Check that pointer arguments have the specified type.
413 Expr *Arg = TheCall->getArg(PtrArgNum);
414 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
415 Arg = ICE->getSubExpr();
416 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
417 QualType RHSTy = RHS.get()->getType();
418 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
419 if (HasConstPtr)
420 EltTy = EltTy.withConst();
421 QualType LHSTy = Context.getPointerType(EltTy);
422 AssignConvertType ConvTy;
423 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
424 if (RHS.isInvalid())
425 return true;
426 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
427 RHS.get(), AA_Assigning))
428 return true;
429 }
430
431 // For NEON intrinsics which take an immediate value as part of the
432 // instruction, range check them here.
433 unsigned i = 0, l = 0, u = 0;
434 switch (BuiltinID) {
435 default:
436 return false;
437#define GET_NEON_AARCH64_IMMEDIATE_CHECK
438#include "clang/Basic/arm_neon.inc"
439#undef GET_NEON_AARCH64_IMMEDIATE_CHECK
440 }
441 ;
442
443 // We can't check the value of a dependent argument.
444 if (TheCall->getArg(i)->isTypeDependent() ||
445 TheCall->getArg(i)->isValueDependent())
446 return false;
447
448 // Check that the immediate argument is actually a constant.
449 if (SemaBuiltinConstantArg(TheCall, i, Result))
450 return true;
451
452 // Range check against the upper/lower values for this isntruction.
453 unsigned Val = Result.getZExtValue();
454 if (Val < l || Val > (u + l))
455 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
456 << l << u + l << TheCall->getArg(i)->getSourceRange();
457
458 return false;
459}
460
Tim Northover09df2b02013-07-16 09:47:53 +0000461bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall) {
462 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
463 BuiltinID == ARM::BI__builtin_arm_strex) &&
464 "unexpected ARM builtin");
465 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex;
466
467 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
468
469 // Ensure that we have the proper number of arguments.
470 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
471 return true;
472
473 // Inspect the pointer argument of the atomic builtin. This should always be
474 // a pointer type, whose element is an integral scalar or pointer type.
475 // Because it is a pointer type, we don't have to worry about any implicit
476 // casts here.
477 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
478 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
479 if (PointerArgRes.isInvalid())
480 return true;
481 PointerArg = PointerArgRes.take();
482
483 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
484 if (!pointerType) {
485 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
486 << PointerArg->getType() << PointerArg->getSourceRange();
487 return true;
488 }
489
490 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
491 // task is to insert the appropriate casts into the AST. First work out just
492 // what the appropriate type is.
493 QualType ValType = pointerType->getPointeeType();
494 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
495 if (IsLdrex)
496 AddrType.addConst();
497
498 // Issue a warning if the cast is dodgy.
499 CastKind CastNeeded = CK_NoOp;
500 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
501 CastNeeded = CK_BitCast;
502 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
503 << PointerArg->getType()
504 << Context.getPointerType(AddrType)
505 << AA_Passing << PointerArg->getSourceRange();
506 }
507
508 // Finally, do the cast and replace the argument with the corrected version.
509 AddrType = Context.getPointerType(AddrType);
510 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
511 if (PointerArgRes.isInvalid())
512 return true;
513 PointerArg = PointerArgRes.take();
514
515 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
516
517 // In general, we allow ints, floats and pointers to be loaded and stored.
518 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
519 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
520 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
521 << PointerArg->getType() << PointerArg->getSourceRange();
522 return true;
523 }
524
525 // But ARM doesn't have instructions to deal with 128-bit versions.
526 if (Context.getTypeSize(ValType) > 64) {
527 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
528 << PointerArg->getType() << PointerArg->getSourceRange();
529 return true;
530 }
531
532 switch (ValType.getObjCLifetime()) {
533 case Qualifiers::OCL_None:
534 case Qualifiers::OCL_ExplicitNone:
535 // okay
536 break;
537
538 case Qualifiers::OCL_Weak:
539 case Qualifiers::OCL_Strong:
540 case Qualifiers::OCL_Autoreleasing:
541 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
542 << ValType << PointerArg->getSourceRange();
543 return true;
544 }
545
546
547 if (IsLdrex) {
548 TheCall->setType(ValType);
549 return false;
550 }
551
552 // Initialize the argument to be stored.
553 ExprResult ValArg = TheCall->getArg(0);
554 InitializedEntity Entity = InitializedEntity::InitializeParameter(
555 Context, ValType, /*consume*/ false);
556 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
557 if (ValArg.isInvalid())
558 return true;
Tim Northover09df2b02013-07-16 09:47:53 +0000559 TheCall->setArg(0, ValArg.get());
Tim Northovera6306fc2013-10-29 12:32:58 +0000560
561 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
562 // but the custom checker bypasses all default analysis.
563 TheCall->setType(Context.IntTy);
Tim Northover09df2b02013-07-16 09:47:53 +0000564 return false;
565}
566
Nate Begeman26a31422010-06-08 02:47:44 +0000567bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000568 llvm::APSInt Result;
569
Tim Northover09df2b02013-07-16 09:47:53 +0000570 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
571 BuiltinID == ARM::BI__builtin_arm_strex) {
572 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall);
573 }
574
Richard Smithf8ee6bc2012-08-14 01:28:02 +0000575 uint64_t mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000576 unsigned TV = 0;
Bob Wilson46482552011-11-16 21:32:23 +0000577 int PtrArgNum = -1;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000578 bool HasConstPtr = false;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000579 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000580#define GET_NEON_OVERLOAD_CHECK
581#include "clang/Basic/arm_neon.inc"
582#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000583 }
584
Nate Begeman0d15c532010-06-13 04:47:52 +0000585 // For NEON intrinsics which are overloaded on vector element type, validate
586 // the immediate which specifies which variant to emit.
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000587 unsigned ImmArg = TheCall->getNumArgs()-1;
Nate Begeman0d15c532010-06-13 04:47:52 +0000588 if (mask) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000589 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
Nate Begeman0d15c532010-06-13 04:47:52 +0000590 return true;
591
Bob Wilsonda95f732011-11-08 01:16:11 +0000592 TV = Result.getLimitedValue(64);
Richard Smithf8ee6bc2012-08-14 01:28:02 +0000593 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000594 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000595 << TheCall->getArg(ImmArg)->getSourceRange();
596 }
597
Bob Wilson46482552011-11-16 21:32:23 +0000598 if (PtrArgNum >= 0) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000599 // Check that pointer arguments have the specified type.
Bob Wilson46482552011-11-16 21:32:23 +0000600 Expr *Arg = TheCall->getArg(PtrArgNum);
601 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
602 Arg = ICE->getSubExpr();
603 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
604 QualType RHSTy = RHS.get()->getType();
605 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
606 if (HasConstPtr)
607 EltTy = EltTy.withConst();
608 QualType LHSTy = Context.getPointerType(EltTy);
609 AssignConvertType ConvTy;
610 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
611 if (RHS.isInvalid())
612 return true;
613 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
614 RHS.get(), AA_Assigning))
615 return true;
Nate Begeman0d15c532010-06-13 04:47:52 +0000616 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000617
Nate Begeman0d15c532010-06-13 04:47:52 +0000618 // For NEON intrinsics which take an immediate value as part of the
619 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000620 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000621 switch (BuiltinID) {
622 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000623 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
624 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000625 case ARM::BI__builtin_arm_vcvtr_f:
626 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao186b26d2013-11-12 21:42:50 +0000627 case ARM::BI__builtin_arm_dmb:
628 case ARM::BI__builtin_arm_dsb: l = 0; u = 15; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000629#define GET_NEON_IMMEDIATE_CHECK
630#include "clang/Basic/arm_neon.inc"
631#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000632 };
633
Douglas Gregor592a4232012-06-29 01:05:22 +0000634 // We can't check the value of a dependent argument.
635 if (TheCall->getArg(i)->isTypeDependent() ||
636 TheCall->getArg(i)->isValueDependent())
637 return false;
638
Nate Begeman61eecf52010-06-14 05:21:25 +0000639 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000640 if (SemaBuiltinConstantArg(TheCall, i, Result))
641 return true;
642
Nate Begeman61eecf52010-06-14 05:21:25 +0000643 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000644 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000645 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000646 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000647 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000648
Nate Begeman99c40bb2010-08-03 21:32:34 +0000649 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000650 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000651}
Daniel Dunbarde454282008-10-02 18:44:07 +0000652
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000653bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
654 unsigned i = 0, l = 0, u = 0;
655 switch (BuiltinID) {
656 default: return false;
657 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
658 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyanbe22cb82012-08-27 12:29:20 +0000659 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
660 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
661 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
662 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
663 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000664 };
665
666 // We can't check the value of a dependent argument.
667 if (TheCall->getArg(i)->isTypeDependent() ||
668 TheCall->getArg(i)->isValueDependent())
669 return false;
670
671 // Check that the immediate argument is actually a constant.
672 llvm::APSInt Result;
673 if (SemaBuiltinConstantArg(TheCall, i, Result))
674 return true;
675
676 // Range check against the upper/lower values for this instruction.
677 unsigned Val = Result.getZExtValue();
678 if (Val < l || Val > u)
679 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
680 << l << u << TheCall->getArg(i)->getSourceRange();
681
682 return false;
683}
684
Richard Smith831421f2012-06-25 20:30:08 +0000685/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
686/// parameter with the FormatAttr's correct format_idx and firstDataArg.
687/// Returns true when the format fits the function and the FormatStringInfo has
688/// been populated.
689bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
690 FormatStringInfo *FSI) {
691 FSI->HasVAListArg = Format->getFirstArg() == 0;
692 FSI->FormatIdx = Format->getFormatIdx() - 1;
693 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssond406bf02009-08-16 01:56:34 +0000694
Richard Smith831421f2012-06-25 20:30:08 +0000695 // The way the format attribute works in GCC, the implicit this argument
696 // of member functions is counted. However, it doesn't appear in our own
697 // lists, so decrement format_idx in that case.
698 if (IsCXXMember) {
699 if(FSI->FormatIdx == 0)
700 return false;
701 --FSI->FormatIdx;
702 if (FSI->FirstDataArg != 0)
703 --FSI->FirstDataArg;
704 }
705 return true;
706}
Mike Stump1eb44332009-09-09 15:08:12 +0000707
Richard Smith831421f2012-06-25 20:30:08 +0000708/// Handles the checks for format strings, non-POD arguments to vararg
709/// functions, and NULL arguments passed to non-NULL parameters.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000710void Sema::checkCall(NamedDecl *FDecl,
711 ArrayRef<const Expr *> Args,
Richard Smith831421f2012-06-25 20:30:08 +0000712 unsigned NumProtoArgs,
713 bool IsMemberFunction,
714 SourceLocation Loc,
715 SourceRange Range,
716 VariadicCallType CallType) {
Richard Smith0e218972013-08-05 18:49:43 +0000717 // FIXME: We should check as much as we can in the template definition.
Jordan Rose66360e22012-10-02 01:49:54 +0000718 if (CurContext->isDependentContext())
719 return;
Daniel Dunbarde454282008-10-02 18:44:07 +0000720
Ted Kremenekc82faca2010-09-09 04:33:05 +0000721 // Printf and scanf checking.
Richard Smith0e218972013-08-05 18:49:43 +0000722 llvm::SmallBitVector CheckedVarArgs;
723 if (FDecl) {
Richard Trieu0538f0e2013-06-22 00:20:41 +0000724 for (specific_attr_iterator<FormatAttr>
Benjamin Kramer47abb252013-08-08 11:08:26 +0000725 I = FDecl->specific_attr_begin<FormatAttr>(),
726 E = FDecl->specific_attr_end<FormatAttr>();
Benjamin Kramer541a28f2013-08-09 09:39:17 +0000727 I != E; ++I) {
728 // Only create vector if there are format attributes.
729 CheckedVarArgs.resize(Args.size());
730
Benjamin Kramer47abb252013-08-08 11:08:26 +0000731 CheckFormatArguments(*I, Args, IsMemberFunction, CallType, Loc, Range,
732 CheckedVarArgs);
Benjamin Kramer541a28f2013-08-09 09:39:17 +0000733 }
Richard Smith0e218972013-08-05 18:49:43 +0000734 }
Richard Smith831421f2012-06-25 20:30:08 +0000735
736 // Refuse POD arguments that weren't caught by the format string
737 // checks above.
Richard Smith0e218972013-08-05 18:49:43 +0000738 if (CallType != VariadicDoesNotApply) {
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000739 for (unsigned ArgIdx = NumProtoArgs; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek0234bfa2012-10-11 19:06:43 +0000740 // Args[ArgIdx] can be null in malformed code.
Richard Smith0e218972013-08-05 18:49:43 +0000741 if (const Expr *Arg = Args[ArgIdx]) {
742 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
743 checkVariadicArgument(Arg, CallType);
744 }
Ted Kremenek0234bfa2012-10-11 19:06:43 +0000745 }
Richard Smith0e218972013-08-05 18:49:43 +0000746 }
Mike Stump1eb44332009-09-09 15:08:12 +0000747
Richard Trieu0538f0e2013-06-22 00:20:41 +0000748 if (FDecl) {
749 for (specific_attr_iterator<NonNullAttr>
750 I = FDecl->specific_attr_begin<NonNullAttr>(),
751 E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I)
752 CheckNonNullArguments(*I, Args.data(), Loc);
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +0000753
Richard Trieu0538f0e2013-06-22 00:20:41 +0000754 // Type safety checking.
755 for (specific_attr_iterator<ArgumentWithTypeTagAttr>
756 i = FDecl->specific_attr_begin<ArgumentWithTypeTagAttr>(),
757 e = FDecl->specific_attr_end<ArgumentWithTypeTagAttr>();
758 i != e; ++i) {
759 CheckArgumentWithTypeTag(*i, Args.data());
760 }
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +0000761 }
Richard Smith831421f2012-06-25 20:30:08 +0000762}
763
764/// CheckConstructorCall - Check a constructor call for correctness and safety
765/// properties not enforced by the C type system.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000766void Sema::CheckConstructorCall(FunctionDecl *FDecl,
767 ArrayRef<const Expr *> Args,
Richard Smith831421f2012-06-25 20:30:08 +0000768 const FunctionProtoType *Proto,
769 SourceLocation Loc) {
770 VariadicCallType CallType =
771 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000772 checkCall(FDecl, Args, Proto->getNumArgs(),
Richard Smith831421f2012-06-25 20:30:08 +0000773 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
774}
775
776/// CheckFunctionCall - Check a direct function call for various correctness
777/// and safety properties not strictly enforced by the C type system.
778bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
779 const FunctionProtoType *Proto) {
Eli Friedman2edcde82012-10-11 00:30:58 +0000780 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
781 isa<CXXMethodDecl>(FDecl);
782 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
783 IsMemberOperatorCall;
Richard Smith831421f2012-06-25 20:30:08 +0000784 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
785 TheCall->getCallee());
786 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
Eli Friedman2edcde82012-10-11 00:30:58 +0000787 Expr** Args = TheCall->getArgs();
788 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmandf75b0c2012-10-11 00:34:15 +0000789 if (IsMemberOperatorCall) {
Eli Friedman2edcde82012-10-11 00:30:58 +0000790 // If this is a call to a member operator, hide the first argument
791 // from checkCall.
792 // FIXME: Our choice of AST representation here is less than ideal.
793 ++Args;
794 --NumArgs;
795 }
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000796 checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs),
797 NumProtoArgs,
Richard Smith831421f2012-06-25 20:30:08 +0000798 IsMemberFunction, TheCall->getRParenLoc(),
799 TheCall->getCallee()->getSourceRange(), CallType);
800
801 IdentifierInfo *FnInfo = FDecl->getIdentifier();
802 // None of the checks below are needed for functions that don't have
803 // simple names (e.g., C++ conversion functions).
804 if (!FnInfo)
805 return false;
Sebastian Redl0eb23302009-01-19 00:08:26 +0000806
Anna Zaks0a151a12012-01-17 00:37:07 +0000807 unsigned CMId = FDecl->getMemoryFunctionKind();
808 if (CMId == 0)
Anna Zaksd9b859a2012-01-13 21:52:01 +0000809 return false;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000810
Anna Zaksd9b859a2012-01-13 21:52:01 +0000811 // Handle memory setting and copying functions.
Anna Zaks0a151a12012-01-17 00:37:07 +0000812 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000813 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaksc36bedc2012-02-01 19:08:57 +0000814 else if (CMId == Builtin::BIstrncat)
815 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaksd9b859a2012-01-13 21:52:01 +0000816 else
Anna Zaks0a151a12012-01-17 00:37:07 +0000817 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000818
Anders Carlssond406bf02009-08-16 01:56:34 +0000819 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000820}
821
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000822bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko287f24d2013-05-05 19:42:09 +0000823 ArrayRef<const Expr *> Args) {
Richard Smith831421f2012-06-25 20:30:08 +0000824 VariadicCallType CallType =
825 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000826
Dmitri Gribenko287f24d2013-05-05 19:42:09 +0000827 checkCall(Method, Args, Method->param_size(),
Richard Smith831421f2012-06-25 20:30:08 +0000828 /*IsMemberFunction=*/false,
829 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000830
831 return false;
832}
833
Richard Trieuf462b012013-06-20 21:03:13 +0000834bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
835 const FunctionProtoType *Proto) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000836 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
837 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000838 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000839
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000840 QualType Ty = V->getType();
Richard Trieuf462b012013-06-20 21:03:13 +0000841 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000842 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000843
Richard Trieuf462b012013-06-20 21:03:13 +0000844 VariadicCallType CallType;
Richard Trieua4993772013-06-20 23:21:54 +0000845 if (!Proto || !Proto->isVariadic()) {
Richard Trieuf462b012013-06-20 21:03:13 +0000846 CallType = VariadicDoesNotApply;
847 } else if (Ty->isBlockPointerType()) {
848 CallType = VariadicBlock;
849 } else { // Ty->isFunctionPointerType()
850 CallType = VariadicFunction;
851 }
Richard Smith831421f2012-06-25 20:30:08 +0000852 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
Anders Carlssond406bf02009-08-16 01:56:34 +0000853
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000854 checkCall(NDecl,
855 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
856 TheCall->getNumArgs()),
Richard Smith831421f2012-06-25 20:30:08 +0000857 NumProtoArgs, /*IsMemberFunction=*/false,
858 TheCall->getRParenLoc(),
859 TheCall->getCallee()->getSourceRange(), CallType);
860
Anders Carlssond406bf02009-08-16 01:56:34 +0000861 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000862}
863
Richard Trieu0538f0e2013-06-22 00:20:41 +0000864/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
865/// such as function pointers returned from functions.
866bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
867 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/0, Proto,
868 TheCall->getCallee());
869 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
870
871 checkCall(/*FDecl=*/0,
872 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
873 TheCall->getNumArgs()),
874 NumProtoArgs, /*IsMemberFunction=*/false,
875 TheCall->getRParenLoc(),
876 TheCall->getCallee()->getSourceRange(), CallType);
877
878 return false;
879}
880
Richard Smithff34d402012-04-12 05:08:17 +0000881ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
882 AtomicExpr::AtomicOp Op) {
Eli Friedman276b0612011-10-11 02:20:01 +0000883 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
884 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000885
Richard Smithff34d402012-04-12 05:08:17 +0000886 // All these operations take one of the following forms:
887 enum {
888 // C __c11_atomic_init(A *, C)
889 Init,
890 // C __c11_atomic_load(A *, int)
891 Load,
892 // void __atomic_load(A *, CP, int)
893 Copy,
894 // C __c11_atomic_add(A *, M, int)
895 Arithmetic,
896 // C __atomic_exchange_n(A *, CP, int)
897 Xchg,
898 // void __atomic_exchange(A *, C *, CP, int)
899 GNUXchg,
900 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
901 C11CmpXchg,
902 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
903 GNUCmpXchg
904 } Form = Init;
905 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
906 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
907 // where:
908 // C is an appropriate type,
909 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
910 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
911 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
912 // the int parameters are for orderings.
Eli Friedman276b0612011-10-11 02:20:01 +0000913
Richard Smithff34d402012-04-12 05:08:17 +0000914 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
915 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
916 && "need to update code for modified C11 atomics");
917 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
918 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
919 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
920 Op == AtomicExpr::AO__atomic_store_n ||
921 Op == AtomicExpr::AO__atomic_exchange_n ||
922 Op == AtomicExpr::AO__atomic_compare_exchange_n;
923 bool IsAddSub = false;
924
925 switch (Op) {
926 case AtomicExpr::AO__c11_atomic_init:
927 Form = Init;
928 break;
929
930 case AtomicExpr::AO__c11_atomic_load:
931 case AtomicExpr::AO__atomic_load_n:
932 Form = Load;
933 break;
934
935 case AtomicExpr::AO__c11_atomic_store:
936 case AtomicExpr::AO__atomic_load:
937 case AtomicExpr::AO__atomic_store:
938 case AtomicExpr::AO__atomic_store_n:
939 Form = Copy;
940 break;
941
942 case AtomicExpr::AO__c11_atomic_fetch_add:
943 case AtomicExpr::AO__c11_atomic_fetch_sub:
944 case AtomicExpr::AO__atomic_fetch_add:
945 case AtomicExpr::AO__atomic_fetch_sub:
946 case AtomicExpr::AO__atomic_add_fetch:
947 case AtomicExpr::AO__atomic_sub_fetch:
948 IsAddSub = true;
949 // Fall through.
950 case AtomicExpr::AO__c11_atomic_fetch_and:
951 case AtomicExpr::AO__c11_atomic_fetch_or:
952 case AtomicExpr::AO__c11_atomic_fetch_xor:
953 case AtomicExpr::AO__atomic_fetch_and:
954 case AtomicExpr::AO__atomic_fetch_or:
955 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smith51b92402012-04-13 06:31:38 +0000956 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithff34d402012-04-12 05:08:17 +0000957 case AtomicExpr::AO__atomic_and_fetch:
958 case AtomicExpr::AO__atomic_or_fetch:
959 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smith51b92402012-04-13 06:31:38 +0000960 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithff34d402012-04-12 05:08:17 +0000961 Form = Arithmetic;
962 break;
963
964 case AtomicExpr::AO__c11_atomic_exchange:
965 case AtomicExpr::AO__atomic_exchange_n:
966 Form = Xchg;
967 break;
968
969 case AtomicExpr::AO__atomic_exchange:
970 Form = GNUXchg;
971 break;
972
973 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
974 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
975 Form = C11CmpXchg;
976 break;
977
978 case AtomicExpr::AO__atomic_compare_exchange:
979 case AtomicExpr::AO__atomic_compare_exchange_n:
980 Form = GNUCmpXchg;
981 break;
982 }
983
984 // Check we have the right number of arguments.
985 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedman276b0612011-10-11 02:20:01 +0000986 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithff34d402012-04-12 05:08:17 +0000987 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000988 << TheCall->getCallee()->getSourceRange();
989 return ExprError();
Richard Smithff34d402012-04-12 05:08:17 +0000990 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
991 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedman276b0612011-10-11 02:20:01 +0000992 diag::err_typecheck_call_too_many_args)
Richard Smithff34d402012-04-12 05:08:17 +0000993 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000994 << TheCall->getCallee()->getSourceRange();
995 return ExprError();
996 }
997
Richard Smithff34d402012-04-12 05:08:17 +0000998 // Inspect the first argument of the atomic operation.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000999 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +00001000 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1001 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1002 if (!pointerType) {
Richard Smithff34d402012-04-12 05:08:17 +00001003 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedman276b0612011-10-11 02:20:01 +00001004 << Ptr->getType() << Ptr->getSourceRange();
1005 return ExprError();
1006 }
1007
Richard Smithff34d402012-04-12 05:08:17 +00001008 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1009 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1010 QualType ValType = AtomTy; // 'C'
1011 if (IsC11) {
1012 if (!AtomTy->isAtomicType()) {
1013 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1014 << Ptr->getType() << Ptr->getSourceRange();
1015 return ExprError();
1016 }
Richard Smithbc57b102012-09-15 06:09:58 +00001017 if (AtomTy.isConstQualified()) {
1018 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1019 << Ptr->getType() << Ptr->getSourceRange();
1020 return ExprError();
1021 }
Richard Smithff34d402012-04-12 05:08:17 +00001022 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedman276b0612011-10-11 02:20:01 +00001023 }
Eli Friedman276b0612011-10-11 02:20:01 +00001024
Richard Smithff34d402012-04-12 05:08:17 +00001025 // For an arithmetic operation, the implied arithmetic must be well-formed.
1026 if (Form == Arithmetic) {
1027 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1028 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1029 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1030 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1031 return ExprError();
1032 }
1033 if (!IsAddSub && !ValType->isIntegerType()) {
1034 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1035 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1036 return ExprError();
1037 }
1038 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1039 // For __atomic_*_n operations, the value type must be a scalar integral or
1040 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedman276b0612011-10-11 02:20:01 +00001041 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithff34d402012-04-12 05:08:17 +00001042 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1043 return ExprError();
1044 }
1045
Eli Friedmana3d727b2013-09-11 03:49:34 +00001046 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1047 !AtomTy->isScalarType()) {
Richard Smithff34d402012-04-12 05:08:17 +00001048 // For GNU atomics, require a trivially-copyable type. This is not part of
1049 // the GNU atomics specification, but we enforce it for sanity.
1050 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedman276b0612011-10-11 02:20:01 +00001051 << Ptr->getType() << Ptr->getSourceRange();
1052 return ExprError();
1053 }
1054
Richard Smithff34d402012-04-12 05:08:17 +00001055 // FIXME: For any builtin other than a load, the ValType must not be
1056 // const-qualified.
Eli Friedman276b0612011-10-11 02:20:01 +00001057
1058 switch (ValType.getObjCLifetime()) {
1059 case Qualifiers::OCL_None:
1060 case Qualifiers::OCL_ExplicitNone:
1061 // okay
1062 break;
1063
1064 case Qualifiers::OCL_Weak:
1065 case Qualifiers::OCL_Strong:
1066 case Qualifiers::OCL_Autoreleasing:
Richard Smithff34d402012-04-12 05:08:17 +00001067 // FIXME: Can this happen? By this point, ValType should be known
1068 // to be trivially copyable.
Eli Friedman276b0612011-10-11 02:20:01 +00001069 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1070 << ValType << Ptr->getSourceRange();
1071 return ExprError();
1072 }
1073
1074 QualType ResultType = ValType;
Richard Smithff34d402012-04-12 05:08:17 +00001075 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedman276b0612011-10-11 02:20:01 +00001076 ResultType = Context.VoidTy;
Richard Smithff34d402012-04-12 05:08:17 +00001077 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedman276b0612011-10-11 02:20:01 +00001078 ResultType = Context.BoolTy;
1079
Richard Smithff34d402012-04-12 05:08:17 +00001080 // The type of a parameter passed 'by value'. In the GNU atomics, such
1081 // arguments are actually passed as pointers.
1082 QualType ByValType = ValType; // 'CP'
1083 if (!IsC11 && !IsN)
1084 ByValType = Ptr->getType();
1085
Eli Friedman276b0612011-10-11 02:20:01 +00001086 // The first argument --- the pointer --- has a fixed type; we
1087 // deduce the types of the rest of the arguments accordingly. Walk
1088 // the remaining arguments, converting them to the deduced value type.
Richard Smithff34d402012-04-12 05:08:17 +00001089 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedman276b0612011-10-11 02:20:01 +00001090 QualType Ty;
Richard Smithff34d402012-04-12 05:08:17 +00001091 if (i < NumVals[Form] + 1) {
1092 switch (i) {
1093 case 1:
1094 // The second argument is the non-atomic operand. For arithmetic, this
1095 // is always passed by value, and for a compare_exchange it is always
1096 // passed by address. For the rest, GNU uses by-address and C11 uses
1097 // by-value.
1098 assert(Form != Load);
1099 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1100 Ty = ValType;
1101 else if (Form == Copy || Form == Xchg)
1102 Ty = ByValType;
1103 else if (Form == Arithmetic)
1104 Ty = Context.getPointerDiffType();
1105 else
1106 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1107 break;
1108 case 2:
1109 // The third argument to compare_exchange / GNU exchange is a
1110 // (pointer to a) desired value.
1111 Ty = ByValType;
1112 break;
1113 case 3:
1114 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1115 Ty = Context.BoolTy;
1116 break;
1117 }
Eli Friedman276b0612011-10-11 02:20:01 +00001118 } else {
1119 // The order(s) are always converted to int.
1120 Ty = Context.IntTy;
1121 }
Richard Smithff34d402012-04-12 05:08:17 +00001122
Eli Friedman276b0612011-10-11 02:20:01 +00001123 InitializedEntity Entity =
1124 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithff34d402012-04-12 05:08:17 +00001125 ExprResult Arg = TheCall->getArg(i);
Eli Friedman276b0612011-10-11 02:20:01 +00001126 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1127 if (Arg.isInvalid())
1128 return true;
1129 TheCall->setArg(i, Arg.get());
1130 }
1131
Richard Smithff34d402012-04-12 05:08:17 +00001132 // Permute the arguments into a 'consistent' order.
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001133 SmallVector<Expr*, 5> SubExprs;
1134 SubExprs.push_back(Ptr);
Richard Smithff34d402012-04-12 05:08:17 +00001135 switch (Form) {
1136 case Init:
1137 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnall7a7ee302012-01-16 17:27:18 +00001138 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +00001139 break;
1140 case Load:
1141 SubExprs.push_back(TheCall->getArg(1)); // Order
1142 break;
1143 case Copy:
1144 case Arithmetic:
1145 case Xchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001146 SubExprs.push_back(TheCall->getArg(2)); // Order
1147 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +00001148 break;
1149 case GNUXchg:
1150 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1151 SubExprs.push_back(TheCall->getArg(3)); // Order
1152 SubExprs.push_back(TheCall->getArg(1)); // Val1
1153 SubExprs.push_back(TheCall->getArg(2)); // Val2
1154 break;
1155 case C11CmpXchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001156 SubExprs.push_back(TheCall->getArg(3)); // Order
1157 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001158 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall2ebb98a2012-03-29 17:58:59 +00001159 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithff34d402012-04-12 05:08:17 +00001160 break;
1161 case GNUCmpXchg:
1162 SubExprs.push_back(TheCall->getArg(4)); // Order
1163 SubExprs.push_back(TheCall->getArg(1)); // Val1
1164 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1165 SubExprs.push_back(TheCall->getArg(2)); // Val2
1166 SubExprs.push_back(TheCall->getArg(3)); // Weak
1167 break;
Eli Friedman276b0612011-10-11 02:20:01 +00001168 }
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00001169
1170 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1171 SubExprs, ResultType, Op,
1172 TheCall->getRParenLoc());
1173
1174 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1175 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1176 Context.AtomicUsesUnsupportedLibcall(AE))
1177 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1178 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001179
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00001180 return Owned(AE);
Eli Friedman276b0612011-10-11 02:20:01 +00001181}
1182
1183
John McCall5f8d6042011-08-27 01:09:30 +00001184/// checkBuiltinArgument - Given a call to a builtin function, perform
1185/// normal type-checking on the given argument, updating the call in
1186/// place. This is useful when a builtin function requires custom
1187/// type-checking for some of its arguments but not necessarily all of
1188/// them.
1189///
1190/// Returns true on error.
1191static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1192 FunctionDecl *Fn = E->getDirectCallee();
1193 assert(Fn && "builtin call without direct callee!");
1194
1195 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1196 InitializedEntity Entity =
1197 InitializedEntity::InitializeParameter(S.Context, Param);
1198
1199 ExprResult Arg = E->getArg(0);
1200 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1201 if (Arg.isInvalid())
1202 return true;
1203
1204 E->setArg(ArgIndex, Arg.take());
1205 return false;
1206}
1207
Chris Lattner5caa3702009-05-08 06:58:22 +00001208/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1209/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1210/// type of its first argument. The main ActOnCallExpr routines have already
1211/// promoted the types of arguments because all of these calls are prototyped as
1212/// void(...).
1213///
1214/// This function goes through and does final semantic checking for these
1215/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +00001216ExprResult
1217Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +00001218 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +00001219 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1220 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1221
1222 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +00001223 if (TheCall->getNumArgs() < 1) {
1224 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1225 << 0 << 1 << TheCall->getNumArgs()
1226 << TheCall->getCallee()->getSourceRange();
1227 return ExprError();
1228 }
Mike Stump1eb44332009-09-09 15:08:12 +00001229
Chris Lattner5caa3702009-05-08 06:58:22 +00001230 // Inspect the first argument of the atomic builtin. This should always be
1231 // a pointer type, whose element is an integral scalar or pointer type.
1232 // Because it is a pointer type, we don't have to worry about any implicit
1233 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +00001234 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +00001235 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman8c382062012-01-23 02:35:22 +00001236 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1237 if (FirstArgResult.isInvalid())
1238 return ExprError();
1239 FirstArg = FirstArgResult.take();
1240 TheCall->setArg(0, FirstArg);
1241
John McCallf85e1932011-06-15 23:02:42 +00001242 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1243 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +00001244 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1245 << FirstArg->getType() << FirstArg->getSourceRange();
1246 return ExprError();
1247 }
Mike Stump1eb44332009-09-09 15:08:12 +00001248
John McCallf85e1932011-06-15 23:02:42 +00001249 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +00001250 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +00001251 !ValType->isBlockPointerType()) {
1252 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1253 << FirstArg->getType() << FirstArg->getSourceRange();
1254 return ExprError();
1255 }
Chris Lattner5caa3702009-05-08 06:58:22 +00001256
John McCallf85e1932011-06-15 23:02:42 +00001257 switch (ValType.getObjCLifetime()) {
1258 case Qualifiers::OCL_None:
1259 case Qualifiers::OCL_ExplicitNone:
1260 // okay
1261 break;
1262
1263 case Qualifiers::OCL_Weak:
1264 case Qualifiers::OCL_Strong:
1265 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001266 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001267 << ValType << FirstArg->getSourceRange();
1268 return ExprError();
1269 }
1270
John McCallb45ae252011-10-05 07:41:44 +00001271 // Strip any qualifiers off ValType.
1272 ValType = ValType.getUnqualifiedType();
1273
Chandler Carruth8d13d222010-07-18 20:54:12 +00001274 // The majority of builtins return a value, but a few have special return
1275 // types, so allow them to override appropriately below.
1276 QualType ResultType = ValType;
1277
Chris Lattner5caa3702009-05-08 06:58:22 +00001278 // We need to figure out which concrete builtin this maps onto. For example,
1279 // __sync_fetch_and_add with a 2 byte object turns into
1280 // __sync_fetch_and_add_2.
1281#define BUILTIN_ROW(x) \
1282 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1283 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +00001284
Chris Lattner5caa3702009-05-08 06:58:22 +00001285 static const unsigned BuiltinIndices[][5] = {
1286 BUILTIN_ROW(__sync_fetch_and_add),
1287 BUILTIN_ROW(__sync_fetch_and_sub),
1288 BUILTIN_ROW(__sync_fetch_and_or),
1289 BUILTIN_ROW(__sync_fetch_and_and),
1290 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +00001291
Chris Lattner5caa3702009-05-08 06:58:22 +00001292 BUILTIN_ROW(__sync_add_and_fetch),
1293 BUILTIN_ROW(__sync_sub_and_fetch),
1294 BUILTIN_ROW(__sync_and_and_fetch),
1295 BUILTIN_ROW(__sync_or_and_fetch),
1296 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +00001297
Chris Lattner5caa3702009-05-08 06:58:22 +00001298 BUILTIN_ROW(__sync_val_compare_and_swap),
1299 BUILTIN_ROW(__sync_bool_compare_and_swap),
1300 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +00001301 BUILTIN_ROW(__sync_lock_release),
1302 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +00001303 };
Mike Stump1eb44332009-09-09 15:08:12 +00001304#undef BUILTIN_ROW
1305
Chris Lattner5caa3702009-05-08 06:58:22 +00001306 // Determine the index of the size.
1307 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +00001308 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +00001309 case 1: SizeIndex = 0; break;
1310 case 2: SizeIndex = 1; break;
1311 case 4: SizeIndex = 2; break;
1312 case 8: SizeIndex = 3; break;
1313 case 16: SizeIndex = 4; break;
1314 default:
Chandler Carruthd2014572010-07-09 18:59:35 +00001315 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1316 << FirstArg->getType() << FirstArg->getSourceRange();
1317 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +00001318 }
Mike Stump1eb44332009-09-09 15:08:12 +00001319
Chris Lattner5caa3702009-05-08 06:58:22 +00001320 // Each of these builtins has one pointer argument, followed by some number of
1321 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1322 // that we ignore. Find out which row of BuiltinIndices to read from as well
1323 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00001324 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +00001325 unsigned BuiltinIndex, NumFixed = 1;
1326 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001327 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +00001328 case Builtin::BI__sync_fetch_and_add:
1329 case Builtin::BI__sync_fetch_and_add_1:
1330 case Builtin::BI__sync_fetch_and_add_2:
1331 case Builtin::BI__sync_fetch_and_add_4:
1332 case Builtin::BI__sync_fetch_and_add_8:
1333 case Builtin::BI__sync_fetch_and_add_16:
1334 BuiltinIndex = 0;
1335 break;
1336
1337 case Builtin::BI__sync_fetch_and_sub:
1338 case Builtin::BI__sync_fetch_and_sub_1:
1339 case Builtin::BI__sync_fetch_and_sub_2:
1340 case Builtin::BI__sync_fetch_and_sub_4:
1341 case Builtin::BI__sync_fetch_and_sub_8:
1342 case Builtin::BI__sync_fetch_and_sub_16:
1343 BuiltinIndex = 1;
1344 break;
1345
1346 case Builtin::BI__sync_fetch_and_or:
1347 case Builtin::BI__sync_fetch_and_or_1:
1348 case Builtin::BI__sync_fetch_and_or_2:
1349 case Builtin::BI__sync_fetch_and_or_4:
1350 case Builtin::BI__sync_fetch_and_or_8:
1351 case Builtin::BI__sync_fetch_and_or_16:
1352 BuiltinIndex = 2;
1353 break;
1354
1355 case Builtin::BI__sync_fetch_and_and:
1356 case Builtin::BI__sync_fetch_and_and_1:
1357 case Builtin::BI__sync_fetch_and_and_2:
1358 case Builtin::BI__sync_fetch_and_and_4:
1359 case Builtin::BI__sync_fetch_and_and_8:
1360 case Builtin::BI__sync_fetch_and_and_16:
1361 BuiltinIndex = 3;
1362 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001363
Douglas Gregora9766412011-11-28 16:30:08 +00001364 case Builtin::BI__sync_fetch_and_xor:
1365 case Builtin::BI__sync_fetch_and_xor_1:
1366 case Builtin::BI__sync_fetch_and_xor_2:
1367 case Builtin::BI__sync_fetch_and_xor_4:
1368 case Builtin::BI__sync_fetch_and_xor_8:
1369 case Builtin::BI__sync_fetch_and_xor_16:
1370 BuiltinIndex = 4;
1371 break;
1372
1373 case Builtin::BI__sync_add_and_fetch:
1374 case Builtin::BI__sync_add_and_fetch_1:
1375 case Builtin::BI__sync_add_and_fetch_2:
1376 case Builtin::BI__sync_add_and_fetch_4:
1377 case Builtin::BI__sync_add_and_fetch_8:
1378 case Builtin::BI__sync_add_and_fetch_16:
1379 BuiltinIndex = 5;
1380 break;
1381
1382 case Builtin::BI__sync_sub_and_fetch:
1383 case Builtin::BI__sync_sub_and_fetch_1:
1384 case Builtin::BI__sync_sub_and_fetch_2:
1385 case Builtin::BI__sync_sub_and_fetch_4:
1386 case Builtin::BI__sync_sub_and_fetch_8:
1387 case Builtin::BI__sync_sub_and_fetch_16:
1388 BuiltinIndex = 6;
1389 break;
1390
1391 case Builtin::BI__sync_and_and_fetch:
1392 case Builtin::BI__sync_and_and_fetch_1:
1393 case Builtin::BI__sync_and_and_fetch_2:
1394 case Builtin::BI__sync_and_and_fetch_4:
1395 case Builtin::BI__sync_and_and_fetch_8:
1396 case Builtin::BI__sync_and_and_fetch_16:
1397 BuiltinIndex = 7;
1398 break;
1399
1400 case Builtin::BI__sync_or_and_fetch:
1401 case Builtin::BI__sync_or_and_fetch_1:
1402 case Builtin::BI__sync_or_and_fetch_2:
1403 case Builtin::BI__sync_or_and_fetch_4:
1404 case Builtin::BI__sync_or_and_fetch_8:
1405 case Builtin::BI__sync_or_and_fetch_16:
1406 BuiltinIndex = 8;
1407 break;
1408
1409 case Builtin::BI__sync_xor_and_fetch:
1410 case Builtin::BI__sync_xor_and_fetch_1:
1411 case Builtin::BI__sync_xor_and_fetch_2:
1412 case Builtin::BI__sync_xor_and_fetch_4:
1413 case Builtin::BI__sync_xor_and_fetch_8:
1414 case Builtin::BI__sync_xor_and_fetch_16:
1415 BuiltinIndex = 9;
1416 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001417
Chris Lattner5caa3702009-05-08 06:58:22 +00001418 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001419 case Builtin::BI__sync_val_compare_and_swap_1:
1420 case Builtin::BI__sync_val_compare_and_swap_2:
1421 case Builtin::BI__sync_val_compare_and_swap_4:
1422 case Builtin::BI__sync_val_compare_and_swap_8:
1423 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001424 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +00001425 NumFixed = 2;
1426 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001427
Chris Lattner5caa3702009-05-08 06:58:22 +00001428 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001429 case Builtin::BI__sync_bool_compare_and_swap_1:
1430 case Builtin::BI__sync_bool_compare_and_swap_2:
1431 case Builtin::BI__sync_bool_compare_and_swap_4:
1432 case Builtin::BI__sync_bool_compare_and_swap_8:
1433 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001434 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +00001435 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001436 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001437 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001438
1439 case Builtin::BI__sync_lock_test_and_set:
1440 case Builtin::BI__sync_lock_test_and_set_1:
1441 case Builtin::BI__sync_lock_test_and_set_2:
1442 case Builtin::BI__sync_lock_test_and_set_4:
1443 case Builtin::BI__sync_lock_test_and_set_8:
1444 case Builtin::BI__sync_lock_test_and_set_16:
1445 BuiltinIndex = 12;
1446 break;
1447
Chris Lattner5caa3702009-05-08 06:58:22 +00001448 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +00001449 case Builtin::BI__sync_lock_release_1:
1450 case Builtin::BI__sync_lock_release_2:
1451 case Builtin::BI__sync_lock_release_4:
1452 case Builtin::BI__sync_lock_release_8:
1453 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001454 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +00001455 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001456 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001457 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001458
1459 case Builtin::BI__sync_swap:
1460 case Builtin::BI__sync_swap_1:
1461 case Builtin::BI__sync_swap_2:
1462 case Builtin::BI__sync_swap_4:
1463 case Builtin::BI__sync_swap_8:
1464 case Builtin::BI__sync_swap_16:
1465 BuiltinIndex = 14;
1466 break;
Chris Lattner5caa3702009-05-08 06:58:22 +00001467 }
Mike Stump1eb44332009-09-09 15:08:12 +00001468
Chris Lattner5caa3702009-05-08 06:58:22 +00001469 // Now that we know how many fixed arguments we expect, first check that we
1470 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +00001471 if (TheCall->getNumArgs() < 1+NumFixed) {
1472 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1473 << 0 << 1+NumFixed << TheCall->getNumArgs()
1474 << TheCall->getCallee()->getSourceRange();
1475 return ExprError();
1476 }
Mike Stump1eb44332009-09-09 15:08:12 +00001477
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001478 // Get the decl for the concrete builtin from this, we can tell what the
1479 // concrete integer type we should convert to is.
1480 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1481 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara2ad11cd2012-09-22 09:05:22 +00001482 FunctionDecl *NewBuiltinDecl;
1483 if (NewBuiltinID == BuiltinID)
1484 NewBuiltinDecl = FDecl;
1485 else {
1486 // Perform builtin lookup to avoid redeclaring it.
1487 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1488 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1489 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1490 assert(Res.getFoundDecl());
1491 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1492 if (NewBuiltinDecl == 0)
1493 return ExprError();
1494 }
Chandler Carruthd2014572010-07-09 18:59:35 +00001495
John McCallf871d0c2010-08-07 06:22:56 +00001496 // The first argument --- the pointer --- has a fixed type; we
1497 // deduce the types of the rest of the arguments accordingly. Walk
1498 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +00001499 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +00001500 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +00001501
Chris Lattner5caa3702009-05-08 06:58:22 +00001502 // GCC does an implicit conversion to the pointer or integer ValType. This
1503 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +00001504 // Initialize the argument.
1505 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1506 ValType, /*consume*/ false);
1507 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +00001508 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +00001509 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001510
Chris Lattner5caa3702009-05-08 06:58:22 +00001511 // Okay, we have something that *can* be converted to the right type. Check
1512 // to see if there is a potentially weird extension going on here. This can
1513 // happen when you do an atomic operation on something like an char* and
1514 // pass in 42. The 42 gets converted to char. This is even more strange
1515 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +00001516 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +00001517 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +00001518 }
Mike Stump1eb44332009-09-09 15:08:12 +00001519
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001520 ASTContext& Context = this->getASTContext();
1521
1522 // Create a new DeclRefExpr to refer to the new decl.
1523 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1524 Context,
1525 DRE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001526 SourceLocation(),
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001527 NewBuiltinDecl,
John McCallf4b88a42012-03-10 09:33:50 +00001528 /*enclosing*/ false,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001529 DRE->getLocation(),
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001530 Context.BuiltinFnTy,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001531 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +00001532
Chris Lattner5caa3702009-05-08 06:58:22 +00001533 // Set the callee in the CallExpr.
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001534 // FIXME: This loses syntactic information.
1535 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1536 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1537 CK_BuiltinFnToFnPtr);
John Wiegley429bb272011-04-08 18:41:53 +00001538 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001539
Chandler Carruthdb4325b2010-07-18 07:23:17 +00001540 // Change the result type of the call to match the original value type. This
1541 // is arbitrary, but the codegen for these builtins ins design to handle it
1542 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +00001543 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001544
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001545 return TheCallResult;
Chris Lattner5caa3702009-05-08 06:58:22 +00001546}
1547
Chris Lattner69039812009-02-18 06:01:06 +00001548/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00001549/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00001550/// Note: It might also make sense to do the UTF-16 conversion here (would
1551/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00001552bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00001553 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00001554 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1555
Douglas Gregor5cee1192011-07-27 05:40:30 +00001556 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001557 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1558 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001559 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001560 }
Mike Stump1eb44332009-09-09 15:08:12 +00001561
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001562 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001563 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001564 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001565 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divacky31ba6132012-09-06 15:59:27 +00001566 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001567 UTF16 *ToPtr = &ToBuf[0];
1568
1569 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1570 &ToPtr, ToPtr + NumBytes,
1571 strictConversion);
1572 // Check for conversion failure.
1573 if (Result != conversionOK)
1574 Diag(Arg->getLocStart(),
1575 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1576 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001577 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00001578}
1579
Chris Lattnerc27c6652007-12-20 00:05:45 +00001580/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1581/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00001582bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1583 Expr *Fn = TheCall->getCallee();
1584 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001585 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001586 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001587 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1588 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00001589 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001590 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00001591 return true;
1592 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00001593
1594 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00001595 return Diag(TheCall->getLocEnd(),
1596 diag::err_typecheck_call_too_few_args_at_least)
1597 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00001598 }
1599
John McCall5f8d6042011-08-27 01:09:30 +00001600 // Type-check the first argument normally.
1601 if (checkBuiltinArgument(*this, TheCall, 0))
1602 return true;
1603
Chris Lattnerc27c6652007-12-20 00:05:45 +00001604 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001605 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00001606 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001607 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00001608 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00001609 else if (FunctionDecl *FD = getCurFunctionDecl())
1610 isVariadic = FD->isVariadic();
1611 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001612 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00001613
Chris Lattnerc27c6652007-12-20 00:05:45 +00001614 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001615 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1616 return true;
1617 }
Mike Stump1eb44332009-09-09 15:08:12 +00001618
Chris Lattner30ce3442007-12-19 23:59:04 +00001619 // Verify that the second argument to the builtin is the last argument of the
1620 // current function or method.
1621 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00001622 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001623
Nico Weberb07d4482013-05-24 23:31:57 +00001624 // These are valid if SecondArgIsLastNamedArgument is false after the next
1625 // block.
1626 QualType Type;
1627 SourceLocation ParamLoc;
1628
Anders Carlsson88cf2262008-02-11 04:20:54 +00001629 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1630 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001631 // FIXME: This isn't correct for methods (results in bogus warning).
1632 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00001633 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001634 if (CurBlock)
1635 LastArg = *(CurBlock->TheDecl->param_end()-1);
1636 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00001637 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001638 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001639 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001640 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weberb07d4482013-05-24 23:31:57 +00001641
1642 Type = PV->getType();
1643 ParamLoc = PV->getLocation();
Chris Lattner30ce3442007-12-19 23:59:04 +00001644 }
1645 }
Mike Stump1eb44332009-09-09 15:08:12 +00001646
Chris Lattner30ce3442007-12-19 23:59:04 +00001647 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001648 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00001649 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weberb07d4482013-05-24 23:31:57 +00001650 else if (Type->isReferenceType()) {
1651 Diag(Arg->getLocStart(),
1652 diag::warn_va_start_of_reference_type_is_undefined);
1653 Diag(ParamLoc, diag::note_parameter_type) << Type;
1654 }
1655
Enea Zaffanella54de9bb2013-11-07 08:14:26 +00001656 TheCall->setType(Context.VoidTy);
Chris Lattner30ce3442007-12-19 23:59:04 +00001657 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00001658}
Chris Lattner30ce3442007-12-19 23:59:04 +00001659
Chris Lattner1b9a0792007-12-20 00:26:33 +00001660/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1661/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00001662bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1663 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001664 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001665 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001666 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001667 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001668 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001669 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001670 << SourceRange(TheCall->getArg(2)->getLocStart(),
1671 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001672
John Wiegley429bb272011-04-08 18:41:53 +00001673 ExprResult OrigArg0 = TheCall->getArg(0);
1674 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001675
Chris Lattner1b9a0792007-12-20 00:26:33 +00001676 // Do standard promotions between the two arguments, returning their common
1677 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001678 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001679 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1680 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001681
1682 // Make sure any conversions are pushed back into the call; this is
1683 // type safe since unordered compare builtins are declared as "_Bool
1684 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001685 TheCall->setArg(0, OrigArg0.get());
1686 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001687
John Wiegley429bb272011-04-08 18:41:53 +00001688 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001689 return false;
1690
Chris Lattner1b9a0792007-12-20 00:26:33 +00001691 // If the common type isn't a real floating type, then the arguments were
1692 // invalid for this operation.
Eli Friedman860a3192012-06-16 02:19:17 +00001693 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001694 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001695 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001696 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1697 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001698
Chris Lattner1b9a0792007-12-20 00:26:33 +00001699 return false;
1700}
1701
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001702/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1703/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001704/// to check everything. We expect the last argument to be a floating point
1705/// value.
1706bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1707 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001708 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001709 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001710 if (TheCall->getNumArgs() > NumArgs)
1711 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001712 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001713 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001714 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001715 (*(TheCall->arg_end()-1))->getLocEnd());
1716
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001717 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001718
Eli Friedman9ac6f622009-08-31 20:06:00 +00001719 if (OrigArg->isTypeDependent())
1720 return false;
1721
Chris Lattner81368fb2010-05-06 05:50:07 +00001722 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001723 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001724 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001725 diag::err_typecheck_call_invalid_unary_fp)
1726 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001727
Chris Lattner81368fb2010-05-06 05:50:07 +00001728 // If this is an implicit conversion from float -> double, remove it.
1729 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1730 Expr *CastArg = Cast->getSubExpr();
1731 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1732 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1733 "promotion from float to double is the only expected cast here");
1734 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001735 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner81368fb2010-05-06 05:50:07 +00001736 }
1737 }
1738
Eli Friedman9ac6f622009-08-31 20:06:00 +00001739 return false;
1740}
1741
Eli Friedmand38617c2008-05-14 19:38:39 +00001742/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1743// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001744ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001745 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001746 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001747 diag::err_typecheck_call_too_few_args_at_least)
Craig Topperb44545a2013-07-28 21:50:10 +00001748 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1749 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001750
Nate Begeman37b6a572010-06-08 00:16:34 +00001751 // Determine which of the following types of shufflevector we're checking:
1752 // 1) unary, vector mask: (lhs, mask)
1753 // 2) binary, vector mask: (lhs, rhs, mask)
1754 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1755 QualType resType = TheCall->getArg(0)->getType();
1756 unsigned numElements = 0;
Craig Toppere3fbbe92013-07-19 04:46:31 +00001757
Douglas Gregorcde01732009-05-19 22:10:17 +00001758 if (!TheCall->getArg(0)->isTypeDependent() &&
1759 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001760 QualType LHSType = TheCall->getArg(0)->getType();
1761 QualType RHSType = TheCall->getArg(1)->getType();
Craig Toppere3fbbe92013-07-19 04:46:31 +00001762
Craig Topperbbe759c2013-07-29 06:47:04 +00001763 if (!LHSType->isVectorType() || !RHSType->isVectorType())
1764 return ExprError(Diag(TheCall->getLocStart(),
1765 diag::err_shufflevector_non_vector)
1766 << SourceRange(TheCall->getArg(0)->getLocStart(),
1767 TheCall->getArg(1)->getLocEnd()));
Craig Toppere3fbbe92013-07-19 04:46:31 +00001768
Nate Begeman37b6a572010-06-08 00:16:34 +00001769 numElements = LHSType->getAs<VectorType>()->getNumElements();
1770 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001771
Nate Begeman37b6a572010-06-08 00:16:34 +00001772 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1773 // with mask. If so, verify that RHS is an integer vector type with the
1774 // same number of elts as lhs.
1775 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru4cb3d902013-07-06 08:00:09 +00001776 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001777 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbbe759c2013-07-29 06:47:04 +00001778 return ExprError(Diag(TheCall->getLocStart(),
1779 diag::err_shufflevector_incompatible_vector)
1780 << SourceRange(TheCall->getArg(1)->getLocStart(),
1781 TheCall->getArg(1)->getLocEnd()));
Craig Toppere3fbbe92013-07-19 04:46:31 +00001782 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbbe759c2013-07-29 06:47:04 +00001783 return ExprError(Diag(TheCall->getLocStart(),
1784 diag::err_shufflevector_incompatible_vector)
1785 << SourceRange(TheCall->getArg(0)->getLocStart(),
1786 TheCall->getArg(1)->getLocEnd()));
Nate Begeman37b6a572010-06-08 00:16:34 +00001787 } else if (numElements != numResElements) {
1788 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001789 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001790 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001791 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001792 }
1793
1794 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001795 if (TheCall->getArg(i)->isTypeDependent() ||
1796 TheCall->getArg(i)->isValueDependent())
1797 continue;
1798
Nate Begeman37b6a572010-06-08 00:16:34 +00001799 llvm::APSInt Result(32);
1800 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1801 return ExprError(Diag(TheCall->getLocStart(),
Craig Topperb44545a2013-07-28 21:50:10 +00001802 diag::err_shufflevector_nonconstant_argument)
1803 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001804
Craig Topper6f4f8082013-08-03 17:40:38 +00001805 // Allow -1 which will be translated to undef in the IR.
1806 if (Result.isSigned() && Result.isAllOnesValue())
1807 continue;
1808
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001809 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001810 return ExprError(Diag(TheCall->getLocStart(),
Craig Topperb44545a2013-07-28 21:50:10 +00001811 diag::err_shufflevector_argument_too_large)
1812 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001813 }
1814
Chris Lattner5f9e2722011-07-23 10:55:15 +00001815 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001816
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001817 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001818 exprs.push_back(TheCall->getArg(i));
1819 TheCall->setArg(i, 0);
1820 }
1821
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001822 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001823 TheCall->getCallee()->getLocStart(),
1824 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001825}
Chris Lattner30ce3442007-12-19 23:59:04 +00001826
Hal Finkel414a1bd2013-09-18 03:29:45 +00001827/// SemaConvertVectorExpr - Handle __builtin_convertvector
1828ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
1829 SourceLocation BuiltinLoc,
1830 SourceLocation RParenLoc) {
1831 ExprValueKind VK = VK_RValue;
1832 ExprObjectKind OK = OK_Ordinary;
1833 QualType DstTy = TInfo->getType();
1834 QualType SrcTy = E->getType();
1835
1836 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
1837 return ExprError(Diag(BuiltinLoc,
1838 diag::err_convertvector_non_vector)
1839 << E->getSourceRange());
1840 if (!DstTy->isVectorType() && !DstTy->isDependentType())
1841 return ExprError(Diag(BuiltinLoc,
1842 diag::err_convertvector_non_vector_type));
1843
1844 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
1845 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
1846 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
1847 if (SrcElts != DstElts)
1848 return ExprError(Diag(BuiltinLoc,
1849 diag::err_convertvector_incompatible_vector)
1850 << E->getSourceRange());
1851 }
1852
1853 return Owned(new (Context) ConvertVectorExpr(E, TInfo, DstTy, VK, OK,
1854 BuiltinLoc, RParenLoc));
1855
1856}
1857
Daniel Dunbar4493f792008-07-21 22:59:13 +00001858/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1859// This is declared to take (const void*, ...) and can take two
1860// optional constant int args.
1861bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001862 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001863
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001864 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001865 return Diag(TheCall->getLocEnd(),
1866 diag::err_typecheck_call_too_many_args_at_most)
1867 << 0 /*function call*/ << 3 << NumArgs
1868 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001869
1870 // Argument 0 is checked for us and the remaining arguments must be
1871 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001872 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001873 Expr *Arg = TheCall->getArg(i);
Douglas Gregor592a4232012-06-29 01:05:22 +00001874
1875 // We can't check the value of a dependent argument.
1876 if (Arg->isTypeDependent() || Arg->isValueDependent())
1877 continue;
1878
Eli Friedman9aef7262009-12-04 00:30:06 +00001879 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001880 if (SemaBuiltinConstantArg(TheCall, i, Result))
1881 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001882
Daniel Dunbar4493f792008-07-21 22:59:13 +00001883 // FIXME: gcc issues a warning and rewrites these to 0. These
1884 // seems especially odd for the third argument since the default
1885 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001886 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001887 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001888 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001889 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001890 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001891 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001892 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001893 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001894 }
1895 }
1896
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001897 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001898}
1899
Eric Christopher691ebc32010-04-17 02:26:23 +00001900/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1901/// TheCall is a constant expression.
1902bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1903 llvm::APSInt &Result) {
1904 Expr *Arg = TheCall->getArg(ArgNum);
1905 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1906 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1907
1908 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1909
1910 if (!Arg->isIntegerConstantExpr(Result, Context))
1911 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001912 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001913
Chris Lattner21fb98e2009-09-23 06:06:36 +00001914 return false;
1915}
1916
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001917/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1918/// int type). This simply type checks that type is one of the defined
1919/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001920// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001921bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001922 llvm::APSInt Result;
Douglas Gregor592a4232012-06-29 01:05:22 +00001923
1924 // We can't check the value of a dependent argument.
1925 if (TheCall->getArg(1)->isTypeDependent() ||
1926 TheCall->getArg(1)->isValueDependent())
1927 return false;
1928
Eric Christopher691ebc32010-04-17 02:26:23 +00001929 // Check constant-ness first.
1930 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1931 return true;
1932
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001933 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001934 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001935 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1936 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001937 }
1938
1939 return false;
1940}
1941
Eli Friedman586d6a82009-05-03 06:04:26 +00001942/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001943/// This checks that val is a constant 1.
1944bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1945 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001946 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001947
Eric Christopher691ebc32010-04-17 02:26:23 +00001948 // TODO: This is less than ideal. Overload this to take a value.
1949 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1950 return true;
1951
1952 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001953 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1954 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1955
1956 return false;
1957}
1958
Richard Smith0e218972013-08-05 18:49:43 +00001959namespace {
1960enum StringLiteralCheckType {
1961 SLCT_NotALiteral,
1962 SLCT_UncheckedLiteral,
1963 SLCT_CheckedLiteral
1964};
1965}
1966
Richard Smith831421f2012-06-25 20:30:08 +00001967// Determine if an expression is a string literal or constant string.
1968// If this function returns false on the arguments to a function expecting a
1969// format string, we will usually need to emit a warning.
1970// True string literals are then checked by CheckFormatString.
Richard Smith0e218972013-08-05 18:49:43 +00001971static StringLiteralCheckType
1972checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
1973 bool HasVAListArg, unsigned format_idx,
1974 unsigned firstDataArg, Sema::FormatStringType Type,
1975 Sema::VariadicCallType CallType, bool InFunctionCall,
1976 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001977 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001978 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith831421f2012-06-25 20:30:08 +00001979 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001980
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001981 E = E->IgnoreParenCasts();
Peter Collingbournef111d932011-04-15 00:35:48 +00001982
Richard Smith0e218972013-08-05 18:49:43 +00001983 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikiea73cdcb2012-02-10 21:07:25 +00001984 // Technically -Wformat-nonliteral does not warn about this case.
1985 // The behavior of printf and friends in this case is implementation
1986 // dependent. Ideally if the format string cannot be null then
1987 // it should have a 'nonnull' attribute in the function prototype.
Richard Smith0e218972013-08-05 18:49:43 +00001988 return SLCT_UncheckedLiteral;
David Blaikiea73cdcb2012-02-10 21:07:25 +00001989
Ted Kremenekd30ef872009-01-12 23:09:09 +00001990 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001991 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001992 case Stmt::ConditionalOperatorClass: {
Richard Smith831421f2012-06-25 20:30:08 +00001993 // The expression is a literal if both sub-expressions were, and it was
1994 // completely checked only if both sub-expressions were checked.
1995 const AbstractConditionalOperator *C =
1996 cast<AbstractConditionalOperator>(E);
1997 StringLiteralCheckType Left =
Richard Smith0e218972013-08-05 18:49:43 +00001998 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00001999 HasVAListArg, format_idx, firstDataArg,
Richard Smith0e218972013-08-05 18:49:43 +00002000 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002001 if (Left == SLCT_NotALiteral)
2002 return SLCT_NotALiteral;
2003 StringLiteralCheckType Right =
Richard Smith0e218972013-08-05 18:49:43 +00002004 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00002005 HasVAListArg, format_idx, firstDataArg,
Richard Smith0e218972013-08-05 18:49:43 +00002006 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002007 return Left < Right ? Left : Right;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002008 }
2009
2010 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00002011 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2012 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002013 }
2014
John McCall56ca35d2011-02-17 10:25:35 +00002015 case Stmt::OpaqueValueExprClass:
2016 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2017 E = src;
2018 goto tryAgain;
2019 }
Richard Smith831421f2012-06-25 20:30:08 +00002020 return SLCT_NotALiteral;
John McCall56ca35d2011-02-17 10:25:35 +00002021
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00002022 case Stmt::PredefinedExprClass:
2023 // While __func__, etc., are technically not string literals, they
2024 // cannot contain format specifiers and thus are not a security
2025 // liability.
Richard Smith831421f2012-06-25 20:30:08 +00002026 return SLCT_UncheckedLiteral;
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00002027
Ted Kremenek082d9362009-03-20 21:35:28 +00002028 case Stmt::DeclRefExprClass: {
2029 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002030
Ted Kremenek082d9362009-03-20 21:35:28 +00002031 // As an exception, do not flag errors for variables binding to
2032 // const string literals.
2033 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2034 bool isConstant = false;
2035 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00002036
Richard Smith0e218972013-08-05 18:49:43 +00002037 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2038 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002039 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smith0e218972013-08-05 18:49:43 +00002040 isConstant = T.isConstant(S.Context) &&
2041 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupase98e5b52012-01-25 10:35:33 +00002042 } else if (T->isObjCObjectPointerType()) {
2043 // In ObjC, there is usually no "const ObjectPointer" type,
2044 // so don't check if the pointee type is constant.
Richard Smith0e218972013-08-05 18:49:43 +00002045 isConstant = T.isConstant(S.Context);
Ted Kremenek082d9362009-03-20 21:35:28 +00002046 }
Mike Stump1eb44332009-09-09 15:08:12 +00002047
Ted Kremenek082d9362009-03-20 21:35:28 +00002048 if (isConstant) {
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00002049 if (const Expr *Init = VD->getAnyInitializer()) {
2050 // Look through initializers like const char c[] = { "foo" }
2051 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2052 if (InitList->isStringLiteralInit())
2053 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2054 }
Richard Smith0e218972013-08-05 18:49:43 +00002055 return checkFormatStringExpr(S, Init, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002056 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002057 firstDataArg, Type, CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002058 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00002059 }
Ted Kremenek082d9362009-03-20 21:35:28 +00002060 }
Mike Stump1eb44332009-09-09 15:08:12 +00002061
Anders Carlssond966a552009-06-28 19:55:58 +00002062 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2063 // special check to see if the format string is a function parameter
2064 // of the function calling the printf function. If the function
2065 // has an attribute indicating it is a printf-like function, then we
2066 // should suppress warnings concerning non-literals being used in a call
2067 // to a vprintf function. For example:
2068 //
2069 // void
2070 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2071 // va_list ap;
2072 // va_start(ap, fmt);
2073 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2074 // ...
Richard Smith0e218972013-08-05 18:49:43 +00002075 // }
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00002076 if (HasVAListArg) {
2077 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2078 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2079 int PVIndex = PV->getFunctionScopeIndex() + 1;
2080 for (specific_attr_iterator<FormatAttr>
2081 i = ND->specific_attr_begin<FormatAttr>(),
2082 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
2083 FormatAttr *PVFormat = *i;
2084 // adjust for implicit parameter
2085 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2086 if (MD->isInstance())
2087 ++PVIndex;
2088 // We also check if the formats are compatible.
2089 // We can't pass a 'scanf' string to a 'printf' function.
2090 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smith0e218972013-08-05 18:49:43 +00002091 Type == S.GetFormatStringType(PVFormat))
Richard Smith831421f2012-06-25 20:30:08 +00002092 return SLCT_UncheckedLiteral;
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00002093 }
2094 }
2095 }
2096 }
Ted Kremenek082d9362009-03-20 21:35:28 +00002097 }
Mike Stump1eb44332009-09-09 15:08:12 +00002098
Richard Smith831421f2012-06-25 20:30:08 +00002099 return SLCT_NotALiteral;
Ted Kremenek082d9362009-03-20 21:35:28 +00002100 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00002101
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00002102 case Stmt::CallExprClass:
2103 case Stmt::CXXMemberCallExprClass: {
Anders Carlsson8f031b32009-06-27 04:05:33 +00002104 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00002105 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2106 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2107 unsigned ArgIndex = FA->getFormatIdx();
2108 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2109 if (MD->isInstance())
2110 --ArgIndex;
2111 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00002112
Richard Smith0e218972013-08-05 18:49:43 +00002113 return checkFormatStringExpr(S, Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002114 HasVAListArg, format_idx, firstDataArg,
Richard Smith0e218972013-08-05 18:49:43 +00002115 Type, CallType, InFunctionCall,
2116 CheckedVarArgs);
Jordan Rose50687312012-06-04 23:52:23 +00002117 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2118 unsigned BuiltinID = FD->getBuiltinID();
2119 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2120 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2121 const Expr *Arg = CE->getArg(0);
Richard Smith0e218972013-08-05 18:49:43 +00002122 return checkFormatStringExpr(S, Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002123 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002124 firstDataArg, Type, CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002125 InFunctionCall, CheckedVarArgs);
Jordan Rose50687312012-06-04 23:52:23 +00002126 }
Anders Carlsson8f031b32009-06-27 04:05:33 +00002127 }
2128 }
Mike Stump1eb44332009-09-09 15:08:12 +00002129
Richard Smith831421f2012-06-25 20:30:08 +00002130 return SLCT_NotALiteral;
Anders Carlsson8f031b32009-06-27 04:05:33 +00002131 }
Fariborz Jahanianc85832f2013-10-18 21:20:34 +00002132
2133 case Stmt::ObjCMessageExprClass: {
2134 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(E);
2135 if (const ObjCMethodDecl *MDecl = ME->getMethodDecl()) {
2136 if (const NamedDecl *ND = dyn_cast<NamedDecl>(MDecl)) {
2137 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2138 unsigned ArgIndex = FA->getFormatIdx();
2139 if (ArgIndex <= ME->getNumArgs()) {
2140 const Expr *Arg = ME->getArg(ArgIndex-1);
2141 return checkFormatStringExpr(S, Arg, Args,
2142 HasVAListArg, format_idx,
2143 firstDataArg, Type, CallType,
2144 InFunctionCall, CheckedVarArgs);
2145 }
2146 }
2147 }
2148 }
2149
2150 return SLCT_NotALiteral;
2151 }
2152
Ted Kremenek082d9362009-03-20 21:35:28 +00002153 case Stmt::ObjCStringLiteralClass:
2154 case Stmt::StringLiteralClass: {
2155 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00002156
Ted Kremenek082d9362009-03-20 21:35:28 +00002157 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00002158 StrE = ObjCFExpr->getString();
2159 else
Ted Kremenek082d9362009-03-20 21:35:28 +00002160 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002161
Ted Kremenekd30ef872009-01-12 23:09:09 +00002162 if (StrE) {
Richard Smith0e218972013-08-05 18:49:43 +00002163 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2164 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002165 return SLCT_CheckedLiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002166 }
Mike Stump1eb44332009-09-09 15:08:12 +00002167
Richard Smith831421f2012-06-25 20:30:08 +00002168 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002169 }
Mike Stump1eb44332009-09-09 15:08:12 +00002170
Ted Kremenek082d9362009-03-20 21:35:28 +00002171 default:
Richard Smith831421f2012-06-25 20:30:08 +00002172 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002173 }
2174}
2175
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00002176void
Mike Stump1eb44332009-09-09 15:08:12 +00002177Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00002178 const Expr * const *ExprArgs,
2179 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00002180 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
2181 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00002182 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00002183 const Expr *ArgExpr = ExprArgs[*i];
Nick Lewycky3edf3872013-01-23 05:08:29 +00002184
2185 // As a special case, transparent unions initialized with zero are
2186 // considered null for the purposes of the nonnull attribute.
2187 if (const RecordType *UT = ArgExpr->getType()->getAsUnionType()) {
2188 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2189 if (const CompoundLiteralExpr *CLE =
2190 dyn_cast<CompoundLiteralExpr>(ArgExpr))
2191 if (const InitListExpr *ILE =
2192 dyn_cast<InitListExpr>(CLE->getInitializer()))
2193 ArgExpr = ILE->getInit(0);
2194 }
2195
2196 bool Result;
2197 if (ArgExpr->EvaluateAsBooleanCondition(Result, Context) && !Result)
Nick Lewycky909a70d2011-03-25 01:44:32 +00002198 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00002199 }
2200}
Ted Kremenekd30ef872009-01-12 23:09:09 +00002201
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002202Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmancaa5ab22013-09-03 21:02:22 +00002203 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002204 .Case("scanf", FST_Scanf)
2205 .Cases("printf", "printf0", FST_Printf)
2206 .Cases("NSString", "CFString", FST_NSString)
2207 .Case("strftime", FST_Strftime)
2208 .Case("strfmon", FST_Strfmon)
2209 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2210 .Default(FST_Unknown);
2211}
2212
Jordan Roseddcfbc92012-07-19 18:10:23 +00002213/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek826a3452010-07-16 02:11:22 +00002214/// functions) for correct use of format strings.
Richard Smith831421f2012-06-25 20:30:08 +00002215/// Returns true if a format string has been fully checked.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002216bool Sema::CheckFormatArguments(const FormatAttr *Format,
2217 ArrayRef<const Expr *> Args,
2218 bool IsCXXMember,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002219 VariadicCallType CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002220 SourceLocation Loc, SourceRange Range,
2221 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith831421f2012-06-25 20:30:08 +00002222 FormatStringInfo FSI;
2223 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002224 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith831421f2012-06-25 20:30:08 +00002225 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smith0e218972013-08-05 18:49:43 +00002226 CallType, Loc, Range, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002227 return false;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002228}
Sebastian Redl4a2614e2009-11-17 18:02:24 +00002229
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002230bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002231 bool HasVAListArg, unsigned format_idx,
2232 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002233 VariadicCallType CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002234 SourceLocation Loc, SourceRange Range,
2235 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002236 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002237 if (format_idx >= Args.size()) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002238 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith831421f2012-06-25 20:30:08 +00002239 return false;
Ted Kremenek71895b92007-08-14 17:39:48 +00002240 }
Mike Stump1eb44332009-09-09 15:08:12 +00002241
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002242 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00002243
Chris Lattner59907c42007-08-10 20:18:51 +00002244 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00002245 //
Ted Kremenek71895b92007-08-14 17:39:48 +00002246 // Dynamically generated format strings are difficult to
2247 // automatically vet at compile time. Requiring that format strings
2248 // are string literals: (1) permits the checking of format strings by
2249 // the compiler and thereby (2) can practically remove the source of
2250 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002251
Mike Stump1eb44332009-09-09 15:08:12 +00002252 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002253 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00002254 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002255 // the same format string checking logic for both ObjC and C strings.
Richard Smith831421f2012-06-25 20:30:08 +00002256 StringLiteralCheckType CT =
Richard Smith0e218972013-08-05 18:49:43 +00002257 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2258 format_idx, firstDataArg, Type, CallType,
2259 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002260 if (CT != SLCT_NotALiteral)
2261 // Literal format string found, check done!
2262 return CT == SLCT_CheckedLiteral;
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002263
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00002264 // Strftime is particular as it always uses a single 'time' argument,
2265 // so it is safe to pass a non-literal string.
2266 if (Type == FST_Strftime)
Richard Smith831421f2012-06-25 20:30:08 +00002267 return false;
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00002268
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00002269 // Do not emit diag when the string param is a macro expansion and the
2270 // format is either NSString or CFString. This is a hack to prevent
2271 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2272 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupasdc170202012-05-04 21:08:08 +00002273 if (Type == FST_NSString &&
2274 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith831421f2012-06-25 20:30:08 +00002275 return false;
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00002276
Chris Lattner655f1412009-04-29 04:59:47 +00002277 // If there are no arguments specified, warn with -Wformat-security, otherwise
2278 // warn only with -Wformat-nonliteral.
Eli Friedman2243e782013-06-18 18:10:01 +00002279 if (Args.size() == firstDataArg)
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002280 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00002281 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00002282 << OrigFormatExpr->getSourceRange();
2283 else
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002284 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00002285 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00002286 << OrigFormatExpr->getSourceRange();
Richard Smith831421f2012-06-25 20:30:08 +00002287 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002288}
Ted Kremenek71895b92007-08-14 17:39:48 +00002289
Ted Kremeneke0e53132010-01-28 23:39:18 +00002290namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00002291class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2292protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00002293 Sema &S;
2294 const StringLiteral *FExpr;
2295 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00002296 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00002297 const unsigned NumDataArgs;
Ted Kremeneke0e53132010-01-28 23:39:18 +00002298 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00002299 const bool HasVAListArg;
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002300 ArrayRef<const Expr *> Args;
Ted Kremenek0d277352010-01-29 01:06:55 +00002301 unsigned FormatIdx;
Richard Smith0e218972013-08-05 18:49:43 +00002302 llvm::SmallBitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00002303 bool usesPositionalArgs;
2304 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00002305 bool inFunctionCall;
Jordan Roseddcfbc92012-07-19 18:10:23 +00002306 Sema::VariadicCallType CallType;
Richard Smith0e218972013-08-05 18:49:43 +00002307 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002308public:
Ted Kremenek826a3452010-07-16 02:11:22 +00002309 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00002310 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002311 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002312 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002313 unsigned formatIdx, bool inFunctionCall,
Richard Smith0e218972013-08-05 18:49:43 +00002314 Sema::VariadicCallType callType,
2315 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremeneke0e53132010-01-28 23:39:18 +00002316 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose50687312012-06-04 23:52:23 +00002317 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2318 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002319 Args(Args), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00002320 usesPositionalArgs(false), atFirstArg(true),
Richard Smith0e218972013-08-05 18:49:43 +00002321 inFunctionCall(inFunctionCall), CallType(callType),
2322 CheckedVarArgs(CheckedVarArgs) {
2323 CoveredArgs.resize(numDataArgs);
2324 CoveredArgs.reset();
2325 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002326
Ted Kremenek07d161f2010-01-29 01:50:07 +00002327 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002328
Ted Kremenek826a3452010-07-16 02:11:22 +00002329 void HandleIncompleteSpecifier(const char *startSpecifier,
2330 unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00002331
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002332 void HandleInvalidLengthModifier(
2333 const analyze_format_string::FormatSpecifier &FS,
2334 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00002335 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002336
Hans Wennborg76517422012-02-22 10:17:01 +00002337 void HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00002338 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00002339 const char *startSpecifier, unsigned specifierLen);
2340
2341 void HandleNonStandardConversionSpecifier(
2342 const analyze_format_string::ConversionSpecifier &CS,
2343 const char *startSpecifier, unsigned specifierLen);
2344
Hans Wennborgf8562642012-03-09 10:10:54 +00002345 virtual void HandlePosition(const char *startPos, unsigned posLen);
2346
Ted Kremenekefaff192010-02-27 01:41:03 +00002347 virtual void HandleInvalidPosition(const char *startSpecifier,
2348 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00002349 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00002350
2351 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
2352
Ted Kremeneke0e53132010-01-28 23:39:18 +00002353 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002354
Richard Trieu55733de2011-10-28 00:41:25 +00002355 template <typename Range>
2356 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2357 const Expr *ArgumentExpr,
2358 PartialDiagnostic PDiag,
2359 SourceLocation StringLoc,
2360 bool IsStringLocation, Range StringRange,
Dmitri Gribenko55431692013-05-05 00:41:58 +00002361 ArrayRef<FixItHint> Fixit = None);
Richard Trieu55733de2011-10-28 00:41:25 +00002362
Ted Kremenek826a3452010-07-16 02:11:22 +00002363protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002364 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2365 const char *startSpec,
2366 unsigned specifierLen,
2367 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00002368
2369 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2370 const char *startSpec,
2371 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002372
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002373 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00002374 CharSourceRange getSpecifierRange(const char *startSpecifier,
2375 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002376 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002377
Ted Kremenek0d277352010-01-29 01:06:55 +00002378 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00002379
2380 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2381 const analyze_format_string::ConversionSpecifier &CS,
2382 const char *startSpecifier, unsigned specifierLen,
2383 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00002384
2385 template <typename Range>
2386 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2387 bool IsStringLocation, Range StringRange,
Dmitri Gribenko55431692013-05-05 00:41:58 +00002388 ArrayRef<FixItHint> Fixit = None);
Richard Trieu55733de2011-10-28 00:41:25 +00002389
2390 void CheckPositionalAndNonpositionalArgs(
2391 const analyze_format_string::FormatSpecifier *FS);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002392};
2393}
2394
Ted Kremenek826a3452010-07-16 02:11:22 +00002395SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00002396 return OrigFormatExpr->getSourceRange();
2397}
2398
Ted Kremenek826a3452010-07-16 02:11:22 +00002399CharSourceRange CheckFormatHandler::
2400getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002401 SourceLocation Start = getLocationOfByte(startSpecifier);
2402 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2403
2404 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002405 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00002406
2407 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002408}
2409
Ted Kremenek826a3452010-07-16 02:11:22 +00002410SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002411 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002412}
2413
Ted Kremenek826a3452010-07-16 02:11:22 +00002414void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2415 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00002416 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2417 getLocationOfByte(startSpecifier),
2418 /*IsStringLocation*/true,
2419 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00002420}
2421
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002422void CheckFormatHandler::HandleInvalidLengthModifier(
2423 const analyze_format_string::FormatSpecifier &FS,
2424 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00002425 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002426 using namespace analyze_format_string;
2427
2428 const LengthModifier &LM = FS.getLengthModifier();
2429 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2430
2431 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002432 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002433 if (FixedLM) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002434 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002435 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 {
Jordan Rose8be066e2012-09-08 04:00:12 +00002444 FixItHint Hint;
2445 if (DiagID == diag::warn_format_nonsensical_length)
2446 Hint = FixItHint::CreateRemoval(LMRange);
2447
2448 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002449 getLocationOfByte(LM.getStart()),
2450 /*IsStringLocation*/true,
2451 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose8be066e2012-09-08 04:00:12 +00002452 Hint);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002453 }
2454}
2455
Hans Wennborg76517422012-02-22 10:17:01 +00002456void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00002457 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00002458 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002459 using namespace analyze_format_string;
2460
2461 const LengthModifier &LM = FS.getLengthModifier();
2462 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2463
2464 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002465 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose8be066e2012-09-08 04:00:12 +00002466 if (FixedLM) {
2467 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2468 << LM.toString() << 0,
2469 getLocationOfByte(LM.getStart()),
2470 /*IsStringLocation*/true,
2471 getSpecifierRange(startSpecifier, specifierLen));
2472
2473 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2474 << FixedLM->toString()
2475 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2476
2477 } else {
2478 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2479 << LM.toString() << 0,
2480 getLocationOfByte(LM.getStart()),
2481 /*IsStringLocation*/true,
2482 getSpecifierRange(startSpecifier, specifierLen));
2483 }
Hans Wennborg76517422012-02-22 10:17:01 +00002484}
2485
2486void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2487 const analyze_format_string::ConversionSpecifier &CS,
2488 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose670941c2012-09-13 02:11:15 +00002489 using namespace analyze_format_string;
2490
2491 // See if we know how to fix this conversion specifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002492 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose670941c2012-09-13 02:11:15 +00002493 if (FixedCS) {
2494 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2495 << CS.toString() << /*conversion specifier*/1,
2496 getLocationOfByte(CS.getStart()),
2497 /*IsStringLocation*/true,
2498 getSpecifierRange(startSpecifier, specifierLen));
2499
2500 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2501 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2502 << FixedCS->toString()
2503 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2504 } else {
2505 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2506 << CS.toString() << /*conversion specifier*/1,
2507 getLocationOfByte(CS.getStart()),
2508 /*IsStringLocation*/true,
2509 getSpecifierRange(startSpecifier, specifierLen));
2510 }
Hans Wennborg76517422012-02-22 10:17:01 +00002511}
2512
Hans Wennborgf8562642012-03-09 10:10:54 +00002513void CheckFormatHandler::HandlePosition(const char *startPos,
2514 unsigned posLen) {
2515 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2516 getLocationOfByte(startPos),
2517 /*IsStringLocation*/true,
2518 getSpecifierRange(startPos, posLen));
2519}
2520
Ted Kremenekefaff192010-02-27 01:41:03 +00002521void
Ted Kremenek826a3452010-07-16 02:11:22 +00002522CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2523 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00002524 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2525 << (unsigned) p,
2526 getLocationOfByte(startPos), /*IsStringLocation*/true,
2527 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002528}
2529
Ted Kremenek826a3452010-07-16 02:11:22 +00002530void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00002531 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00002532 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2533 getLocationOfByte(startPos),
2534 /*IsStringLocation*/true,
2535 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002536}
2537
Ted Kremenek826a3452010-07-16 02:11:22 +00002538void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose50687312012-06-04 23:52:23 +00002539 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0c069442011-03-15 21:18:48 +00002540 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00002541 EmitFormatDiagnostic(
2542 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2543 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2544 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00002545 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002546}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002547
Jordan Rose48716662012-07-19 18:10:08 +00002548// Note that this may return NULL if there was an error parsing or building
2549// one of the argument expressions.
Ted Kremenek826a3452010-07-16 02:11:22 +00002550const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002551 return Args[FirstDataArg + i];
Ted Kremenek826a3452010-07-16 02:11:22 +00002552}
2553
2554void CheckFormatHandler::DoneProcessing() {
2555 // Does the number of data arguments exceed the number of
2556 // format conversions in the format string?
2557 if (!HasVAListArg) {
2558 // Find any arguments that weren't covered.
2559 CoveredArgs.flip();
2560 signed notCoveredArg = CoveredArgs.find_first();
2561 if (notCoveredArg >= 0) {
2562 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose48716662012-07-19 18:10:08 +00002563 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2564 SourceLocation Loc = E->getLocStart();
2565 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2566 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2567 Loc, /*IsStringLocation*/false,
2568 getFormatStringRange());
2569 }
Bob Wilsonc03f2df2012-05-03 19:47:19 +00002570 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002571 }
2572 }
2573}
2574
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002575bool
2576CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2577 SourceLocation Loc,
2578 const char *startSpec,
2579 unsigned specifierLen,
2580 const char *csStart,
2581 unsigned csLen) {
2582
2583 bool keepGoing = true;
2584 if (argIndex < NumDataArgs) {
2585 // Consider the argument coverered, even though the specifier doesn't
2586 // make sense.
2587 CoveredArgs.set(argIndex);
2588 }
2589 else {
2590 // If argIndex exceeds the number of data arguments we
2591 // don't issue a warning because that is just a cascade of warnings (and
2592 // they may have intended '%%' anyway). We don't want to continue processing
2593 // the format string after this point, however, as we will like just get
2594 // gibberish when trying to match arguments.
2595 keepGoing = false;
2596 }
2597
Richard Trieu55733de2011-10-28 00:41:25 +00002598 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2599 << StringRef(csStart, csLen),
2600 Loc, /*IsStringLocation*/true,
2601 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002602
2603 return keepGoing;
2604}
2605
Richard Trieu55733de2011-10-28 00:41:25 +00002606void
2607CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2608 const char *startSpec,
2609 unsigned specifierLen) {
2610 EmitFormatDiagnostic(
2611 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2612 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2613}
2614
Ted Kremenek666a1972010-07-26 19:45:42 +00002615bool
2616CheckFormatHandler::CheckNumArgs(
2617 const analyze_format_string::FormatSpecifier &FS,
2618 const analyze_format_string::ConversionSpecifier &CS,
2619 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2620
2621 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002622 PartialDiagnostic PDiag = FS.usesPositionalArg()
2623 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2624 << (argIndex+1) << NumDataArgs)
2625 : S.PDiag(diag::warn_printf_insufficient_data_args);
2626 EmitFormatDiagnostic(
2627 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2628 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00002629 return false;
2630 }
2631 return true;
2632}
2633
Richard Trieu55733de2011-10-28 00:41:25 +00002634template<typename Range>
2635void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2636 SourceLocation Loc,
2637 bool IsStringLocation,
2638 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002639 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002640 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu55733de2011-10-28 00:41:25 +00002641 Loc, IsStringLocation, StringRange, FixIt);
2642}
2643
2644/// \brief If the format string is not within the funcion call, emit a note
2645/// so that the function call and string are in diagnostic messages.
2646///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002647/// \param InFunctionCall if true, the format string is within the function
Richard Trieu55733de2011-10-28 00:41:25 +00002648/// call and only one diagnostic message will be produced. Otherwise, an
2649/// extra note will be emitted pointing to location of the format string.
2650///
2651/// \param ArgumentExpr the expression that is passed as the format string
2652/// argument in the function call. Used for getting locations when two
2653/// diagnostics are emitted.
2654///
2655/// \param PDiag the callee should already have provided any strings for the
2656/// diagnostic message. This function only adds locations and fixits
2657/// to diagnostics.
2658///
2659/// \param Loc primary location for diagnostic. If two diagnostics are
2660/// required, one will be at Loc and a new SourceLocation will be created for
2661/// the other one.
2662///
2663/// \param IsStringLocation if true, Loc points to the format string should be
2664/// used for the note. Otherwise, Loc points to the argument list and will
2665/// be used with PDiag.
2666///
2667/// \param StringRange some or all of the string to highlight. This is
2668/// templated so it can accept either a CharSourceRange or a SourceRange.
2669///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002670/// \param FixIt optional fix it hint for the format string.
Richard Trieu55733de2011-10-28 00:41:25 +00002671template<typename Range>
2672void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2673 const Expr *ArgumentExpr,
2674 PartialDiagnostic PDiag,
2675 SourceLocation Loc,
2676 bool IsStringLocation,
2677 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002678 ArrayRef<FixItHint> FixIt) {
2679 if (InFunctionCall) {
2680 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2681 D << StringRange;
2682 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2683 I != E; ++I) {
2684 D << *I;
2685 }
2686 } else {
Richard Trieu55733de2011-10-28 00:41:25 +00002687 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2688 << ArgumentExpr->getSourceRange();
Jordan Roseec087352012-09-05 22:56:26 +00002689
2690 const Sema::SemaDiagnosticBuilder &Note =
2691 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2692 diag::note_format_string_defined);
2693
2694 Note << StringRange;
2695 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2696 I != E; ++I) {
2697 Note << *I;
2698 }
Richard Trieu55733de2011-10-28 00:41:25 +00002699 }
2700}
2701
Ted Kremenek826a3452010-07-16 02:11:22 +00002702//===--- CHECK: Printf format string checking ------------------------------===//
2703
2704namespace {
2705class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose50687312012-06-04 23:52:23 +00002706 bool ObjCContext;
Ted Kremenek826a3452010-07-16 02:11:22 +00002707public:
2708 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2709 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002710 unsigned numDataArgs, bool isObjC,
Ted Kremenek826a3452010-07-16 02:11:22 +00002711 const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002712 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002713 unsigned formatIdx, bool inFunctionCall,
Richard Smith0e218972013-08-05 18:49:43 +00002714 Sema::VariadicCallType CallType,
2715 llvm::SmallBitVector &CheckedVarArgs)
2716 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2717 numDataArgs, beg, hasVAListArg, Args,
2718 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
2719 ObjCContext(isObjC)
Jordan Roseddcfbc92012-07-19 18:10:23 +00002720 {}
2721
Ted Kremenek826a3452010-07-16 02:11:22 +00002722
2723 bool HandleInvalidPrintfConversionSpecifier(
2724 const analyze_printf::PrintfSpecifier &FS,
2725 const char *startSpecifier,
2726 unsigned specifierLen);
2727
2728 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2729 const char *startSpecifier,
2730 unsigned specifierLen);
Richard Smith831421f2012-06-25 20:30:08 +00002731 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2732 const char *StartSpecifier,
2733 unsigned SpecifierLen,
2734 const Expr *E);
2735
Ted Kremenek826a3452010-07-16 02:11:22 +00002736 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2737 const char *startSpecifier, unsigned specifierLen);
2738 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2739 const analyze_printf::OptionalAmount &Amt,
2740 unsigned type,
2741 const char *startSpecifier, unsigned specifierLen);
2742 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2743 const analyze_printf::OptionalFlag &flag,
2744 const char *startSpecifier, unsigned specifierLen);
2745 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2746 const analyze_printf::OptionalFlag &ignoredFlag,
2747 const analyze_printf::OptionalFlag &flag,
2748 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgf3749f42012-08-07 08:11:26 +00002749 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith831421f2012-06-25 20:30:08 +00002750 const Expr *E, const CharSourceRange &CSR);
2751
Ted Kremenek826a3452010-07-16 02:11:22 +00002752};
2753}
2754
2755bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2756 const analyze_printf::PrintfSpecifier &FS,
2757 const char *startSpecifier,
2758 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002759 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002760 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002761
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002762 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2763 getLocationOfByte(CS.getStart()),
2764 startSpecifier, specifierLen,
2765 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00002766}
2767
Ted Kremenek826a3452010-07-16 02:11:22 +00002768bool CheckPrintfHandler::HandleAmount(
2769 const analyze_format_string::OptionalAmount &Amt,
2770 unsigned k, const char *startSpecifier,
2771 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002772
2773 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002774 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002775 unsigned argIndex = Amt.getArgIndex();
2776 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002777 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2778 << k,
2779 getLocationOfByte(Amt.getStart()),
2780 /*IsStringLocation*/true,
2781 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002782 // Don't do any more checking. We will just emit
2783 // spurious errors.
2784 return false;
2785 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002786
Ted Kremenek0d277352010-01-29 01:06:55 +00002787 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00002788 // Although not in conformance with C99, we also allow the argument to be
2789 // an 'unsigned int' as that is a reasonably safe case. GCC also
2790 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002791 CoveredArgs.set(argIndex);
2792 const Expr *Arg = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00002793 if (!Arg)
2794 return false;
2795
Ted Kremenek0d277352010-01-29 01:06:55 +00002796 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002797
Hans Wennborgf3749f42012-08-07 08:11:26 +00002798 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2799 assert(AT.isValid());
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002800
Hans Wennborgf3749f42012-08-07 08:11:26 +00002801 if (!AT.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00002802 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgf3749f42012-08-07 08:11:26 +00002803 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00002804 << T << Arg->getSourceRange(),
2805 getLocationOfByte(Amt.getStart()),
2806 /*IsStringLocation*/true,
2807 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002808 // Don't do any more checking. We will just emit
2809 // spurious errors.
2810 return false;
2811 }
2812 }
2813 }
2814 return true;
2815}
Ted Kremenek0d277352010-01-29 01:06:55 +00002816
Tom Caree4ee9662010-06-17 19:00:27 +00002817void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00002818 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002819 const analyze_printf::OptionalAmount &Amt,
2820 unsigned type,
2821 const char *startSpecifier,
2822 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002823 const analyze_printf::PrintfConversionSpecifier &CS =
2824 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00002825
Richard Trieu55733de2011-10-28 00:41:25 +00002826 FixItHint fixit =
2827 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2828 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2829 Amt.getConstantLength()))
2830 : FixItHint();
2831
2832 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2833 << type << CS.toString(),
2834 getLocationOfByte(Amt.getStart()),
2835 /*IsStringLocation*/true,
2836 getSpecifierRange(startSpecifier, specifierLen),
2837 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00002838}
2839
Ted Kremenek826a3452010-07-16 02:11:22 +00002840void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002841 const analyze_printf::OptionalFlag &flag,
2842 const char *startSpecifier,
2843 unsigned specifierLen) {
2844 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002845 const analyze_printf::PrintfConversionSpecifier &CS =
2846 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00002847 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2848 << flag.toString() << CS.toString(),
2849 getLocationOfByte(flag.getPosition()),
2850 /*IsStringLocation*/true,
2851 getSpecifierRange(startSpecifier, specifierLen),
2852 FixItHint::CreateRemoval(
2853 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002854}
2855
2856void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00002857 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002858 const analyze_printf::OptionalFlag &ignoredFlag,
2859 const analyze_printf::OptionalFlag &flag,
2860 const char *startSpecifier,
2861 unsigned specifierLen) {
2862 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00002863 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2864 << ignoredFlag.toString() << flag.toString(),
2865 getLocationOfByte(ignoredFlag.getPosition()),
2866 /*IsStringLocation*/true,
2867 getSpecifierRange(startSpecifier, specifierLen),
2868 FixItHint::CreateRemoval(
2869 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002870}
2871
Richard Smith831421f2012-06-25 20:30:08 +00002872// Determines if the specified is a C++ class or struct containing
2873// a member with the specified name and kind (e.g. a CXXMethodDecl named
2874// "c_str()").
2875template<typename MemberKind>
2876static llvm::SmallPtrSet<MemberKind*, 1>
2877CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2878 const RecordType *RT = Ty->getAs<RecordType>();
2879 llvm::SmallPtrSet<MemberKind*, 1> Results;
2880
2881 if (!RT)
2882 return Results;
2883 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2884 if (!RD)
2885 return Results;
2886
2887 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2888 Sema::LookupMemberName);
2889
2890 // We just need to include all members of the right kind turned up by the
2891 // filter, at this point.
2892 if (S.LookupQualifiedName(R, RT->getDecl()))
2893 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2894 NamedDecl *decl = (*I)->getUnderlyingDecl();
2895 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2896 Results.insert(FK);
2897 }
2898 return Results;
2899}
2900
2901// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgf3749f42012-08-07 08:11:26 +00002902// better diagnostic if so. AT is assumed to be valid.
Richard Smith831421f2012-06-25 20:30:08 +00002903// Returns true when a c_str() conversion method is found.
2904bool CheckPrintfHandler::checkForCStrMembers(
Hans Wennborgf3749f42012-08-07 08:11:26 +00002905 const analyze_printf::ArgType &AT, const Expr *E,
Richard Smith831421f2012-06-25 20:30:08 +00002906 const CharSourceRange &CSR) {
2907 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2908
2909 MethodSet Results =
2910 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2911
2912 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2913 MI != ME; ++MI) {
2914 const CXXMethodDecl *Method = *MI;
2915 if (Method->getNumParams() == 0 &&
Hans Wennborgf3749f42012-08-07 08:11:26 +00002916 AT.matchesType(S.Context, Method->getResultType())) {
Richard Smith831421f2012-06-25 20:30:08 +00002917 // FIXME: Suggest parens if the expression needs them.
2918 SourceLocation EndLoc =
2919 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2920 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2921 << "c_str()"
2922 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2923 return true;
2924 }
2925 }
2926
2927 return false;
2928}
2929
Ted Kremeneke0e53132010-01-28 23:39:18 +00002930bool
Ted Kremenek826a3452010-07-16 02:11:22 +00002931CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002932 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00002933 const char *startSpecifier,
2934 unsigned specifierLen) {
2935
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002936 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00002937 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002938 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00002939
Ted Kremenekbaa40062010-07-19 22:01:06 +00002940 if (FS.consumesDataArgument()) {
2941 if (atFirstArg) {
2942 atFirstArg = false;
2943 usesPositionalArgs = FS.usesPositionalArg();
2944 }
2945 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002946 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2947 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002948 return false;
2949 }
Ted Kremenek0d277352010-01-29 01:06:55 +00002950 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002951
Ted Kremenekefaff192010-02-27 01:41:03 +00002952 // First check if the field width, precision, and conversion specifier
2953 // have matching data arguments.
2954 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2955 startSpecifier, specifierLen)) {
2956 return false;
2957 }
2958
2959 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2960 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002961 return false;
2962 }
2963
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002964 if (!CS.consumesDataArgument()) {
2965 // FIXME: Technically specifying a precision or field width here
2966 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002967 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002968 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002969
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002970 // Consume the argument.
2971 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00002972 if (argIndex < NumDataArgs) {
2973 // The check to see if the argIndex is valid will come later.
2974 // We set the bit here because we may exit early from this
2975 // function if we encounter some other error.
2976 CoveredArgs.set(argIndex);
2977 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002978
2979 // Check for using an Objective-C specific conversion specifier
2980 // in a non-ObjC literal.
Jordan Rose50687312012-06-04 23:52:23 +00002981 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002982 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2983 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002984 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002985
Tom Caree4ee9662010-06-17 19:00:27 +00002986 // Check for invalid use of field width
2987 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002988 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00002989 startSpecifier, specifierLen);
2990 }
2991
2992 // Check for invalid use of precision
2993 if (!FS.hasValidPrecision()) {
2994 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2995 startSpecifier, specifierLen);
2996 }
2997
2998 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00002999 if (!FS.hasValidThousandsGroupingPrefix())
3000 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00003001 if (!FS.hasValidLeadingZeros())
3002 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3003 if (!FS.hasValidPlusPrefix())
3004 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00003005 if (!FS.hasValidSpacePrefix())
3006 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00003007 if (!FS.hasValidAlternativeForm())
3008 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3009 if (!FS.hasValidLeftJustified())
3010 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3011
3012 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00003013 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3014 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3015 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00003016 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3017 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3018 startSpecifier, specifierLen);
3019
3020 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003021 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00003022 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3023 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003024 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00003025 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003026 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00003027 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3028 diag::warn_format_non_standard_conversion_spec);
Tom Caree4ee9662010-06-17 19:00:27 +00003029
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003030 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3031 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3032
Ted Kremenekda51f0d2010-01-29 01:43:31 +00003033 // The remaining checks depend on the data arguments.
3034 if (HasVAListArg)
3035 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003036
Ted Kremenek666a1972010-07-26 19:45:42 +00003037 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00003038 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00003039
Jordan Rose48716662012-07-19 18:10:08 +00003040 const Expr *Arg = getDataArg(argIndex);
3041 if (!Arg)
3042 return true;
3043
3044 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith831421f2012-06-25 20:30:08 +00003045}
3046
Jordan Roseec087352012-09-05 22:56:26 +00003047static bool requiresParensToAddCast(const Expr *E) {
3048 // FIXME: We should have a general way to reason about operator
3049 // precedence and whether parens are actually needed here.
3050 // Take care of a few common cases where they aren't.
3051 const Expr *Inside = E->IgnoreImpCasts();
3052 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3053 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3054
3055 switch (Inside->getStmtClass()) {
3056 case Stmt::ArraySubscriptExprClass:
3057 case Stmt::CallExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003058 case Stmt::CharacterLiteralClass:
3059 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00003060 case Stmt::DeclRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003061 case Stmt::FloatingLiteralClass:
3062 case Stmt::IntegerLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00003063 case Stmt::MemberExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003064 case Stmt::ObjCArrayLiteralClass:
3065 case Stmt::ObjCBoolLiteralExprClass:
3066 case Stmt::ObjCBoxedExprClass:
3067 case Stmt::ObjCDictionaryLiteralClass:
3068 case Stmt::ObjCEncodeExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00003069 case Stmt::ObjCIvarRefExprClass:
3070 case Stmt::ObjCMessageExprClass:
3071 case Stmt::ObjCPropertyRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003072 case Stmt::ObjCStringLiteralClass:
3073 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00003074 case Stmt::ParenExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003075 case Stmt::StringLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00003076 case Stmt::UnaryOperatorClass:
3077 return false;
3078 default:
3079 return true;
3080 }
3081}
3082
Richard Smith831421f2012-06-25 20:30:08 +00003083bool
3084CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3085 const char *StartSpecifier,
3086 unsigned SpecifierLen,
3087 const Expr *E) {
3088 using namespace analyze_format_string;
3089 using namespace analyze_printf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003090 // Now type check the data expression that matches the
3091 // format specifier.
Hans Wennborgf3749f42012-08-07 08:11:26 +00003092 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3093 ObjCContext);
Jordan Rose614a8652012-09-05 22:56:19 +00003094 if (!AT.isValid())
3095 return true;
Jordan Roseec087352012-09-05 22:56:26 +00003096
Jordan Rose448ac3e2012-12-05 18:44:40 +00003097 QualType ExprTy = E->getType();
Ted Kremenek02be9682013-04-10 06:26:26 +00003098 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3099 ExprTy = TET->getUnderlyingExpr()->getType();
3100 }
3101
Jordan Rose448ac3e2012-12-05 18:44:40 +00003102 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00003103 return true;
Jordan Roseee0259d2012-06-04 22:48:57 +00003104
Jordan Rose614a8652012-09-05 22:56:19 +00003105 // Look through argument promotions for our error message's reported type.
3106 // This includes the integral and floating promotions, but excludes array
3107 // and function pointer decay; seeing that an argument intended to be a
3108 // string has type 'char [6]' is probably more confusing than 'char *'.
3109 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3110 if (ICE->getCastKind() == CK_IntegralCast ||
3111 ICE->getCastKind() == CK_FloatingCast) {
3112 E = ICE->getSubExpr();
Jordan Rose448ac3e2012-12-05 18:44:40 +00003113 ExprTy = E->getType();
Jordan Rose614a8652012-09-05 22:56:19 +00003114
3115 // Check if we didn't match because of an implicit cast from a 'char'
3116 // or 'short' to an 'int'. This is done because printf is a varargs
3117 // function.
3118 if (ICE->getType() == S.Context.IntTy ||
3119 ICE->getType() == S.Context.UnsignedIntTy) {
3120 // All further checking is done on the subexpression.
Jordan Rose448ac3e2012-12-05 18:44:40 +00003121 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00003122 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00003123 }
Jordan Roseee0259d2012-06-04 22:48:57 +00003124 }
Jordan Rose448ac3e2012-12-05 18:44:40 +00003125 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3126 // Special case for 'a', which has type 'int' in C.
3127 // Note, however, that we do /not/ want to treat multibyte constants like
3128 // 'MooV' as characters! This form is deprecated but still exists.
3129 if (ExprTy == S.Context.IntTy)
3130 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3131 ExprTy = S.Context.CharTy;
Jordan Rose614a8652012-09-05 22:56:19 +00003132 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003133
Jordan Rose2cd34402012-12-05 18:44:49 +00003134 // %C in an Objective-C context prints a unichar, not a wchar_t.
3135 // If the argument is an integer of some kind, believe the %C and suggest
3136 // a cast instead of changing the conversion specifier.
Jordan Rose448ac3e2012-12-05 18:44:40 +00003137 QualType IntendedTy = ExprTy;
Jordan Rose2cd34402012-12-05 18:44:49 +00003138 if (ObjCContext &&
3139 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3140 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3141 !ExprTy->isCharType()) {
3142 // 'unichar' is defined as a typedef of unsigned short, but we should
3143 // prefer using the typedef if it is visible.
3144 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenek656465d2013-10-15 05:25:17 +00003145
3146 // While we are here, check if the value is an IntegerLiteral that happens
3147 // to be within the valid range.
3148 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3149 const llvm::APInt &V = IL->getValue();
3150 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3151 return true;
3152 }
3153
Jordan Rose2cd34402012-12-05 18:44:49 +00003154 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3155 Sema::LookupOrdinaryName);
3156 if (S.LookupName(Result, S.getCurScope())) {
3157 NamedDecl *ND = Result.getFoundDecl();
3158 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3159 if (TD->getUnderlyingType() == IntendedTy)
3160 IntendedTy = S.Context.getTypedefType(TD);
3161 }
3162 }
3163 }
3164
3165 // Special-case some of Darwin's platform-independence types by suggesting
3166 // casts to primitive types that are known to be large enough.
3167 bool ShouldNotPrintDirectly = false;
Jordan Roseec087352012-09-05 22:56:26 +00003168 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Ted Kremenek6edb0292013-03-25 22:28:37 +00003169 // Use a 'while' to peel off layers of typedefs.
3170 QualType TyTy = IntendedTy;
3171 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
Jordan Roseec087352012-09-05 22:56:26 +00003172 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose2cd34402012-12-05 18:44:49 +00003173 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseec087352012-09-05 22:56:26 +00003174 .Case("NSInteger", S.Context.LongTy)
3175 .Case("NSUInteger", S.Context.UnsignedLongTy)
3176 .Case("SInt32", S.Context.IntTy)
3177 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose2cd34402012-12-05 18:44:49 +00003178 .Default(QualType());
3179
3180 if (!CastTy.isNull()) {
3181 ShouldNotPrintDirectly = true;
3182 IntendedTy = CastTy;
Ted Kremenek6edb0292013-03-25 22:28:37 +00003183 break;
Jordan Rose2cd34402012-12-05 18:44:49 +00003184 }
Ted Kremenek6edb0292013-03-25 22:28:37 +00003185 TyTy = UserTy->desugar();
Jordan Roseec087352012-09-05 22:56:26 +00003186 }
3187 }
3188
Jordan Rose614a8652012-09-05 22:56:19 +00003189 // We may be able to offer a FixItHint if it is a supported type.
3190 PrintfSpecifier fixedFS = FS;
Jordan Roseec087352012-09-05 22:56:26 +00003191 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose614a8652012-09-05 22:56:19 +00003192 S.Context, ObjCContext);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003193
Jordan Rose614a8652012-09-05 22:56:19 +00003194 if (success) {
3195 // Get the fix string from the fixed format specifier
3196 SmallString<16> buf;
3197 llvm::raw_svector_ostream os(buf);
3198 fixedFS.toString(os);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003199
Jordan Roseec087352012-09-05 22:56:26 +00003200 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3201
Jordan Rose2cd34402012-12-05 18:44:49 +00003202 if (IntendedTy == ExprTy) {
3203 // In this case, the specifier is wrong and should be changed to match
3204 // the argument.
3205 EmitFormatDiagnostic(
3206 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3207 << AT.getRepresentativeTypeName(S.Context) << IntendedTy
3208 << E->getSourceRange(),
3209 E->getLocStart(),
3210 /*IsStringLocation*/false,
3211 SpecRange,
3212 FixItHint::CreateReplacement(SpecRange, os.str()));
3213
3214 } else {
Jordan Roseec087352012-09-05 22:56:26 +00003215 // The canonical type for formatting this value is different from the
3216 // actual type of the expression. (This occurs, for example, with Darwin's
3217 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3218 // should be printed as 'long' for 64-bit compatibility.)
3219 // Rather than emitting a normal format/argument mismatch, we want to
3220 // add a cast to the recommended type (and correct the format string
3221 // if necessary).
3222 SmallString<16> CastBuf;
3223 llvm::raw_svector_ostream CastFix(CastBuf);
3224 CastFix << "(";
3225 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3226 CastFix << ")";
3227
3228 SmallVector<FixItHint,4> Hints;
3229 if (!AT.matchesType(S.Context, IntendedTy))
3230 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3231
3232 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3233 // If there's already a cast present, just replace it.
3234 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3235 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3236
3237 } else if (!requiresParensToAddCast(E)) {
3238 // If the expression has high enough precedence,
3239 // just write the C-style cast.
3240 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3241 CastFix.str()));
3242 } else {
3243 // Otherwise, add parens around the expression as well as the cast.
3244 CastFix << "(";
3245 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3246 CastFix.str()));
3247
3248 SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
3249 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3250 }
3251
Jordan Rose2cd34402012-12-05 18:44:49 +00003252 if (ShouldNotPrintDirectly) {
3253 // The expression has a type that should not be printed directly.
3254 // We extract the name from the typedef because we don't want to show
3255 // the underlying type in the diagnostic.
3256 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseec087352012-09-05 22:56:26 +00003257
Jordan Rose2cd34402012-12-05 18:44:49 +00003258 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
3259 << Name << IntendedTy
3260 << E->getSourceRange(),
3261 E->getLocStart(), /*IsStringLocation=*/false,
3262 SpecRange, Hints);
3263 } else {
3264 // In this case, the expression could be printed using a different
3265 // specifier, but we've decided that the specifier is probably correct
3266 // and we should cast instead. Just use the normal warning message.
3267 EmitFormatDiagnostic(
3268 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3269 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3270 << E->getSourceRange(),
3271 E->getLocStart(), /*IsStringLocation*/false,
3272 SpecRange, Hints);
3273 }
Jordan Roseec087352012-09-05 22:56:26 +00003274 }
Jordan Rose614a8652012-09-05 22:56:19 +00003275 } else {
3276 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3277 SpecifierLen);
3278 // Since the warning for passing non-POD types to variadic functions
3279 // was deferred until now, we emit a warning for non-POD
3280 // arguments here.
Richard Smith0e218972013-08-05 18:49:43 +00003281 switch (S.isValidVarArgType(ExprTy)) {
3282 case Sema::VAK_Valid:
3283 case Sema::VAK_ValidInCXX11:
Jordan Rose614a8652012-09-05 22:56:19 +00003284 EmitFormatDiagnostic(
Richard Smith0e218972013-08-05 18:49:43 +00003285 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3286 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3287 << CSR
3288 << E->getSourceRange(),
3289 E->getLocStart(), /*IsStringLocation*/false, CSR);
3290 break;
3291
3292 case Sema::VAK_Undefined:
3293 EmitFormatDiagnostic(
3294 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith80ad52f2013-01-02 11:42:31 +00003295 << S.getLangOpts().CPlusPlus11
Jordan Rose448ac3e2012-12-05 18:44:40 +00003296 << ExprTy
Jordan Rose614a8652012-09-05 22:56:19 +00003297 << CallType
3298 << AT.getRepresentativeTypeName(S.Context)
3299 << CSR
3300 << E->getSourceRange(),
3301 E->getLocStart(), /*IsStringLocation*/false, CSR);
Jordan Rose614a8652012-09-05 22:56:19 +00003302 checkForCStrMembers(AT, E, CSR);
Richard Smith0e218972013-08-05 18:49:43 +00003303 break;
3304
3305 case Sema::VAK_Invalid:
3306 if (ExprTy->isObjCObjectType())
3307 EmitFormatDiagnostic(
3308 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3309 << S.getLangOpts().CPlusPlus11
3310 << ExprTy
3311 << CallType
3312 << AT.getRepresentativeTypeName(S.Context)
3313 << CSR
3314 << E->getSourceRange(),
3315 E->getLocStart(), /*IsStringLocation*/false, CSR);
3316 else
3317 // FIXME: If this is an initializer list, suggest removing the braces
3318 // or inserting a cast to the target type.
3319 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3320 << isa<InitListExpr>(E) << ExprTy << CallType
3321 << AT.getRepresentativeTypeName(S.Context)
3322 << E->getSourceRange();
3323 break;
3324 }
3325
3326 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3327 "format string specifier index out of range");
3328 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003329 }
3330
Ted Kremeneke0e53132010-01-28 23:39:18 +00003331 return true;
3332}
3333
Ted Kremenek826a3452010-07-16 02:11:22 +00003334//===--- CHECK: Scanf format string checking ------------------------------===//
3335
3336namespace {
3337class CheckScanfHandler : public CheckFormatHandler {
3338public:
3339 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3340 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003341 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003342 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003343 unsigned formatIdx, bool inFunctionCall,
Richard Smith0e218972013-08-05 18:49:43 +00003344 Sema::VariadicCallType CallType,
3345 llvm::SmallBitVector &CheckedVarArgs)
3346 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3347 numDataArgs, beg, hasVAListArg,
3348 Args, formatIdx, inFunctionCall, CallType,
3349 CheckedVarArgs)
Jordan Roseddcfbc92012-07-19 18:10:23 +00003350 {}
Ted Kremenek826a3452010-07-16 02:11:22 +00003351
3352 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3353 const char *startSpecifier,
3354 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003355
3356 bool HandleInvalidScanfConversionSpecifier(
3357 const analyze_scanf::ScanfSpecifier &FS,
3358 const char *startSpecifier,
3359 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00003360
3361 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00003362};
Ted Kremenek07d161f2010-01-29 01:50:07 +00003363}
Ted Kremeneke0e53132010-01-28 23:39:18 +00003364
Ted Kremenekb7c21012010-07-16 18:28:03 +00003365void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3366 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00003367 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3368 getLocationOfByte(end), /*IsStringLocation*/true,
3369 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00003370}
3371
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003372bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3373 const analyze_scanf::ScanfSpecifier &FS,
3374 const char *startSpecifier,
3375 unsigned specifierLen) {
3376
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003377 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003378 FS.getConversionSpecifier();
3379
3380 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3381 getLocationOfByte(CS.getStart()),
3382 startSpecifier, specifierLen,
3383 CS.getStart(), CS.getLength());
3384}
3385
Ted Kremenek826a3452010-07-16 02:11:22 +00003386bool CheckScanfHandler::HandleScanfSpecifier(
3387 const analyze_scanf::ScanfSpecifier &FS,
3388 const char *startSpecifier,
3389 unsigned specifierLen) {
3390
3391 using namespace analyze_scanf;
3392 using namespace analyze_format_string;
3393
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003394 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00003395
Ted Kremenekbaa40062010-07-19 22:01:06 +00003396 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3397 // be used to decide if we are using positional arguments consistently.
3398 if (FS.consumesDataArgument()) {
3399 if (atFirstArg) {
3400 atFirstArg = false;
3401 usesPositionalArgs = FS.usesPositionalArg();
3402 }
3403 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003404 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3405 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00003406 return false;
3407 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003408 }
3409
3410 // Check if the field with is non-zero.
3411 const OptionalAmount &Amt = FS.getFieldWidth();
3412 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3413 if (Amt.getConstantAmount() == 0) {
3414 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3415 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00003416 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3417 getLocationOfByte(Amt.getStart()),
3418 /*IsStringLocation*/true, R,
3419 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00003420 }
3421 }
3422
3423 if (!FS.consumesDataArgument()) {
3424 // FIXME: Technically specifying a precision or field width here
3425 // makes no sense. Worth issuing a warning at some point.
3426 return true;
3427 }
3428
3429 // Consume the argument.
3430 unsigned argIndex = FS.getArgIndex();
3431 if (argIndex < NumDataArgs) {
3432 // The check to see if the argIndex is valid will come later.
3433 // We set the bit here because we may exit early from this
3434 // function if we encounter some other error.
3435 CoveredArgs.set(argIndex);
3436 }
3437
Ted Kremenek1e51c202010-07-20 20:04:47 +00003438 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003439 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00003440 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3441 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003442 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00003443 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003444 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00003445 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3446 diag::warn_format_non_standard_conversion_spec);
Hans Wennborg76517422012-02-22 10:17:01 +00003447
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003448 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3449 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3450
Ted Kremenek826a3452010-07-16 02:11:22 +00003451 // The remaining checks depend on the data arguments.
3452 if (HasVAListArg)
3453 return true;
3454
Ted Kremenek666a1972010-07-26 19:45:42 +00003455 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00003456 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00003457
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003458 // Check that the argument type matches the format specifier.
3459 const Expr *Ex = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00003460 if (!Ex)
3461 return true;
3462
Hans Wennborg58e1e542012-08-07 08:59:46 +00003463 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3464 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003465 ScanfSpecifier fixedFS = FS;
David Blaikie4e4d0842012-03-11 07:00:24 +00003466 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgbe6126a2012-02-15 09:59:46 +00003467 S.Context);
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003468
3469 if (success) {
3470 // Get the fix string from the fixed format specifier.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003471 SmallString<128> buf;
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003472 llvm::raw_svector_ostream os(buf);
3473 fixedFS.toString(os);
3474
3475 EmitFormatDiagnostic(
3476 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003477 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003478 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003479 Ex->getLocStart(),
3480 /*IsStringLocation*/false,
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003481 getSpecifierRange(startSpecifier, specifierLen),
3482 FixItHint::CreateReplacement(
3483 getSpecifierRange(startSpecifier, specifierLen),
3484 os.str()));
3485 } else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003486 EmitFormatDiagnostic(
3487 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003488 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003489 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003490 Ex->getLocStart(),
3491 /*IsStringLocation*/false,
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003492 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003493 }
3494 }
3495
Ted Kremenek826a3452010-07-16 02:11:22 +00003496 return true;
3497}
3498
3499void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00003500 const Expr *OrigFormatExpr,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003501 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003502 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003503 unsigned firstDataArg, FormatStringType Type,
Richard Smith0e218972013-08-05 18:49:43 +00003504 bool inFunctionCall, VariadicCallType CallType,
3505 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003506
Ted Kremeneke0e53132010-01-28 23:39:18 +00003507 // CHECK: is the format string a wide literal?
Richard Smithdf9ef1b2012-06-13 05:37:23 +00003508 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003509 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003510 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003511 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3512 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003513 return;
3514 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003515
Ted Kremeneke0e53132010-01-28 23:39:18 +00003516 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00003517 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00003518 const char *Str = StrRef.data();
3519 unsigned StrLen = StrRef.size();
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003520 const unsigned numDataArgs = Args.size() - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00003521
Ted Kremeneke0e53132010-01-28 23:39:18 +00003522 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00003523 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00003524 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003525 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003526 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3527 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003528 return;
3529 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003530
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003531 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003532 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003533 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003534 Str, HasVAListArg, Args, format_idx,
Richard Smith0e218972013-08-05 18:49:43 +00003535 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek826a3452010-07-16 02:11:22 +00003536
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003537 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003538 getLangOpts(),
3539 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003540 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003541 } else if (Type == FST_Scanf) {
Jordan Rose50687312012-06-04 23:52:23 +00003542 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003543 Str, HasVAListArg, Args, format_idx,
Richard Smith0e218972013-08-05 18:49:43 +00003544 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek826a3452010-07-16 02:11:22 +00003545
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003546 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003547 getLangOpts(),
3548 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003549 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003550 } // TODO: handle other formats
Ted Kremenekce7024e2010-01-28 01:18:22 +00003551}
3552
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003553//===--- CHECK: Standard memory functions ---------------------------------===//
3554
Douglas Gregor2a053a32011-05-03 20:05:22 +00003555/// \brief Determine whether the given type is a dynamic class type (e.g.,
3556/// whether it has a vtable).
3557static bool isDynamicClassType(QualType T) {
3558 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3559 if (CXXRecordDecl *Definition = Record->getDefinition())
3560 if (Definition->isDynamicClass())
3561 return true;
3562
3563 return false;
3564}
3565
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003566/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00003567/// otherwise returns NULL.
3568static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00003569 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00003570 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3571 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
3572 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003573
Chandler Carruth000d4282011-06-16 09:09:40 +00003574 return 0;
3575}
3576
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003577/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00003578static QualType getSizeOfArgType(const Expr* E) {
3579 if (const UnaryExprOrTypeTraitExpr *SizeOf =
3580 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3581 if (SizeOf->getKind() == clang::UETT_SizeOf)
3582 return SizeOf->getTypeOfArgument();
3583
3584 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00003585}
3586
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003587/// \brief Check for dangerous or invalid arguments to memset().
3588///
Chandler Carruth929f0132011-06-03 06:23:57 +00003589/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003590/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3591/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003592///
3593/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003594void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00003595 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003596 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00003597 assert(BId != 0);
3598
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003599 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00003600 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00003601 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00003602 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003603 return;
3604
Anna Zaks0a151a12012-01-17 00:37:07 +00003605 unsigned LastArg = (BId == Builtin::BImemset ||
3606 BId == Builtin::BIstrndup ? 1 : 2);
3607 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00003608 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00003609
3610 // We have special checking when the length is a sizeof expression.
3611 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
3612 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
3613 llvm::FoldingSetNodeID SizeOfArgID;
3614
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003615 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
3616 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003617 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003618
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003619 QualType DestTy = Dest->getType();
3620 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
3621 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00003622
Chandler Carruth000d4282011-06-16 09:09:40 +00003623 // Never warn about void type pointers. This can be used to suppress
3624 // false positives.
3625 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003626 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003627
Chandler Carruth000d4282011-06-16 09:09:40 +00003628 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
3629 // actually comparing the expressions for equality. Because computing the
3630 // expression IDs can be expensive, we only do this if the diagnostic is
3631 // enabled.
3632 if (SizeOfArg &&
3633 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
3634 SizeOfArg->getExprLoc())) {
3635 // We only compute IDs for expressions if the warning is enabled, and
3636 // cache the sizeof arg's ID.
3637 if (SizeOfArgID == llvm::FoldingSetNodeID())
3638 SizeOfArg->Profile(SizeOfArgID, Context, true);
3639 llvm::FoldingSetNodeID DestID;
3640 Dest->Profile(DestID, Context, true);
3641 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00003642 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
3643 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00003644 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003645 StringRef ReadableName = FnName->getName();
3646
Chandler Carruth000d4282011-06-16 09:09:40 +00003647 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaks90c78322012-05-30 23:14:52 +00003648 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth000d4282011-06-16 09:09:40 +00003649 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian7adf4172013-01-30 01:12:44 +00003650 if (!PointeeTy->isIncompleteType() &&
3651 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth000d4282011-06-16 09:09:40 +00003652 ActionIdx = 2; // If the pointee's size is sizeof(char),
3653 // suggest an explicit length.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003654
3655 // If the function is defined as a builtin macro, do not show macro
3656 // expansion.
3657 SourceLocation SL = SizeOfArg->getExprLoc();
3658 SourceRange DSR = Dest->getSourceRange();
3659 SourceRange SSR = SizeOfArg->getSourceRange();
3660 SourceManager &SM = PP.getSourceManager();
3661
3662 if (SM.isMacroArgExpansion(SL)) {
3663 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
3664 SL = SM.getSpellingLoc(SL);
3665 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
3666 SM.getSpellingLoc(DSR.getEnd()));
3667 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
3668 SM.getSpellingLoc(SSR.getEnd()));
3669 }
3670
Anna Zaks90c78322012-05-30 23:14:52 +00003671 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth000d4282011-06-16 09:09:40 +00003672 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks6fcb3722012-05-30 00:34:21 +00003673 << ReadableName
Anna Zaks90c78322012-05-30 23:14:52 +00003674 << PointeeTy
3675 << DestTy
Anna Zaks6fcb3722012-05-30 00:34:21 +00003676 << DSR
Anna Zaks90c78322012-05-30 23:14:52 +00003677 << SSR);
3678 DiagRuntimeBehavior(SL, SizeOfArg,
3679 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
3680 << ActionIdx
3681 << SSR);
3682
Chandler Carruth000d4282011-06-16 09:09:40 +00003683 break;
3684 }
3685 }
3686
3687 // Also check for cases where the sizeof argument is the exact same
3688 // type as the memory argument, and where it points to a user-defined
3689 // record type.
3690 if (SizeOfArgTy != QualType()) {
3691 if (PointeeTy->isRecordType() &&
3692 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
3693 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
3694 PDiag(diag::warn_sizeof_pointer_type_memaccess)
3695 << FnName << SizeOfArgTy << ArgIdx
3696 << PointeeTy << Dest->getSourceRange()
3697 << LenExpr->getSourceRange());
3698 break;
3699 }
Nico Webere4a1c642011-06-14 16:14:58 +00003700 }
3701
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003702 // Always complain about dynamic classes.
Anna Zaks0a151a12012-01-17 00:37:07 +00003703 if (isDynamicClassType(PointeeTy)) {
3704
3705 unsigned OperationType = 0;
3706 // "overwritten" if we're warning about the destination for any call
3707 // but memcmp; otherwise a verb appropriate to the call.
3708 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
3709 if (BId == Builtin::BImemcpy)
3710 OperationType = 1;
3711 else if(BId == Builtin::BImemmove)
3712 OperationType = 2;
3713 else if (BId == Builtin::BImemcmp)
3714 OperationType = 3;
3715 }
3716
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003717 DiagRuntimeBehavior(
3718 Dest->getExprLoc(), Dest,
3719 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks0a151a12012-01-17 00:37:07 +00003720 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaksd9b859a2012-01-13 21:52:01 +00003721 << FnName << PointeeTy
Anna Zaks0a151a12012-01-17 00:37:07 +00003722 << OperationType
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003723 << Call->getCallee()->getSourceRange());
Anna Zaks0a151a12012-01-17 00:37:07 +00003724 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
3725 BId != Builtin::BImemset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003726 DiagRuntimeBehavior(
3727 Dest->getExprLoc(), Dest,
3728 PDiag(diag::warn_arc_object_memaccess)
3729 << ArgIdx << FnName << PointeeTy
3730 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00003731 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003732 continue;
John McCallf85e1932011-06-15 23:02:42 +00003733
3734 DiagRuntimeBehavior(
3735 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00003736 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003737 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
3738 break;
3739 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003740 }
3741}
3742
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003743// A little helper routine: ignore addition and subtraction of integer literals.
3744// This intentionally does not ignore all integer constant expressions because
3745// we don't want to remove sizeof().
3746static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
3747 Ex = Ex->IgnoreParenCasts();
3748
3749 for (;;) {
3750 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
3751 if (!BO || !BO->isAdditiveOp())
3752 break;
3753
3754 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
3755 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
3756
3757 if (isa<IntegerLiteral>(RHS))
3758 Ex = LHS;
3759 else if (isa<IntegerLiteral>(LHS))
3760 Ex = RHS;
3761 else
3762 break;
3763 }
3764
3765 return Ex;
3766}
3767
Anna Zaks0f38ace2012-08-08 21:42:23 +00003768static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
3769 ASTContext &Context) {
3770 // Only handle constant-sized or VLAs, but not flexible members.
3771 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
3772 // Only issue the FIXIT for arrays of size > 1.
3773 if (CAT->getSize().getSExtValue() <= 1)
3774 return false;
3775 } else if (!Ty->isVariableArrayType()) {
3776 return false;
3777 }
3778 return true;
3779}
3780
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003781// Warn if the user has made the 'size' argument to strlcpy or strlcat
3782// be the size of the source, instead of the destination.
3783void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
3784 IdentifierInfo *FnName) {
3785
3786 // Don't crash if the user has the wrong number of arguments
3787 if (Call->getNumArgs() != 3)
3788 return;
3789
3790 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
3791 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
3792 const Expr *CompareWithSrc = NULL;
3793
3794 // Look for 'strlcpy(dst, x, sizeof(x))'
3795 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
3796 CompareWithSrc = Ex;
3797 else {
3798 // Look for 'strlcpy(dst, x, strlen(x))'
3799 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smith180f4792011-11-10 06:34:14 +00003800 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003801 && SizeCall->getNumArgs() == 1)
3802 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
3803 }
3804 }
3805
3806 if (!CompareWithSrc)
3807 return;
3808
3809 // Determine if the argument to sizeof/strlen is equal to the source
3810 // argument. In principle there's all kinds of things you could do
3811 // here, for instance creating an == expression and evaluating it with
3812 // EvaluateAsBooleanCondition, but this uses a more direct technique:
3813 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
3814 if (!SrcArgDRE)
3815 return;
3816
3817 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
3818 if (!CompareWithSrcDRE ||
3819 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
3820 return;
3821
3822 const Expr *OriginalSizeArg = Call->getArg(2);
3823 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
3824 << OriginalSizeArg->getSourceRange() << FnName;
3825
3826 // Output a FIXIT hint if the destination is an array (rather than a
3827 // pointer to an array). This could be enhanced to handle some
3828 // pointers if we know the actual size, like if DstArg is 'array+2'
3829 // we could say 'sizeof(array)-2'.
3830 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks0f38ace2012-08-08 21:42:23 +00003831 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek8f746222011-08-18 22:48:41 +00003832 return;
Ted Kremenek8f746222011-08-18 22:48:41 +00003833
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003834 SmallString<128> sizeString;
Ted Kremenek8f746222011-08-18 22:48:41 +00003835 llvm::raw_svector_ostream OS(sizeString);
3836 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003837 DstArg->printPretty(OS, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00003838 OS << ")";
3839
3840 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
3841 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
3842 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003843}
3844
Anna Zaksc36bedc2012-02-01 19:08:57 +00003845/// Check if two expressions refer to the same declaration.
3846static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
3847 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
3848 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
3849 return D1->getDecl() == D2->getDecl();
3850 return false;
3851}
3852
3853static const Expr *getStrlenExprArg(const Expr *E) {
3854 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
3855 const FunctionDecl *FD = CE->getDirectCallee();
3856 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
3857 return 0;
3858 return CE->getArg(0)->IgnoreParenCasts();
3859 }
3860 return 0;
3861}
3862
3863// Warn on anti-patterns as the 'size' argument to strncat.
3864// The correct size argument should look like following:
3865// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3866void Sema::CheckStrncatArguments(const CallExpr *CE,
3867 IdentifierInfo *FnName) {
3868 // Don't crash if the user has the wrong number of arguments.
3869 if (CE->getNumArgs() < 3)
3870 return;
3871 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
3872 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
3873 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
3874
3875 // Identify common expressions, which are wrongly used as the size argument
3876 // to strncat and may lead to buffer overflows.
3877 unsigned PatternType = 0;
3878 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
3879 // - sizeof(dst)
3880 if (referToTheSameDecl(SizeOfArg, DstArg))
3881 PatternType = 1;
3882 // - sizeof(src)
3883 else if (referToTheSameDecl(SizeOfArg, SrcArg))
3884 PatternType = 2;
3885 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
3886 if (BE->getOpcode() == BO_Sub) {
3887 const Expr *L = BE->getLHS()->IgnoreParenCasts();
3888 const Expr *R = BE->getRHS()->IgnoreParenCasts();
3889 // - sizeof(dst) - strlen(dst)
3890 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
3891 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
3892 PatternType = 1;
3893 // - sizeof(src) - (anything)
3894 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
3895 PatternType = 2;
3896 }
3897 }
3898
3899 if (PatternType == 0)
3900 return;
3901
Anna Zaksafdb0412012-02-03 01:27:37 +00003902 // Generate the diagnostic.
3903 SourceLocation SL = LenArg->getLocStart();
3904 SourceRange SR = LenArg->getSourceRange();
3905 SourceManager &SM = PP.getSourceManager();
3906
3907 // If the function is defined as a builtin macro, do not show macro expansion.
3908 if (SM.isMacroArgExpansion(SL)) {
3909 SL = SM.getSpellingLoc(SL);
3910 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
3911 SM.getSpellingLoc(SR.getEnd()));
3912 }
3913
Anna Zaks0f38ace2012-08-08 21:42:23 +00003914 // Check if the destination is an array (rather than a pointer to an array).
3915 QualType DstTy = DstArg->getType();
3916 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
3917 Context);
3918 if (!isKnownSizeArray) {
3919 if (PatternType == 1)
3920 Diag(SL, diag::warn_strncat_wrong_size) << SR;
3921 else
3922 Diag(SL, diag::warn_strncat_src_size) << SR;
3923 return;
3924 }
3925
Anna Zaksc36bedc2012-02-01 19:08:57 +00003926 if (PatternType == 1)
Anna Zaksafdb0412012-02-03 01:27:37 +00003927 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003928 else
Anna Zaksafdb0412012-02-03 01:27:37 +00003929 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003930
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003931 SmallString<128> sizeString;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003932 llvm::raw_svector_ostream OS(sizeString);
3933 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003934 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003935 OS << ") - ";
3936 OS << "strlen(";
Richard Smithd1420c62012-08-16 03:56:14 +00003937 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003938 OS << ") - 1";
3939
Anna Zaksafdb0412012-02-03 01:27:37 +00003940 Diag(SL, diag::note_strncat_wrong_size)
3941 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003942}
3943
Ted Kremenek06de2762007-08-17 16:46:58 +00003944//===--- CHECK: Return Address of Stack Variable --------------------------===//
3945
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003946static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3947 Decl *ParentDecl);
3948static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
3949 Decl *ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003950
3951/// CheckReturnStackAddr - Check if a return statement returns the address
3952/// of a stack variable.
3953void
3954Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
3955 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00003956
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003957 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003958 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003959
3960 // Perform checking for returned stack addresses, local blocks,
3961 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00003962 if (lhsType->isPointerType() ||
David Blaikie4e4d0842012-03-11 07:00:24 +00003963 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003964 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003965 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003966 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003967 }
3968
3969 if (stackE == 0)
3970 return; // Nothing suspicious was found.
3971
3972 SourceLocation diagLoc;
3973 SourceRange diagRange;
3974 if (refVars.empty()) {
3975 diagLoc = stackE->getLocStart();
3976 diagRange = stackE->getSourceRange();
3977 } else {
3978 // We followed through a reference variable. 'stackE' contains the
3979 // problematic expression but we will warn at the return statement pointing
3980 // at the reference variable. We will later display the "trail" of
3981 // reference variables using notes.
3982 diagLoc = refVars[0]->getLocStart();
3983 diagRange = refVars[0]->getSourceRange();
3984 }
3985
3986 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
3987 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
3988 : diag::warn_ret_stack_addr)
3989 << DR->getDecl()->getDeclName() << diagRange;
3990 } else if (isa<BlockExpr>(stackE)) { // local block.
3991 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
3992 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
3993 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
3994 } else { // local temporary.
3995 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
3996 : diag::warn_ret_local_temp_addr)
3997 << diagRange;
3998 }
3999
4000 // Display the "trail" of reference variables that we followed until we
4001 // found the problematic expression using notes.
4002 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4003 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4004 // If this var binds to another reference var, show the range of the next
4005 // var, otherwise the var binds to the problematic expression, in which case
4006 // show the range of the expression.
4007 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4008 : stackE->getSourceRange();
4009 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4010 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00004011 }
4012}
4013
4014/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4015/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004016/// to a location on the stack, a local block, an address of a label, or a
4017/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00004018/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004019/// encounter a subexpression that (1) clearly does not lead to one of the
4020/// above problematic expressions (2) is something we cannot determine leads to
4021/// a problematic expression based on such local checking.
4022///
4023/// Both EvalAddr and EvalVal follow through reference variables to evaluate
4024/// the expression that they point to. Such variables are added to the
4025/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00004026///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00004027/// EvalAddr processes expressions that are pointers that are used as
4028/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004029/// At the base case of the recursion is a check for the above problematic
4030/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00004031///
4032/// This implementation handles:
4033///
4034/// * pointer-to-pointer casts
4035/// * implicit conversions from array references to pointers
4036/// * taking the address of fields
4037/// * arbitrary interplay between "&" and "*" operators
4038/// * pointer arithmetic from an address of a stack variable
4039/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004040static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4041 Decl *ParentDecl) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004042 if (E->isTypeDependent())
Craig Topperb61c2942013-08-02 05:10:31 +00004043 return NULL;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004044
Ted Kremenek06de2762007-08-17 16:46:58 +00004045 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00004046 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00004047 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004048 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004049 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00004050
Peter Collingbournef111d932011-04-15 00:35:48 +00004051 E = E->IgnoreParens();
4052
Ted Kremenek06de2762007-08-17 16:46:58 +00004053 // Our "symbolic interpreter" is just a dispatch off the currently
4054 // viewed AST node. We then recursively traverse the AST by calling
4055 // EvalAddr and EvalVal appropriately.
4056 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004057 case Stmt::DeclRefExprClass: {
4058 DeclRefExpr *DR = cast<DeclRefExpr>(E);
4059
4060 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
4061 // If this is a reference variable, follow through to the expression that
4062 // it points to.
4063 if (V->hasLocalStorage() &&
4064 V->getType()->isReferenceType() && V->hasInit()) {
4065 // Add the reference variable to the "trail".
4066 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004067 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004068 }
4069
4070 return NULL;
4071 }
Ted Kremenek06de2762007-08-17 16:46:58 +00004072
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004073 case Stmt::UnaryOperatorClass: {
4074 // The only unary operator that make sense to handle here
4075 // is AddrOf. All others don't make sense as pointers.
4076 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004077
John McCall2de56d12010-08-25 11:45:40 +00004078 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004079 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004080 else
Ted Kremenek06de2762007-08-17 16:46:58 +00004081 return NULL;
4082 }
Mike Stump1eb44332009-09-09 15:08:12 +00004083
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004084 case Stmt::BinaryOperatorClass: {
4085 // Handle pointer arithmetic. All other binary operators are not valid
4086 // in this context.
4087 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00004088 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00004089
John McCall2de56d12010-08-25 11:45:40 +00004090 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004091 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00004092
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004093 Expr *Base = B->getLHS();
4094
4095 // Determine which argument is the real pointer base. It could be
4096 // the RHS argument instead of the LHS.
4097 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00004098
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004099 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004100 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004101 }
Steve Naroff61f40a22008-09-10 19:17:48 +00004102
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004103 // For conditional operators we need to see if either the LHS or RHS are
4104 // valid DeclRefExpr*s. If one of them is valid, we return it.
4105 case Stmt::ConditionalOperatorClass: {
4106 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004107
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004108 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00004109 if (Expr *lhsExpr = C->getLHS()) {
4110 // In C++, we can have a throw-expression, which has 'void' type.
4111 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004112 if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00004113 return LHS;
4114 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004115
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00004116 // In C++, we can have a throw-expression, which has 'void' type.
4117 if (C->getRHS()->getType()->isVoidType())
4118 return NULL;
4119
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004120 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004121 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004122
4123 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00004124 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004125 return E; // local block.
4126 return NULL;
4127
4128 case Stmt::AddrLabelExprClass:
4129 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00004130
John McCall80ee6e82011-11-10 05:35:25 +00004131 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004132 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4133 ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00004134
Ted Kremenek54b52742008-08-07 00:49:01 +00004135 // For casts, we need to handle conversions from arrays to
4136 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00004137 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00004138 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00004139 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8b9414e2012-02-23 23:04:32 +00004140 case Stmt::ObjCBridgedCastExprClass:
Mike Stump1eb44332009-09-09 15:08:12 +00004141 case Stmt::CXXStaticCastExprClass:
4142 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00004143 case Stmt::CXXConstCastExprClass:
4144 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8b9414e2012-02-23 23:04:32 +00004145 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4146 switch (cast<CastExpr>(E)->getCastKind()) {
4147 case CK_BitCast:
4148 case CK_LValueToRValue:
4149 case CK_NoOp:
4150 case CK_BaseToDerived:
4151 case CK_DerivedToBase:
4152 case CK_UncheckedDerivedToBase:
4153 case CK_Dynamic:
4154 case CK_CPointerToObjCPointerCast:
4155 case CK_BlockPointerToObjCPointerCast:
4156 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004157 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00004158
4159 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004160 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00004161
4162 default:
4163 return 0;
4164 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004165 }
Mike Stump1eb44332009-09-09 15:08:12 +00004166
Douglas Gregor03e80032011-06-21 17:03:29 +00004167 case Stmt::MaterializeTemporaryExprClass:
4168 if (Expr *Result = EvalAddr(
4169 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004170 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00004171 return Result;
4172
4173 return E;
4174
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004175 // Everything else: we simply don't reason about them.
4176 default:
4177 return NULL;
4178 }
Ted Kremenek06de2762007-08-17 16:46:58 +00004179}
Mike Stump1eb44332009-09-09 15:08:12 +00004180
Ted Kremenek06de2762007-08-17 16:46:58 +00004181
4182/// EvalVal - This function is complements EvalAddr in the mutual recursion.
4183/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004184static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4185 Decl *ParentDecl) {
Ted Kremenek68957a92010-08-04 20:01:07 +00004186do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00004187 // We should only be called for evaluating non-pointer expressions, or
4188 // expressions with a pointer type that are not used as references but instead
4189 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00004190
Ted Kremenek06de2762007-08-17 16:46:58 +00004191 // Our "symbolic interpreter" is just a dispatch off the currently
4192 // viewed AST node. We then recursively traverse the AST by calling
4193 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00004194
4195 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00004196 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00004197 case Stmt::ImplicitCastExprClass: {
4198 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00004199 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00004200 E = IE->getSubExpr();
4201 continue;
4202 }
4203 return NULL;
4204 }
4205
John McCall80ee6e82011-11-10 05:35:25 +00004206 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004207 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00004208
Douglas Gregora2813ce2009-10-23 18:54:35 +00004209 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004210 // When we hit a DeclRefExpr we are looking at code that refers to a
4211 // variable's name. If it's not a reference variable we check if it has
4212 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00004213 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004214
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004215 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
4216 // Check if it refers to itself, e.g. "int& i = i;".
4217 if (V == ParentDecl)
4218 return DR;
4219
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004220 if (V->hasLocalStorage()) {
4221 if (!V->getType()->isReferenceType())
4222 return DR;
4223
4224 // Reference variable, follow through to the expression that
4225 // it points to.
4226 if (V->hasInit()) {
4227 // Add the reference variable to the "trail".
4228 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004229 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004230 }
4231 }
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004232 }
Mike Stump1eb44332009-09-09 15:08:12 +00004233
Ted Kremenek06de2762007-08-17 16:46:58 +00004234 return NULL;
4235 }
Mike Stump1eb44332009-09-09 15:08:12 +00004236
Ted Kremenek06de2762007-08-17 16:46:58 +00004237 case Stmt::UnaryOperatorClass: {
4238 // The only unary operator that make sense to handle here
4239 // is Deref. All others don't resolve to a "name." This includes
4240 // handling all sorts of rvalues passed to a unary operator.
4241 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004242
John McCall2de56d12010-08-25 11:45:40 +00004243 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004244 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004245
4246 return NULL;
4247 }
Mike Stump1eb44332009-09-09 15:08:12 +00004248
Ted Kremenek06de2762007-08-17 16:46:58 +00004249 case Stmt::ArraySubscriptExprClass: {
4250 // Array subscripts are potential references to data on the stack. We
4251 // retrieve the DeclRefExpr* for the array variable if it indeed
4252 // has local storage.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004253 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004254 }
Mike Stump1eb44332009-09-09 15:08:12 +00004255
Ted Kremenek06de2762007-08-17 16:46:58 +00004256 case Stmt::ConditionalOperatorClass: {
4257 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004258 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00004259 ConditionalOperator *C = cast<ConditionalOperator>(E);
4260
Anders Carlsson39073232007-11-30 19:04:31 +00004261 // Handle the GNU extension for missing LHS.
4262 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004263 if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl))
Anders Carlsson39073232007-11-30 19:04:31 +00004264 return LHS;
4265
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004266 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004267 }
Mike Stump1eb44332009-09-09 15:08:12 +00004268
Ted Kremenek06de2762007-08-17 16:46:58 +00004269 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00004270 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00004271 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004272
Ted Kremenek06de2762007-08-17 16:46:58 +00004273 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00004274 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00004275 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00004276
4277 // Check whether the member type is itself a reference, in which case
4278 // we're not going to refer to the member, but to what the member refers to.
4279 if (M->getMemberDecl()->getType()->isReferenceType())
4280 return NULL;
4281
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004282 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004283 }
Mike Stump1eb44332009-09-09 15:08:12 +00004284
Douglas Gregor03e80032011-06-21 17:03:29 +00004285 case Stmt::MaterializeTemporaryExprClass:
4286 if (Expr *Result = EvalVal(
4287 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004288 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00004289 return Result;
4290
4291 return E;
4292
Ted Kremenek06de2762007-08-17 16:46:58 +00004293 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004294 // Check that we don't return or take the address of a reference to a
4295 // temporary. This is only useful in C++.
4296 if (!E->isTypeDependent() && E->isRValue())
4297 return E;
4298
4299 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00004300 return NULL;
4301 }
Ted Kremenek68957a92010-08-04 20:01:07 +00004302} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00004303}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004304
4305//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
4306
4307/// Check for comparisons of floating point operands using != and ==.
4308/// Issue a warning if these are no self-comparisons, as they are not likely
4309/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00004310void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieudd225092011-09-15 21:56:47 +00004311 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
4312 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004313
4314 // Special case: check for x == x (which is OK).
4315 // Do not emit warnings for such cases.
4316 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
4317 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
4318 if (DRL->getDecl() == DRR->getDecl())
David Blaikie980343b2012-07-16 20:47:22 +00004319 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004320
4321
Ted Kremenek1b500bb2007-11-29 00:59:04 +00004322 // Special case: check for comparisons against literals that can be exactly
4323 // represented by APFloat. In such cases, do not emit a warning. This
4324 // is a heuristic: often comparison against such literals are used to
4325 // detect if a value in a variable has not changed. This clearly can
4326 // lead to false negatives.
David Blaikie980343b2012-07-16 20:47:22 +00004327 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
4328 if (FLL->isExact())
4329 return;
4330 } else
4331 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
4332 if (FLR->isExact())
4333 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004334
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004335 // Check for comparisons with builtin types.
David Blaikie980343b2012-07-16 20:47:22 +00004336 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
4337 if (CL->isBuiltinCall())
4338 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004339
David Blaikie980343b2012-07-16 20:47:22 +00004340 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
4341 if (CR->isBuiltinCall())
4342 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004343
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004344 // Emit the diagnostic.
David Blaikie980343b2012-07-16 20:47:22 +00004345 Diag(Loc, diag::warn_floatingpoint_eq)
4346 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004347}
John McCallba26e582010-01-04 23:21:16 +00004348
John McCallf2370c92010-01-06 05:24:50 +00004349//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
4350//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00004351
John McCallf2370c92010-01-06 05:24:50 +00004352namespace {
John McCallba26e582010-01-04 23:21:16 +00004353
John McCallf2370c92010-01-06 05:24:50 +00004354/// Structure recording the 'active' range of an integer-valued
4355/// expression.
4356struct IntRange {
4357 /// The number of bits active in the int.
4358 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00004359
John McCallf2370c92010-01-06 05:24:50 +00004360 /// True if the int is known not to have negative values.
4361 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00004362
John McCallf2370c92010-01-06 05:24:50 +00004363 IntRange(unsigned Width, bool NonNegative)
4364 : Width(Width), NonNegative(NonNegative)
4365 {}
John McCallba26e582010-01-04 23:21:16 +00004366
John McCall1844a6e2010-11-10 23:38:19 +00004367 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00004368 static IntRange forBoolType() {
4369 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00004370 }
4371
John McCall1844a6e2010-11-10 23:38:19 +00004372 /// Returns the range of an opaque value of the given integral type.
4373 static IntRange forValueOfType(ASTContext &C, QualType T) {
4374 return forValueOfCanonicalType(C,
4375 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00004376 }
4377
John McCall1844a6e2010-11-10 23:38:19 +00004378 /// Returns the range of an opaque value of a canonical integral type.
4379 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00004380 assert(T->isCanonicalUnqualified());
4381
4382 if (const VectorType *VT = dyn_cast<VectorType>(T))
4383 T = VT->getElementType().getTypePtr();
4384 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4385 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00004386
David Majnemerf9eaf982013-06-07 22:07:20 +00004387 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00004388 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemerf9eaf982013-06-07 22:07:20 +00004389 EnumDecl *Enum = ET->getDecl();
4390 if (!Enum->isCompleteDefinition())
4391 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall091f23f2010-11-09 22:22:12 +00004392
David Majnemerf9eaf982013-06-07 22:07:20 +00004393 unsigned NumPositive = Enum->getNumPositiveBits();
4394 unsigned NumNegative = Enum->getNumNegativeBits();
John McCall323ed742010-05-06 08:58:33 +00004395
David Majnemerf9eaf982013-06-07 22:07:20 +00004396 if (NumNegative == 0)
4397 return IntRange(NumPositive, true/*NonNegative*/);
4398 else
4399 return IntRange(std::max(NumPositive + 1, NumNegative),
4400 false/*NonNegative*/);
John McCall323ed742010-05-06 08:58:33 +00004401 }
John McCallf2370c92010-01-06 05:24:50 +00004402
4403 const BuiltinType *BT = cast<BuiltinType>(T);
4404 assert(BT->isInteger());
4405
4406 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4407 }
4408
John McCall1844a6e2010-11-10 23:38:19 +00004409 /// Returns the "target" range of a canonical integral type, i.e.
4410 /// the range of values expressible in the type.
4411 ///
4412 /// This matches forValueOfCanonicalType except that enums have the
4413 /// full range of their type, not the range of their enumerators.
4414 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4415 assert(T->isCanonicalUnqualified());
4416
4417 if (const VectorType *VT = dyn_cast<VectorType>(T))
4418 T = VT->getElementType().getTypePtr();
4419 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4420 T = CT->getElementType().getTypePtr();
4421 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00004422 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00004423
4424 const BuiltinType *BT = cast<BuiltinType>(T);
4425 assert(BT->isInteger());
4426
4427 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4428 }
4429
4430 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00004431 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00004432 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00004433 L.NonNegative && R.NonNegative);
4434 }
4435
John McCall1844a6e2010-11-10 23:38:19 +00004436 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00004437 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00004438 return IntRange(std::min(L.Width, R.Width),
4439 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00004440 }
4441};
4442
Ted Kremenek0692a192012-01-31 05:37:37 +00004443static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4444 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004445 if (value.isSigned() && value.isNegative())
4446 return IntRange(value.getMinSignedBits(), false);
4447
4448 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00004449 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004450
4451 // isNonNegative() just checks the sign bit without considering
4452 // signedness.
4453 return IntRange(value.getActiveBits(), true);
4454}
4455
Ted Kremenek0692a192012-01-31 05:37:37 +00004456static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4457 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004458 if (result.isInt())
4459 return GetValueRange(C, result.getInt(), MaxWidth);
4460
4461 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00004462 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4463 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4464 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4465 R = IntRange::join(R, El);
4466 }
John McCallf2370c92010-01-06 05:24:50 +00004467 return R;
4468 }
4469
4470 if (result.isComplexInt()) {
4471 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4472 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4473 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00004474 }
4475
4476 // This can happen with lossless casts to intptr_t of "based" lvalues.
4477 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00004478 // FIXME: The only reason we need to pass the type in here is to get
4479 // the sign right on this one case. It would be nice if APValue
4480 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00004481 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004482 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00004483}
John McCallf2370c92010-01-06 05:24:50 +00004484
Eli Friedman09bddcf2013-07-08 20:20:06 +00004485static QualType GetExprType(Expr *E) {
4486 QualType Ty = E->getType();
4487 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
4488 Ty = AtomicRHS->getValueType();
4489 return Ty;
4490}
4491
John McCallf2370c92010-01-06 05:24:50 +00004492/// Pseudo-evaluate the given integer expression, estimating the
4493/// range of values it might take.
4494///
4495/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek0692a192012-01-31 05:37:37 +00004496static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004497 E = E->IgnoreParens();
4498
4499 // Try a full evaluation first.
4500 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004501 if (E->EvaluateAsRValue(result, C))
Eli Friedman09bddcf2013-07-08 20:20:06 +00004502 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004503
4504 // I think we only want to look through implicit casts here; if the
4505 // user has an explicit widening cast, we should treat the value as
4506 // being of the new, wider type.
4507 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00004508 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00004509 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4510
Eli Friedman09bddcf2013-07-08 20:20:06 +00004511 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCallf2370c92010-01-06 05:24:50 +00004512
John McCall2de56d12010-08-25 11:45:40 +00004513 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00004514
John McCallf2370c92010-01-06 05:24:50 +00004515 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00004516 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00004517 return OutputTypeRange;
4518
4519 IntRange SubRange
4520 = GetExprRange(C, CE->getSubExpr(),
4521 std::min(MaxWidth, OutputTypeRange.Width));
4522
4523 // Bail out if the subexpr's range is as wide as the cast type.
4524 if (SubRange.Width >= OutputTypeRange.Width)
4525 return OutputTypeRange;
4526
4527 // Otherwise, we take the smaller width, and we're non-negative if
4528 // either the output type or the subexpr is.
4529 return IntRange(SubRange.Width,
4530 SubRange.NonNegative || OutputTypeRange.NonNegative);
4531 }
4532
4533 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4534 // If we can fold the condition, just take that operand.
4535 bool CondResult;
4536 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
4537 return GetExprRange(C, CondResult ? CO->getTrueExpr()
4538 : CO->getFalseExpr(),
4539 MaxWidth);
4540
4541 // Otherwise, conservatively merge.
4542 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
4543 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
4544 return IntRange::join(L, R);
4545 }
4546
4547 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4548 switch (BO->getOpcode()) {
4549
4550 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00004551 case BO_LAnd:
4552 case BO_LOr:
4553 case BO_LT:
4554 case BO_GT:
4555 case BO_LE:
4556 case BO_GE:
4557 case BO_EQ:
4558 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00004559 return IntRange::forBoolType();
4560
John McCall862ff872011-07-13 06:35:24 +00004561 // The type of the assignments is the type of the LHS, so the RHS
4562 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00004563 case BO_MulAssign:
4564 case BO_DivAssign:
4565 case BO_RemAssign:
4566 case BO_AddAssign:
4567 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00004568 case BO_XorAssign:
4569 case BO_OrAssign:
4570 // TODO: bitfields?
Eli Friedman09bddcf2013-07-08 20:20:06 +00004571 return IntRange::forValueOfType(C, GetExprType(E));
John McCallc0cd21d2010-02-23 19:22:29 +00004572
John McCall862ff872011-07-13 06:35:24 +00004573 // Simple assignments just pass through the RHS, which will have
4574 // been coerced to the LHS type.
4575 case BO_Assign:
4576 // TODO: bitfields?
4577 return GetExprRange(C, BO->getRHS(), MaxWidth);
4578
John McCallf2370c92010-01-06 05:24:50 +00004579 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004580 case BO_PtrMemD:
4581 case BO_PtrMemI:
Eli Friedman09bddcf2013-07-08 20:20:06 +00004582 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004583
John McCall60fad452010-01-06 22:07:33 +00004584 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00004585 case BO_And:
4586 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00004587 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
4588 GetExprRange(C, BO->getRHS(), MaxWidth));
4589
John McCallf2370c92010-01-06 05:24:50 +00004590 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00004591 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00004592 // ...except that we want to treat '1 << (blah)' as logically
4593 // positive. It's an important idiom.
4594 if (IntegerLiteral *I
4595 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
4596 if (I->getValue() == 1) {
Eli Friedman09bddcf2013-07-08 20:20:06 +00004597 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall3aae6092010-04-07 01:14:35 +00004598 return IntRange(R.Width, /*NonNegative*/ true);
4599 }
4600 }
4601 // fallthrough
4602
John McCall2de56d12010-08-25 11:45:40 +00004603 case BO_ShlAssign:
Eli Friedman09bddcf2013-07-08 20:20:06 +00004604 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004605
John McCall60fad452010-01-06 22:07:33 +00004606 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00004607 case BO_Shr:
4608 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00004609 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4610
4611 // If the shift amount is a positive constant, drop the width by
4612 // that much.
4613 llvm::APSInt shift;
4614 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
4615 shift.isNonNegative()) {
4616 unsigned zext = shift.getZExtValue();
4617 if (zext >= L.Width)
4618 L.Width = (L.NonNegative ? 0 : 1);
4619 else
4620 L.Width -= zext;
4621 }
4622
4623 return L;
4624 }
4625
4626 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00004627 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00004628 return GetExprRange(C, BO->getRHS(), MaxWidth);
4629
John McCall60fad452010-01-06 22:07:33 +00004630 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00004631 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00004632 if (BO->getLHS()->getType()->isPointerType())
Eli Friedman09bddcf2013-07-08 20:20:06 +00004633 return IntRange::forValueOfType(C, GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00004634 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00004635
John McCall00fe7612011-07-14 22:39:48 +00004636 // The width of a division result is mostly determined by the size
4637 // of the LHS.
4638 case BO_Div: {
4639 // Don't 'pre-truncate' the operands.
Eli Friedman09bddcf2013-07-08 20:20:06 +00004640 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00004641 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4642
4643 // If the divisor is constant, use that.
4644 llvm::APSInt divisor;
4645 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
4646 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
4647 if (log2 >= L.Width)
4648 L.Width = (L.NonNegative ? 0 : 1);
4649 else
4650 L.Width = std::min(L.Width - log2, MaxWidth);
4651 return L;
4652 }
4653
4654 // Otherwise, just use the LHS's width.
4655 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4656 return IntRange(L.Width, L.NonNegative && R.NonNegative);
4657 }
4658
4659 // The result of a remainder can't be larger than the result of
4660 // either side.
4661 case BO_Rem: {
4662 // Don't 'pre-truncate' the operands.
Eli Friedman09bddcf2013-07-08 20:20:06 +00004663 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00004664 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4665 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4666
4667 IntRange meet = IntRange::meet(L, R);
4668 meet.Width = std::min(meet.Width, MaxWidth);
4669 return meet;
4670 }
4671
4672 // The default behavior is okay for these.
4673 case BO_Mul:
4674 case BO_Add:
4675 case BO_Xor:
4676 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00004677 break;
4678 }
4679
John McCall00fe7612011-07-14 22:39:48 +00004680 // The default case is to treat the operation as if it were closed
4681 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00004682 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4683 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
4684 return IntRange::join(L, R);
4685 }
4686
4687 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
4688 switch (UO->getOpcode()) {
4689 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00004690 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00004691 return IntRange::forBoolType();
4692
4693 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004694 case UO_Deref:
4695 case UO_AddrOf: // should be impossible
Eli Friedman09bddcf2013-07-08 20:20:06 +00004696 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004697
4698 default:
4699 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
4700 }
4701 }
4702
Ted Kremenek728a1fb2013-10-14 18:55:27 +00004703 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
4704 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
4705
John McCall993f43f2013-05-06 21:39:12 +00004706 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004707 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004708 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00004709
Eli Friedman09bddcf2013-07-08 20:20:06 +00004710 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004711}
John McCall51313c32010-01-04 23:31:57 +00004712
Ted Kremenek0692a192012-01-31 05:37:37 +00004713static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedman09bddcf2013-07-08 20:20:06 +00004714 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCall323ed742010-05-06 08:58:33 +00004715}
4716
John McCall51313c32010-01-04 23:31:57 +00004717/// Checks whether the given value, which currently has the given
4718/// source semantics, has the same value when coerced through the
4719/// target semantics.
Ted Kremenek0692a192012-01-31 05:37:37 +00004720static bool IsSameFloatAfterCast(const llvm::APFloat &value,
4721 const llvm::fltSemantics &Src,
4722 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004723 llvm::APFloat truncated = value;
4724
4725 bool ignored;
4726 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
4727 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
4728
4729 return truncated.bitwiseIsEqual(value);
4730}
4731
4732/// Checks whether the given value, which currently has the given
4733/// source semantics, has the same value when coerced through the
4734/// target semantics.
4735///
4736/// The value might be a vector of floats (or a complex number).
Ted Kremenek0692a192012-01-31 05:37:37 +00004737static bool IsSameFloatAfterCast(const APValue &value,
4738 const llvm::fltSemantics &Src,
4739 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004740 if (value.isFloat())
4741 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
4742
4743 if (value.isVector()) {
4744 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
4745 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
4746 return false;
4747 return true;
4748 }
4749
4750 assert(value.isComplexFloat());
4751 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
4752 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
4753}
4754
Ted Kremenek0692a192012-01-31 05:37:37 +00004755static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00004756
Ted Kremeneke3b159c2010-09-23 21:43:44 +00004757static bool IsZero(Sema &S, Expr *E) {
4758 // Suppress cases where we are comparing against an enum constant.
4759 if (const DeclRefExpr *DR =
4760 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
4761 if (isa<EnumConstantDecl>(DR->getDecl()))
4762 return false;
4763
4764 // Suppress cases where the '0' value is expanded from a macro.
4765 if (E->getLocStart().isMacroID())
4766 return false;
4767
John McCall323ed742010-05-06 08:58:33 +00004768 llvm::APSInt Value;
4769 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
4770}
4771
John McCall372e1032010-10-06 00:25:24 +00004772static bool HasEnumType(Expr *E) {
4773 // Strip off implicit integral promotions.
4774 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004775 if (ICE->getCastKind() != CK_IntegralCast &&
4776 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00004777 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004778 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00004779 }
4780
4781 return E->getType()->isEnumeralType();
4782}
4783
Ted Kremenek0692a192012-01-31 05:37:37 +00004784static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieucbc19872013-11-01 21:47:19 +00004785 // Disable warning in template instantiations.
4786 if (!S.ActiveTemplateInstantiations.empty())
4787 return;
4788
John McCall2de56d12010-08-25 11:45:40 +00004789 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00004790 if (E->isValueDependent())
4791 return;
4792
John McCall2de56d12010-08-25 11:45:40 +00004793 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004794 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004795 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004796 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004797 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004798 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004799 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004800 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004801 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004802 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004803 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004804 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004805 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004806 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004807 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004808 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4809 }
4810}
4811
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004812static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004813 Expr *Constant, Expr *Other,
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004814 llvm::APSInt Value,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004815 bool RhsConstant) {
Richard Trieu311cb2b2013-11-01 21:19:43 +00004816 // Disable warning in template instantiations.
4817 if (!S.ActiveTemplateInstantiations.empty())
4818 return;
4819
Richard Trieu526e6272012-11-14 22:50:24 +00004820 // 0 values are handled later by CheckTrivialUnsignedComparison().
4821 if (Value == 0)
4822 return;
4823
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004824 BinaryOperatorKind op = E->getOpcode();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004825 QualType OtherT = Other->getType();
4826 QualType ConstantT = Constant->getType();
Richard Trieu526e6272012-11-14 22:50:24 +00004827 QualType CommonT = E->getLHS()->getType();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004828 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004829 return;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004830 assert((OtherT->isIntegerType() && ConstantT->isIntegerType())
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004831 && "comparison with non-integer type");
Richard Trieu526e6272012-11-14 22:50:24 +00004832
4833 bool ConstantSigned = ConstantT->isSignedIntegerType();
Richard Trieu526e6272012-11-14 22:50:24 +00004834 bool CommonSigned = CommonT->isSignedIntegerType();
4835
4836 bool EqualityOnly = false;
4837
4838 // TODO: Investigate using GetExprRange() to get tighter bounds on
4839 // on the bit ranges.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004840 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
Richard Trieu526e6272012-11-14 22:50:24 +00004841 unsigned OtherWidth = OtherRange.Width;
4842
4843 if (CommonSigned) {
4844 // The common type is signed, therefore no signed to unsigned conversion.
Eli Friedmand87de7b2012-11-30 23:09:29 +00004845 if (!OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00004846 // Check that the constant is representable in type OtherT.
4847 if (ConstantSigned) {
4848 if (OtherWidth >= Value.getMinSignedBits())
4849 return;
4850 } else { // !ConstantSigned
4851 if (OtherWidth >= Value.getActiveBits() + 1)
4852 return;
4853 }
4854 } else { // !OtherSigned
4855 // Check that the constant is representable in type OtherT.
4856 // Negative values are out of range.
4857 if (ConstantSigned) {
4858 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
4859 return;
4860 } else { // !ConstantSigned
4861 if (OtherWidth >= Value.getActiveBits())
4862 return;
4863 }
4864 }
4865 } else { // !CommonSigned
Eli Friedmand87de7b2012-11-30 23:09:29 +00004866 if (OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00004867 if (OtherWidth >= Value.getActiveBits())
4868 return;
Eli Friedmand87de7b2012-11-30 23:09:29 +00004869 } else if (!OtherRange.NonNegative && !ConstantSigned) {
Richard Trieu526e6272012-11-14 22:50:24 +00004870 // Check to see if the constant is representable in OtherT.
4871 if (OtherWidth > Value.getActiveBits())
4872 return;
4873 // Check to see if the constant is equivalent to a negative value
4874 // cast to CommonT.
4875 if (S.Context.getIntWidth(ConstantT) == S.Context.getIntWidth(CommonT) &&
Richard Trieu5d1cf4f2012-11-15 03:43:50 +00004876 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
Richard Trieu526e6272012-11-14 22:50:24 +00004877 return;
4878 // The constant value rests between values that OtherT can represent after
4879 // conversion. Relational comparison still works, but equality
4880 // comparisons will be tautological.
4881 EqualityOnly = true;
4882 } else { // OtherSigned && ConstantSigned
4883 assert(0 && "Two signed types converted to unsigned types.");
4884 }
4885 }
4886
4887 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
4888
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004889 bool IsTrue = true;
Richard Trieu526e6272012-11-14 22:50:24 +00004890 if (op == BO_EQ || op == BO_NE) {
4891 IsTrue = op == BO_NE;
4892 } else if (EqualityOnly) {
4893 return;
4894 } else if (RhsConstant) {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004895 if (op == BO_GT || op == BO_GE)
Richard Trieu526e6272012-11-14 22:50:24 +00004896 IsTrue = !PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004897 else // op == BO_LT || op == BO_LE
Richard Trieu526e6272012-11-14 22:50:24 +00004898 IsTrue = PositiveConstant;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004899 } else {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004900 if (op == BO_LT || op == BO_LE)
Richard Trieu526e6272012-11-14 22:50:24 +00004901 IsTrue = !PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004902 else // op == BO_GT || op == BO_GE
Richard Trieu526e6272012-11-14 22:50:24 +00004903 IsTrue = PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004904 }
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004905
4906 // If this is a comparison to an enum constant, include that
4907 // constant in the diagnostic.
4908 const EnumConstantDecl *ED = 0;
4909 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
4910 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
4911
4912 SmallString<64> PrettySourceValue;
4913 llvm::raw_svector_ostream OS(PrettySourceValue);
4914 if (ED)
Ted Kremenek9de50942013-03-15 22:02:46 +00004915 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004916 else
4917 OS << Value;
4918
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004919 S.Diag(E->getOperatorLoc(), diag::warn_out_of_range_compare)
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004920 << OS.str() << OtherT << IsTrue
Richard Trieu526e6272012-11-14 22:50:24 +00004921 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004922}
4923
John McCall323ed742010-05-06 08:58:33 +00004924/// Analyze the operands of the given comparison. Implements the
4925/// fallback case from AnalyzeComparison.
Ted Kremenek0692a192012-01-31 05:37:37 +00004926static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00004927 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4928 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00004929}
John McCall51313c32010-01-04 23:31:57 +00004930
John McCallba26e582010-01-04 23:21:16 +00004931/// \brief Implements -Wsign-compare.
4932///
Richard Trieudd225092011-09-15 21:56:47 +00004933/// \param E the binary operator to check for warnings
Ted Kremenek0692a192012-01-31 05:37:37 +00004934static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCall323ed742010-05-06 08:58:33 +00004935 // The type the comparison is being performed in.
4936 QualType T = E->getLHS()->getType();
4937 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
4938 && "comparison with mismatched types");
Fariborz Jahanianab4702f2012-09-18 17:46:26 +00004939 if (E->isValueDependent())
4940 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004941
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004942 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
4943 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004944
4945 bool IsComparisonConstant = false;
4946
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004947 // Check whether an integer constant comparison results in a value
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004948 // of 'true' or 'false'.
4949 if (T->isIntegralType(S.Context)) {
4950 llvm::APSInt RHSValue;
4951 bool IsRHSIntegralLiteral =
4952 RHS->isIntegerConstantExpr(RHSValue, S.Context);
4953 llvm::APSInt LHSValue;
4954 bool IsLHSIntegralLiteral =
4955 LHS->isIntegerConstantExpr(LHSValue, S.Context);
4956 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
4957 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
4958 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
4959 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
4960 else
4961 IsComparisonConstant =
4962 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004963 } else if (!T->hasUnsignedIntegerRepresentation())
4964 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004965
John McCall323ed742010-05-06 08:58:33 +00004966 // We don't do anything special if this isn't an unsigned integral
4967 // comparison: we're only interested in integral comparisons, and
4968 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00004969 //
4970 // We also don't care about value-dependent expressions or expressions
4971 // whose result is a constant.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004972 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCall323ed742010-05-06 08:58:33 +00004973 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004974
John McCall323ed742010-05-06 08:58:33 +00004975 // Check to see if one of the (unmodified) operands is of different
4976 // signedness.
4977 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00004978 if (LHS->getType()->hasSignedIntegerRepresentation()) {
4979 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00004980 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00004981 signedOperand = LHS;
4982 unsignedOperand = RHS;
4983 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
4984 signedOperand = RHS;
4985 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00004986 } else {
John McCall323ed742010-05-06 08:58:33 +00004987 CheckTrivialUnsignedComparison(S, E);
4988 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004989 }
4990
John McCall323ed742010-05-06 08:58:33 +00004991 // Otherwise, calculate the effective range of the signed operand.
4992 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00004993
John McCall323ed742010-05-06 08:58:33 +00004994 // Go ahead and analyze implicit conversions in the operands. Note
4995 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00004996 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
4997 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00004998
John McCall323ed742010-05-06 08:58:33 +00004999 // If the signed range is non-negative, -Wsign-compare won't fire,
5000 // but we should still check for comparisons which are always true
5001 // or false.
5002 if (signedRange.NonNegative)
5003 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00005004
5005 // For (in)equality comparisons, if the unsigned operand is a
5006 // constant which cannot collide with a overflowed signed operand,
5007 // then reinterpreting the signed operand as unsigned will not
5008 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00005009 if (E->isEqualityOp()) {
5010 unsigned comparisonWidth = S.Context.getIntWidth(T);
5011 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00005012
John McCall323ed742010-05-06 08:58:33 +00005013 // We should never be unable to prove that the unsigned operand is
5014 // non-negative.
5015 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
5016
5017 if (unsignedRange.Width < comparisonWidth)
5018 return;
5019 }
5020
Douglas Gregor6d3b93d2012-05-01 01:53:49 +00005021 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5022 S.PDiag(diag::warn_mixed_sign_comparison)
5023 << LHS->getType() << RHS->getType()
5024 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallba26e582010-01-04 23:21:16 +00005025}
5026
John McCall15d7d122010-11-11 03:21:53 +00005027/// Analyzes an attempt to assign the given value to a bitfield.
5028///
5029/// Returns true if there was something fishy about the attempt.
Ted Kremenek0692a192012-01-31 05:37:37 +00005030static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
5031 SourceLocation InitLoc) {
John McCall15d7d122010-11-11 03:21:53 +00005032 assert(Bitfield->isBitField());
5033 if (Bitfield->isInvalidDecl())
5034 return false;
5035
John McCall91b60142010-11-11 05:33:51 +00005036 // White-list bool bitfields.
5037 if (Bitfield->getType()->isBooleanType())
5038 return false;
5039
Douglas Gregor46ff3032011-02-04 13:09:01 +00005040 // Ignore value- or type-dependent expressions.
5041 if (Bitfield->getBitWidth()->isValueDependent() ||
5042 Bitfield->getBitWidth()->isTypeDependent() ||
5043 Init->isValueDependent() ||
5044 Init->isTypeDependent())
5045 return false;
5046
John McCall15d7d122010-11-11 03:21:53 +00005047 Expr *OriginalInit = Init->IgnoreParenImpCasts();
5048
Richard Smith80d4b552011-12-28 19:48:30 +00005049 llvm::APSInt Value;
5050 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00005051 return false;
5052
John McCall15d7d122010-11-11 03:21:53 +00005053 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00005054 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00005055
5056 if (OriginalWidth <= FieldWidth)
5057 return false;
5058
Eli Friedman3a643af2012-01-26 23:11:39 +00005059 // Compute the value which the bitfield will contain.
Jay Foad9f71a8f2010-12-07 08:25:34 +00005060 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedman3a643af2012-01-26 23:11:39 +00005061 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall15d7d122010-11-11 03:21:53 +00005062
Eli Friedman3a643af2012-01-26 23:11:39 +00005063 // Check whether the stored value is equal to the original value.
5064 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieue1ecdc12012-07-23 20:21:35 +00005065 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall15d7d122010-11-11 03:21:53 +00005066 return false;
5067
Eli Friedman3a643af2012-01-26 23:11:39 +00005068 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedman34ff0622012-02-02 00:40:20 +00005069 // therefore don't strictly fit into a signed bitfield of width 1.
5070 if (FieldWidth == 1 && Value == 1)
Eli Friedman3a643af2012-01-26 23:11:39 +00005071 return false;
5072
John McCall15d7d122010-11-11 03:21:53 +00005073 std::string PrettyValue = Value.toString(10);
5074 std::string PrettyTrunc = TruncatedValue.toString(10);
5075
5076 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
5077 << PrettyValue << PrettyTrunc << OriginalInit->getType()
5078 << Init->getSourceRange();
5079
5080 return true;
5081}
5082
John McCallbeb22aa2010-11-09 23:24:47 +00005083/// Analyze the given simple or compound assignment for warning-worthy
5084/// operations.
Ted Kremenek0692a192012-01-31 05:37:37 +00005085static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCallbeb22aa2010-11-09 23:24:47 +00005086 // Just recurse on the LHS.
5087 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5088
5089 // We want to recurse on the RHS as normal unless we're assigning to
5090 // a bitfield.
John McCall993f43f2013-05-06 21:39:12 +00005091 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005092 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall15d7d122010-11-11 03:21:53 +00005093 E->getOperatorLoc())) {
5094 // Recurse, ignoring any implicit conversions on the RHS.
5095 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
5096 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00005097 }
5098 }
5099
5100 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
5101}
5102
John McCall51313c32010-01-04 23:31:57 +00005103/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00005104static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00005105 SourceLocation CContext, unsigned diag,
5106 bool pruneControlFlow = false) {
5107 if (pruneControlFlow) {
5108 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5109 S.PDiag(diag)
5110 << SourceType << T << E->getSourceRange()
5111 << SourceRange(CContext));
5112 return;
5113 }
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005114 S.Diag(E->getExprLoc(), diag)
5115 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
5116}
5117
Chandler Carruthe1b02e02011-04-05 06:47:57 +00005118/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00005119static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00005120 SourceLocation CContext, unsigned diag,
5121 bool pruneControlFlow = false) {
5122 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruthe1b02e02011-04-05 06:47:57 +00005123}
5124
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005125/// Diagnose an implicit cast from a literal expression. Does not warn when the
5126/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00005127void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
5128 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005129 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00005130 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005131 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00005132 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
5133 T->hasUnsignedIntegerRepresentation());
5134 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00005135 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005136 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00005137 return;
5138
Eli Friedman4e1a82c2013-08-29 23:44:43 +00005139 // FIXME: Force the precision of the source value down so we don't print
5140 // digits which are usually useless (we don't really care here if we
5141 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
5142 // would automatically print the shortest representation, but it's a bit
5143 // tricky to implement.
David Blaikiebe0ee872012-05-15 16:56:36 +00005144 SmallString<16> PrettySourceValue;
Eli Friedman4e1a82c2013-08-29 23:44:43 +00005145 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
5146 precision = (precision * 59 + 195) / 196;
5147 Value.toString(PrettySourceValue, precision);
5148
David Blaikiede7e7b82012-05-15 17:18:27 +00005149 SmallString<16> PrettyTargetValue;
David Blaikiebe0ee872012-05-15 16:56:36 +00005150 if (T->isSpecificBuiltinType(BuiltinType::Bool))
5151 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
5152 else
David Blaikiede7e7b82012-05-15 17:18:27 +00005153 IntegerValue.toString(PrettyTargetValue);
David Blaikiebe0ee872012-05-15 16:56:36 +00005154
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005155 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikiebe0ee872012-05-15 16:56:36 +00005156 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
5157 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00005158}
5159
John McCall091f23f2010-11-09 22:22:12 +00005160std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
5161 if (!Range.Width) return "0";
5162
5163 llvm::APSInt ValueInRange = Value;
5164 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00005165 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00005166 return ValueInRange.toString(10);
5167}
5168
Hans Wennborg88617a22012-08-28 15:44:30 +00005169static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
5170 if (!isa<ImplicitCastExpr>(Ex))
5171 return false;
5172
5173 Expr *InnerE = Ex->IgnoreParenImpCasts();
5174 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
5175 const Type *Source =
5176 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5177 if (Target->isDependentType())
5178 return false;
5179
5180 const BuiltinType *FloatCandidateBT =
5181 dyn_cast<BuiltinType>(ToBool ? Source : Target);
5182 const Type *BoolCandidateType = ToBool ? Target : Source;
5183
5184 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
5185 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
5186}
5187
5188void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
5189 SourceLocation CC) {
5190 unsigned NumArgs = TheCall->getNumArgs();
5191 for (unsigned i = 0; i < NumArgs; ++i) {
5192 Expr *CurrA = TheCall->getArg(i);
5193 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
5194 continue;
5195
5196 bool IsSwapped = ((i > 0) &&
5197 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
5198 IsSwapped |= ((i < (NumArgs - 1)) &&
5199 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
5200 if (IsSwapped) {
5201 // Warn on this floating-point to bool conversion.
5202 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
5203 CurrA->getType(), CC,
5204 diag::warn_impcast_floating_point_to_bool);
5205 }
5206 }
5207}
5208
John McCall323ed742010-05-06 08:58:33 +00005209void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005210 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00005211 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00005212
John McCall323ed742010-05-06 08:58:33 +00005213 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
5214 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
5215 if (Source == Target) return;
5216 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00005217
Chandler Carruth108f7562011-07-26 05:40:03 +00005218 // If the conversion context location is invalid don't complain. We also
5219 // don't want to emit a warning if the issue occurs from the expansion of
5220 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
5221 // delay this check as long as possible. Once we detect we are in that
5222 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00005223 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00005224 return;
5225
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005226 // Diagnose implicit casts to bool.
5227 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
5228 if (isa<StringLiteral>(E))
5229 // Warn on string literal to bool. Checks for string literals in logical
5230 // expressions, for instances, assert(0 && "error here"), is prevented
5231 // by a check in AnalyzeImplicitConversions().
5232 return DiagnoseImpCast(S, E, T, CC,
5233 diag::warn_impcast_string_literal_to_bool);
Lang Hamese14ca9f2011-12-05 20:49:50 +00005234 if (Source->isFunctionType()) {
5235 // Warn on function to bool. Checks free functions and static member
5236 // functions. Weakly imported functions are excluded from the check,
5237 // since it's common to test their value to check whether the linker
5238 // found a definition for them.
5239 ValueDecl *D = 0;
5240 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
5241 D = R->getDecl();
5242 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
5243 D = M->getMemberDecl();
5244 }
5245
5246 if (D && !D->isWeak()) {
Richard Trieu26b45d82011-12-06 04:48:01 +00005247 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
5248 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
5249 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie2def7732011-12-09 21:42:37 +00005250 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
5251 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
5252 QualType ReturnType;
5253 UnresolvedSet<4> NonTemplateOverloads;
David Blaikiec8fa5252013-06-21 23:54:45 +00005254 S.tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
David Blaikie2def7732011-12-09 21:42:37 +00005255 if (!ReturnType.isNull()
5256 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
5257 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
5258 << FixItHint::CreateInsertion(
5259 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu26b45d82011-12-06 04:48:01 +00005260 return;
5261 }
Lang Hamese14ca9f2011-12-05 20:49:50 +00005262 }
5263 }
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005264 }
John McCall51313c32010-01-04 23:31:57 +00005265
5266 // Strip vector types.
5267 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00005268 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005269 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005270 return;
John McCallb4eb64d2010-10-08 02:01:28 +00005271 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005272 }
Chris Lattnerb792b302011-06-14 04:51:15 +00005273
5274 // If the vector cast is cast between two vectors of the same size, it is
5275 // a bitcast, not a conversion.
5276 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
5277 return;
John McCall51313c32010-01-04 23:31:57 +00005278
5279 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
5280 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
5281 }
5282
5283 // Strip complex types.
5284 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00005285 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005286 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005287 return;
5288
John McCallb4eb64d2010-10-08 02:01:28 +00005289 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005290 }
John McCall51313c32010-01-04 23:31:57 +00005291
5292 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
5293 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
5294 }
5295
5296 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
5297 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
5298
5299 // If the source is floating point...
5300 if (SourceBT && SourceBT->isFloatingPoint()) {
5301 // ...and the target is floating point...
5302 if (TargetBT && TargetBT->isFloatingPoint()) {
5303 // ...then warn if we're dropping FP rank.
5304
5305 // Builtin FP kinds are ordered by increasing FP rank.
5306 if (SourceBT->getKind() > TargetBT->getKind()) {
5307 // Don't warn about float constants that are precisely
5308 // representable in the target type.
5309 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00005310 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00005311 // Value might be a float, a float vector, or a float complex.
5312 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00005313 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
5314 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00005315 return;
5316 }
5317
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005318 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005319 return;
5320
John McCallb4eb64d2010-10-08 02:01:28 +00005321 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00005322 }
5323 return;
5324 }
5325
Ted Kremenekef9ff882011-03-10 20:03:42 +00005326 // If the target is integral, always warn.
David Blaikiebe0ee872012-05-15 16:56:36 +00005327 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005328 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005329 return;
5330
Chandler Carrutha5b93322011-02-17 11:05:49 +00005331 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00005332 // We also want to warn on, e.g., "int i = -1.234"
5333 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
5334 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
5335 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
5336
Chandler Carruthf65076e2011-04-10 08:36:24 +00005337 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
5338 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00005339 } else {
5340 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
5341 }
5342 }
John McCall51313c32010-01-04 23:31:57 +00005343
Hans Wennborg88617a22012-08-28 15:44:30 +00005344 // If the target is bool, warn if expr is a function or method call.
5345 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
5346 isa<CallExpr>(E)) {
5347 // Check last argument of function call to see if it is an
5348 // implicit cast from a type matching the type the result
5349 // is being cast to.
5350 CallExpr *CEx = cast<CallExpr>(E);
5351 unsigned NumArgs = CEx->getNumArgs();
5352 if (NumArgs > 0) {
5353 Expr *LastA = CEx->getArg(NumArgs - 1);
5354 Expr *InnerE = LastA->IgnoreParenImpCasts();
5355 const Type *InnerType =
5356 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5357 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
5358 // Warn on this floating-point to bool conversion
5359 DiagnoseImpCast(S, E, T, CC,
5360 diag::warn_impcast_floating_point_to_bool);
5361 }
5362 }
5363 }
John McCall51313c32010-01-04 23:31:57 +00005364 return;
5365 }
5366
Richard Trieu1838ca52011-05-29 19:59:02 +00005367 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikieb26331b2012-06-19 21:19:06 +00005368 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiee81b43b2012-11-08 00:41:20 +00005369 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikie896c7dd2013-02-16 00:56:22 +00005370 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieb1360492012-03-16 20:30:12 +00005371 SourceLocation Loc = E->getSourceRange().getBegin();
5372 if (Loc.isMacroID())
5373 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie9fb1ac52012-05-15 21:57:38 +00005374 if (!Loc.isMacroID() || CC.isMacroID())
5375 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
5376 << T << clang::SourceRange(CC)
Richard Smith8adf8372013-09-20 00:27:40 +00005377 << FixItHint::CreateReplacement(Loc,
5378 S.getFixItZeroLiteralForType(T, Loc));
Richard Trieu1838ca52011-05-29 19:59:02 +00005379 }
5380
David Blaikieb26331b2012-06-19 21:19:06 +00005381 if (!Source->isIntegerType() || !Target->isIntegerType())
5382 return;
5383
David Blaikiebe0ee872012-05-15 16:56:36 +00005384 // TODO: remove this early return once the false positives for constant->bool
5385 // in templates, macros, etc, are reduced or removed.
5386 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
5387 return;
5388
John McCall323ed742010-05-06 08:58:33 +00005389 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00005390 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00005391
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005392 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer25ffbef2013-03-28 19:07:11 +00005393 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005394 // TODO: this should happen for bitfield stores, too.
5395 llvm::APSInt Value(32);
5396 if (E->isIntegerConstantExpr(Value, S.Context)) {
5397 if (S.SourceMgr.isInSystemMacro(CC))
5398 return;
5399
John McCall091f23f2010-11-09 22:22:12 +00005400 std::string PrettySourceValue = Value.toString(10);
5401 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005402
Ted Kremenek5e745da2011-10-22 02:37:33 +00005403 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5404 S.PDiag(diag::warn_impcast_integer_precision_constant)
5405 << PrettySourceValue << PrettyTargetValue
5406 << E->getType() << T << E->getSourceRange()
5407 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00005408 return;
5409 }
5410
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005411 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
5412 if (S.SourceMgr.isInSystemMacro(CC))
5413 return;
5414
David Blaikie37050842012-04-12 22:40:54 +00005415 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaksc36bedc2012-02-01 19:08:57 +00005416 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
5417 /* pruneControlFlow */ true);
John McCallb4eb64d2010-10-08 02:01:28 +00005418 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00005419 }
5420
5421 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
5422 (!TargetRange.NonNegative && SourceRange.NonNegative &&
5423 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00005424
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005425 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005426 return;
5427
John McCall323ed742010-05-06 08:58:33 +00005428 unsigned DiagID = diag::warn_impcast_integer_sign;
5429
5430 // Traditionally, gcc has warned about this under -Wsign-compare.
5431 // We also want to warn about it in -Wconversion.
5432 // So if -Wconversion is off, use a completely identical diagnostic
5433 // in the sign-compare group.
5434 // The conditional-checking code will
5435 if (ICContext) {
5436 DiagID = diag::warn_impcast_integer_sign_conditional;
5437 *ICContext = true;
5438 }
5439
John McCallb4eb64d2010-10-08 02:01:28 +00005440 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00005441 }
5442
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005443 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005444 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
5445 // type, to give us better diagnostics.
5446 QualType SourceType = E->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +00005447 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005448 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5449 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
5450 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
5451 SourceType = S.Context.getTypeDeclType(Enum);
5452 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
5453 }
5454 }
5455
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005456 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
5457 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall83972f12013-03-09 00:54:27 +00005458 if (SourceEnum->getDecl()->hasNameForLinkage() &&
5459 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00005460 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005461 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005462 return;
5463
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005464 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005465 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005466 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005467
John McCall51313c32010-01-04 23:31:57 +00005468 return;
5469}
5470
David Blaikie9fb1ac52012-05-15 21:57:38 +00005471void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5472 SourceLocation CC, QualType T);
John McCall323ed742010-05-06 08:58:33 +00005473
5474void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00005475 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00005476 E = E->IgnoreParenImpCasts();
5477
5478 if (isa<ConditionalOperator>(E))
David Blaikie9fb1ac52012-05-15 21:57:38 +00005479 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCall323ed742010-05-06 08:58:33 +00005480
John McCallb4eb64d2010-10-08 02:01:28 +00005481 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005482 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00005483 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00005484 return;
5485}
5486
David Blaikie9fb1ac52012-05-15 21:57:38 +00005487void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5488 SourceLocation CC, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00005489 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00005490
5491 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00005492 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
5493 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00005494
5495 // If -Wconversion would have warned about either of the candidates
5496 // for a signedness conversion to the context type...
5497 if (!Suspicious) return;
5498
5499 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005500 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
5501 CC))
John McCall323ed742010-05-06 08:58:33 +00005502 return;
5503
John McCall323ed742010-05-06 08:58:33 +00005504 // ...then check whether it would have warned about either of the
5505 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00005506 if (E->getType() == T) return;
5507
5508 Suspicious = false;
5509 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
5510 E->getType(), CC, &Suspicious);
5511 if (!Suspicious)
5512 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00005513 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00005514}
5515
5516/// AnalyzeImplicitConversions - Find and report any interesting
5517/// implicit conversions in the given expression. There are a couple
5518/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00005519void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00005520 QualType T = OrigE->getType();
5521 Expr *E = OrigE->IgnoreParenImpCasts();
5522
Douglas Gregorf8b6e152011-10-10 17:38:18 +00005523 if (E->isTypeDependent() || E->isValueDependent())
5524 return;
5525
John McCall323ed742010-05-06 08:58:33 +00005526 // For conditional operators, we analyze the arguments as if they
5527 // were being fed directly into the output.
5528 if (isa<ConditionalOperator>(E)) {
5529 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie9fb1ac52012-05-15 21:57:38 +00005530 CheckConditionalOperator(S, CO, CC, T);
John McCall323ed742010-05-06 08:58:33 +00005531 return;
5532 }
5533
Hans Wennborg88617a22012-08-28 15:44:30 +00005534 // Check implicit argument conversions for function calls.
5535 if (CallExpr *Call = dyn_cast<CallExpr>(E))
5536 CheckImplicitArgumentConversions(S, Call, CC);
5537
John McCall323ed742010-05-06 08:58:33 +00005538 // Go ahead and check any implicit conversions we might have skipped.
5539 // The non-canonical typecheck is just an optimization;
5540 // CheckImplicitConversion will filter out dead implicit conversions.
5541 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00005542 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00005543
5544 // Now continue drilling into this expression.
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00005545
5546 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00005547 if (POE->getResultExpr())
5548 E = POE->getResultExpr();
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00005549 }
5550
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00005551 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5552 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
5553
John McCall323ed742010-05-06 08:58:33 +00005554 // Skip past explicit casts.
5555 if (isa<ExplicitCastExpr>(E)) {
5556 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00005557 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005558 }
5559
John McCallbeb22aa2010-11-09 23:24:47 +00005560 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5561 // Do a somewhat different check with comparison operators.
5562 if (BO->isComparisonOp())
5563 return AnalyzeComparison(S, BO);
5564
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005565 // And with simple assignments.
5566 if (BO->getOpcode() == BO_Assign)
John McCallbeb22aa2010-11-09 23:24:47 +00005567 return AnalyzeAssignment(S, BO);
5568 }
John McCall323ed742010-05-06 08:58:33 +00005569
5570 // These break the otherwise-useful invariant below. Fortunately,
5571 // we don't really need to recurse into them, because any internal
5572 // expressions should have been analyzed already when they were
5573 // built into statements.
5574 if (isa<StmtExpr>(E)) return;
5575
5576 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005577 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00005578
5579 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00005580 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005581 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
5582 bool IsLogicalOperator = BO && BO->isLogicalOp();
5583 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor54042f12012-02-09 10:18:50 +00005584 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor503384f2012-02-09 00:47:04 +00005585 if (!ChildExpr)
5586 continue;
5587
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005588 if (IsLogicalOperator &&
5589 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
5590 // Ignore checking string literals that are in logical operators.
5591 continue;
5592 AnalyzeImplicitConversions(S, ChildExpr, CC);
5593 }
John McCall323ed742010-05-06 08:58:33 +00005594}
5595
5596} // end anonymous namespace
5597
5598/// Diagnoses "dangerous" implicit conversions within the given
5599/// expression (which is a full expression). Implements -Wconversion
5600/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00005601///
5602/// \param CC the "context" location of the implicit conversion, i.e.
5603/// the most location of the syntactic entity requiring the implicit
5604/// conversion
5605void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00005606 // Don't diagnose in unevaluated contexts.
David Blaikie71f55f72012-08-06 22:47:24 +00005607 if (isUnevaluatedContext())
John McCall323ed742010-05-06 08:58:33 +00005608 return;
5609
5610 // Don't diagnose for value- or type-dependent expressions.
5611 if (E->isTypeDependent() || E->isValueDependent())
5612 return;
5613
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005614 // Check for array bounds violations in cases where the check isn't triggered
5615 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
5616 // ArraySubscriptExpr is on the RHS of a variable initialization.
5617 CheckArrayAccess(E);
5618
John McCallb4eb64d2010-10-08 02:01:28 +00005619 // This is not the right CC for (e.g.) a variable initialization.
5620 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005621}
5622
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005623/// Diagnose when expression is an integer constant expression and its evaluation
5624/// results in integer overflow
5625void Sema::CheckForIntOverflow (Expr *E) {
Richard Smith00043292013-11-05 22:23:30 +00005626 if (isa<BinaryOperator>(E->IgnoreParens()))
5627 E->EvaluateForOverflow(Context);
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005628}
5629
Richard Smith6c3af3d2013-01-17 01:17:56 +00005630namespace {
5631/// \brief Visitor for expressions which looks for unsequenced operations on the
5632/// same object.
5633class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smith0c0b3902013-06-30 10:40:20 +00005634 typedef EvaluatedExprVisitor<SequenceChecker> Base;
5635
Richard Smith6c3af3d2013-01-17 01:17:56 +00005636 /// \brief A tree of sequenced regions within an expression. Two regions are
5637 /// unsequenced if one is an ancestor or a descendent of the other. When we
5638 /// finish processing an expression with sequencing, such as a comma
5639 /// expression, we fold its tree nodes into its parent, since they are
5640 /// unsequenced with respect to nodes we will visit later.
5641 class SequenceTree {
5642 struct Value {
5643 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
5644 unsigned Parent : 31;
5645 bool Merged : 1;
5646 };
Robert Wilhelme7205c02013-08-10 12:33:24 +00005647 SmallVector<Value, 8> Values;
Richard Smith6c3af3d2013-01-17 01:17:56 +00005648
5649 public:
5650 /// \brief A region within an expression which may be sequenced with respect
5651 /// to some other region.
5652 class Seq {
5653 explicit Seq(unsigned N) : Index(N) {}
5654 unsigned Index;
5655 friend class SequenceTree;
5656 public:
5657 Seq() : Index(0) {}
5658 };
5659
5660 SequenceTree() { Values.push_back(Value(0)); }
5661 Seq root() const { return Seq(0); }
5662
5663 /// \brief Create a new sequence of operations, which is an unsequenced
5664 /// subset of \p Parent. This sequence of operations is sequenced with
5665 /// respect to other children of \p Parent.
5666 Seq allocate(Seq Parent) {
5667 Values.push_back(Value(Parent.Index));
5668 return Seq(Values.size() - 1);
5669 }
5670
5671 /// \brief Merge a sequence of operations into its parent.
5672 void merge(Seq S) {
5673 Values[S.Index].Merged = true;
5674 }
5675
5676 /// \brief Determine whether two operations are unsequenced. This operation
5677 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
5678 /// should have been merged into its parent as appropriate.
5679 bool isUnsequenced(Seq Cur, Seq Old) {
5680 unsigned C = representative(Cur.Index);
5681 unsigned Target = representative(Old.Index);
5682 while (C >= Target) {
5683 if (C == Target)
5684 return true;
5685 C = Values[C].Parent;
5686 }
5687 return false;
5688 }
5689
5690 private:
5691 /// \brief Pick a representative for a sequence.
5692 unsigned representative(unsigned K) {
5693 if (Values[K].Merged)
5694 // Perform path compression as we go.
5695 return Values[K].Parent = representative(Values[K].Parent);
5696 return K;
5697 }
5698 };
5699
5700 /// An object for which we can track unsequenced uses.
5701 typedef NamedDecl *Object;
5702
5703 /// Different flavors of object usage which we track. We only track the
5704 /// least-sequenced usage of each kind.
5705 enum UsageKind {
5706 /// A read of an object. Multiple unsequenced reads are OK.
5707 UK_Use,
5708 /// A modification of an object which is sequenced before the value
Richard Smith418dd3e2013-06-26 23:16:51 +00005709 /// computation of the expression, such as ++n in C++.
Richard Smith6c3af3d2013-01-17 01:17:56 +00005710 UK_ModAsValue,
5711 /// A modification of an object which is not sequenced before the value
5712 /// computation of the expression, such as n++.
5713 UK_ModAsSideEffect,
5714
5715 UK_Count = UK_ModAsSideEffect + 1
5716 };
5717
5718 struct Usage {
5719 Usage() : Use(0), Seq() {}
5720 Expr *Use;
5721 SequenceTree::Seq Seq;
5722 };
5723
5724 struct UsageInfo {
5725 UsageInfo() : Diagnosed(false) {}
5726 Usage Uses[UK_Count];
5727 /// Have we issued a diagnostic for this variable already?
5728 bool Diagnosed;
5729 };
5730 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
5731
5732 Sema &SemaRef;
5733 /// Sequenced regions within the expression.
5734 SequenceTree Tree;
5735 /// Declaration modifications and references which we have seen.
5736 UsageInfoMap UsageMap;
5737 /// The region we are currently within.
5738 SequenceTree::Seq Region;
5739 /// Filled in with declarations which were modified as a side-effect
5740 /// (that is, post-increment operations).
Robert Wilhelme7205c02013-08-10 12:33:24 +00005741 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smith1a2dcd52013-01-17 23:18:09 +00005742 /// Expressions to check later. We defer checking these to reduce
5743 /// stack usage.
Robert Wilhelme7205c02013-08-10 12:33:24 +00005744 SmallVectorImpl<Expr *> &WorkList;
Richard Smith6c3af3d2013-01-17 01:17:56 +00005745
5746 /// RAII object wrapping the visitation of a sequenced subexpression of an
5747 /// expression. At the end of this process, the side-effects of the evaluation
5748 /// become sequenced with respect to the value computation of the result, so
5749 /// we downgrade any UK_ModAsSideEffect within the evaluation to
5750 /// UK_ModAsValue.
5751 struct SequencedSubexpression {
5752 SequencedSubexpression(SequenceChecker &Self)
5753 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
5754 Self.ModAsSideEffect = &ModAsSideEffect;
5755 }
5756 ~SequencedSubexpression() {
5757 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
5758 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
5759 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
5760 Self.addUsage(U, ModAsSideEffect[I].first,
5761 ModAsSideEffect[I].second.Use, UK_ModAsValue);
5762 }
5763 Self.ModAsSideEffect = OldModAsSideEffect;
5764 }
5765
5766 SequenceChecker &Self;
Robert Wilhelme7205c02013-08-10 12:33:24 +00005767 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
5768 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smith6c3af3d2013-01-17 01:17:56 +00005769 };
5770
Richard Smith67470052013-06-20 22:21:56 +00005771 /// RAII object wrapping the visitation of a subexpression which we might
5772 /// choose to evaluate as a constant. If any subexpression is evaluated and
5773 /// found to be non-constant, this allows us to suppress the evaluation of
5774 /// the outer expression.
5775 class EvaluationTracker {
5776 public:
5777 EvaluationTracker(SequenceChecker &Self)
5778 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
5779 Self.EvalTracker = this;
5780 }
5781 ~EvaluationTracker() {
5782 Self.EvalTracker = Prev;
5783 if (Prev)
5784 Prev->EvalOK &= EvalOK;
5785 }
5786
5787 bool evaluate(const Expr *E, bool &Result) {
5788 if (!EvalOK || E->isValueDependent())
5789 return false;
5790 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
5791 return EvalOK;
5792 }
5793
5794 private:
5795 SequenceChecker &Self;
5796 EvaluationTracker *Prev;
5797 bool EvalOK;
5798 } *EvalTracker;
5799
Richard Smith6c3af3d2013-01-17 01:17:56 +00005800 /// \brief Find the object which is produced by the specified expression,
5801 /// if any.
5802 Object getObject(Expr *E, bool Mod) const {
5803 E = E->IgnoreParenCasts();
5804 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5805 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
5806 return getObject(UO->getSubExpr(), Mod);
5807 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5808 if (BO->getOpcode() == BO_Comma)
5809 return getObject(BO->getRHS(), Mod);
5810 if (Mod && BO->isAssignmentOp())
5811 return getObject(BO->getLHS(), Mod);
5812 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
5813 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
5814 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
5815 return ME->getMemberDecl();
5816 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5817 // FIXME: If this is a reference, map through to its value.
5818 return DRE->getDecl();
5819 return 0;
5820 }
5821
5822 /// \brief Note that an object was modified or used by an expression.
5823 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
5824 Usage &U = UI.Uses[UK];
5825 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
5826 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
5827 ModAsSideEffect->push_back(std::make_pair(O, U));
5828 U.Use = Ref;
5829 U.Seq = Region;
5830 }
5831 }
5832 /// \brief Check whether a modification or use conflicts with a prior usage.
5833 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
5834 bool IsModMod) {
5835 if (UI.Diagnosed)
5836 return;
5837
5838 const Usage &U = UI.Uses[OtherKind];
5839 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
5840 return;
5841
5842 Expr *Mod = U.Use;
5843 Expr *ModOrUse = Ref;
5844 if (OtherKind == UK_Use)
5845 std::swap(Mod, ModOrUse);
5846
5847 SemaRef.Diag(Mod->getExprLoc(),
5848 IsModMod ? diag::warn_unsequenced_mod_mod
5849 : diag::warn_unsequenced_mod_use)
5850 << O << SourceRange(ModOrUse->getExprLoc());
5851 UI.Diagnosed = true;
5852 }
5853
5854 void notePreUse(Object O, Expr *Use) {
5855 UsageInfo &U = UsageMap[O];
5856 // Uses conflict with other modifications.
5857 checkUsage(O, U, Use, UK_ModAsValue, false);
5858 }
5859 void notePostUse(Object O, Expr *Use) {
5860 UsageInfo &U = UsageMap[O];
5861 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
5862 addUsage(U, O, Use, UK_Use);
5863 }
5864
5865 void notePreMod(Object O, Expr *Mod) {
5866 UsageInfo &U = UsageMap[O];
5867 // Modifications conflict with other modifications and with uses.
5868 checkUsage(O, U, Mod, UK_ModAsValue, true);
5869 checkUsage(O, U, Mod, UK_Use, false);
5870 }
5871 void notePostMod(Object O, Expr *Use, UsageKind UK) {
5872 UsageInfo &U = UsageMap[O];
5873 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
5874 addUsage(U, O, Use, UK);
5875 }
5876
5877public:
Robert Wilhelme7205c02013-08-10 12:33:24 +00005878 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
5879 : Base(S.Context), SemaRef(S), Region(Tree.root()), ModAsSideEffect(0),
5880 WorkList(WorkList), EvalTracker(0) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00005881 Visit(E);
5882 }
5883
5884 void VisitStmt(Stmt *S) {
5885 // Skip all statements which aren't expressions for now.
5886 }
5887
5888 void VisitExpr(Expr *E) {
5889 // By default, just recurse to evaluated subexpressions.
Richard Smith0c0b3902013-06-30 10:40:20 +00005890 Base::VisitStmt(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005891 }
5892
5893 void VisitCastExpr(CastExpr *E) {
5894 Object O = Object();
5895 if (E->getCastKind() == CK_LValueToRValue)
5896 O = getObject(E->getSubExpr(), false);
5897
5898 if (O)
5899 notePreUse(O, E);
5900 VisitExpr(E);
5901 if (O)
5902 notePostUse(O, E);
5903 }
5904
5905 void VisitBinComma(BinaryOperator *BO) {
5906 // C++11 [expr.comma]p1:
5907 // Every value computation and side effect associated with the left
5908 // expression is sequenced before every value computation and side
5909 // effect associated with the right expression.
5910 SequenceTree::Seq LHS = Tree.allocate(Region);
5911 SequenceTree::Seq RHS = Tree.allocate(Region);
5912 SequenceTree::Seq OldRegion = Region;
5913
5914 {
5915 SequencedSubexpression SeqLHS(*this);
5916 Region = LHS;
5917 Visit(BO->getLHS());
5918 }
5919
5920 Region = RHS;
5921 Visit(BO->getRHS());
5922
5923 Region = OldRegion;
5924
5925 // Forget that LHS and RHS are sequenced. They are both unsequenced
5926 // with respect to other stuff.
5927 Tree.merge(LHS);
5928 Tree.merge(RHS);
5929 }
5930
5931 void VisitBinAssign(BinaryOperator *BO) {
5932 // The modification is sequenced after the value computation of the LHS
5933 // and RHS, so check it before inspecting the operands and update the
5934 // map afterwards.
5935 Object O = getObject(BO->getLHS(), true);
5936 if (!O)
5937 return VisitExpr(BO);
5938
5939 notePreMod(O, BO);
5940
5941 // C++11 [expr.ass]p7:
5942 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
5943 // only once.
5944 //
5945 // Therefore, for a compound assignment operator, O is considered used
5946 // everywhere except within the evaluation of E1 itself.
5947 if (isa<CompoundAssignOperator>(BO))
5948 notePreUse(O, BO);
5949
5950 Visit(BO->getLHS());
5951
5952 if (isa<CompoundAssignOperator>(BO))
5953 notePostUse(O, BO);
5954
5955 Visit(BO->getRHS());
5956
Richard Smith418dd3e2013-06-26 23:16:51 +00005957 // C++11 [expr.ass]p1:
5958 // the assignment is sequenced [...] before the value computation of the
5959 // assignment expression.
5960 // C11 6.5.16/3 has no such rule.
5961 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
5962 : UK_ModAsSideEffect);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005963 }
5964 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
5965 VisitBinAssign(CAO);
5966 }
5967
5968 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
5969 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
5970 void VisitUnaryPreIncDec(UnaryOperator *UO) {
5971 Object O = getObject(UO->getSubExpr(), true);
5972 if (!O)
5973 return VisitExpr(UO);
5974
5975 notePreMod(O, UO);
5976 Visit(UO->getSubExpr());
Richard Smith418dd3e2013-06-26 23:16:51 +00005977 // C++11 [expr.pre.incr]p1:
5978 // the expression ++x is equivalent to x+=1
5979 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
5980 : UK_ModAsSideEffect);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005981 }
5982
5983 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
5984 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
5985 void VisitUnaryPostIncDec(UnaryOperator *UO) {
5986 Object O = getObject(UO->getSubExpr(), true);
5987 if (!O)
5988 return VisitExpr(UO);
5989
5990 notePreMod(O, UO);
5991 Visit(UO->getSubExpr());
5992 notePostMod(O, UO, UK_ModAsSideEffect);
5993 }
5994
5995 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
5996 void VisitBinLOr(BinaryOperator *BO) {
5997 // The side-effects of the LHS of an '&&' are sequenced before the
5998 // value computation of the RHS, and hence before the value computation
5999 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
6000 // as if they were unconditionally sequenced.
Richard Smith67470052013-06-20 22:21:56 +00006001 EvaluationTracker Eval(*this);
Richard Smith6c3af3d2013-01-17 01:17:56 +00006002 {
6003 SequencedSubexpression Sequenced(*this);
6004 Visit(BO->getLHS());
6005 }
6006
6007 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00006008 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith995e4a72013-01-17 22:06:26 +00006009 if (!Result)
6010 Visit(BO->getRHS());
6011 } else {
6012 // Check for unsequenced operations in the RHS, treating it as an
6013 // entirely separate evaluation.
6014 //
6015 // FIXME: If there are operations in the RHS which are unsequenced
6016 // with respect to operations outside the RHS, and those operations
6017 // are unconditionally evaluated, diagnose them.
Richard Smith1a2dcd52013-01-17 23:18:09 +00006018 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00006019 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00006020 }
6021 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith67470052013-06-20 22:21:56 +00006022 EvaluationTracker Eval(*this);
Richard Smith6c3af3d2013-01-17 01:17:56 +00006023 {
6024 SequencedSubexpression Sequenced(*this);
6025 Visit(BO->getLHS());
6026 }
6027
6028 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00006029 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith995e4a72013-01-17 22:06:26 +00006030 if (Result)
6031 Visit(BO->getRHS());
6032 } else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00006033 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00006034 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00006035 }
6036
6037 // Only visit the condition, unless we can be sure which subexpression will
6038 // be chosen.
6039 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith67470052013-06-20 22:21:56 +00006040 EvaluationTracker Eval(*this);
Richard Smith418dd3e2013-06-26 23:16:51 +00006041 {
6042 SequencedSubexpression Sequenced(*this);
6043 Visit(CO->getCond());
6044 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00006045
6046 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00006047 if (Eval.evaluate(CO->getCond(), Result))
Richard Smith6c3af3d2013-01-17 01:17:56 +00006048 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00006049 else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00006050 WorkList.push_back(CO->getTrueExpr());
6051 WorkList.push_back(CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00006052 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00006053 }
6054
Richard Smith0c0b3902013-06-30 10:40:20 +00006055 void VisitCallExpr(CallExpr *CE) {
6056 // C++11 [intro.execution]p15:
6057 // When calling a function [...], every value computation and side effect
6058 // associated with any argument expression, or with the postfix expression
6059 // designating the called function, is sequenced before execution of every
6060 // expression or statement in the body of the function [and thus before
6061 // the value computation of its result].
6062 SequencedSubexpression Sequenced(*this);
6063 Base::VisitCallExpr(CE);
6064
6065 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
6066 }
6067
Richard Smith6c3af3d2013-01-17 01:17:56 +00006068 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smith0c0b3902013-06-30 10:40:20 +00006069 // This is a call, so all subexpressions are sequenced before the result.
6070 SequencedSubexpression Sequenced(*this);
6071
Richard Smith6c3af3d2013-01-17 01:17:56 +00006072 if (!CCE->isListInitialization())
6073 return VisitExpr(CCE);
6074
6075 // In C++11, list initializations are sequenced.
Robert Wilhelme7205c02013-08-10 12:33:24 +00006076 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smith6c3af3d2013-01-17 01:17:56 +00006077 SequenceTree::Seq Parent = Region;
6078 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
6079 E = CCE->arg_end();
6080 I != E; ++I) {
6081 Region = Tree.allocate(Parent);
6082 Elts.push_back(Region);
6083 Visit(*I);
6084 }
6085
6086 // Forget that the initializers are sequenced.
6087 Region = Parent;
6088 for (unsigned I = 0; I < Elts.size(); ++I)
6089 Tree.merge(Elts[I]);
6090 }
6091
6092 void VisitInitListExpr(InitListExpr *ILE) {
6093 if (!SemaRef.getLangOpts().CPlusPlus11)
6094 return VisitExpr(ILE);
6095
6096 // In C++11, list initializations are sequenced.
Robert Wilhelme7205c02013-08-10 12:33:24 +00006097 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smith6c3af3d2013-01-17 01:17:56 +00006098 SequenceTree::Seq Parent = Region;
6099 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
6100 Expr *E = ILE->getInit(I);
6101 if (!E) continue;
6102 Region = Tree.allocate(Parent);
6103 Elts.push_back(Region);
6104 Visit(E);
6105 }
6106
6107 // Forget that the initializers are sequenced.
6108 Region = Parent;
6109 for (unsigned I = 0; I < Elts.size(); ++I)
6110 Tree.merge(Elts[I]);
6111 }
6112};
6113}
6114
6115void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelme7205c02013-08-10 12:33:24 +00006116 SmallVector<Expr *, 8> WorkList;
Richard Smith1a2dcd52013-01-17 23:18:09 +00006117 WorkList.push_back(E);
6118 while (!WorkList.empty()) {
Robert Wilhelm344472e2013-08-23 16:11:15 +00006119 Expr *Item = WorkList.pop_back_val();
Richard Smith1a2dcd52013-01-17 23:18:09 +00006120 SequenceChecker(*this, Item, WorkList);
6121 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00006122}
6123
Fariborz Jahanianad48a502013-01-24 22:11:45 +00006124void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
6125 bool IsConstexpr) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00006126 CheckImplicitConversions(E, CheckLoc);
6127 CheckUnsequencedOperations(E);
Fariborz Jahanianad48a502013-01-24 22:11:45 +00006128 if (!IsConstexpr && !E->isValueDependent())
6129 CheckForIntOverflow(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00006130}
6131
John McCall15d7d122010-11-11 03:21:53 +00006132void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
6133 FieldDecl *BitField,
6134 Expr *Init) {
6135 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
6136}
6137
Mike Stumpf8c49212010-01-21 03:59:47 +00006138/// CheckParmsForFunctionDef - Check that the parameters of the given
6139/// function are appropriate for the definition of a function. This
6140/// takes care of any checks that cannot be performed on the
6141/// declaration itself, e.g., that the types of each of the function
6142/// parameters are complete.
Reid Kleckner8c0501c2013-06-24 14:38:26 +00006143bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
6144 ParmVarDecl *const *PEnd,
Douglas Gregor82aa7132010-11-01 18:37:59 +00006145 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00006146 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00006147 for (; P != PEnd; ++P) {
6148 ParmVarDecl *Param = *P;
6149
Mike Stumpf8c49212010-01-21 03:59:47 +00006150 // C99 6.7.5.3p4: the parameters in a parameter type list in a
6151 // function declarator that is part of a function definition of
6152 // that function shall not have incomplete type.
6153 //
6154 // This is also C++ [dcl.fct]p6.
6155 if (!Param->isInvalidDecl() &&
6156 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00006157 diag::err_typecheck_decl_incomplete_type)) {
Mike Stumpf8c49212010-01-21 03:59:47 +00006158 Param->setInvalidDecl();
6159 HasInvalidParm = true;
6160 }
6161
6162 // C99 6.9.1p5: If the declarator includes a parameter type list, the
6163 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00006164 if (CheckParameterNames &&
6165 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00006166 !Param->isImplicit() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006167 !getLangOpts().CPlusPlus)
Mike Stumpf8c49212010-01-21 03:59:47 +00006168 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00006169
6170 // C99 6.7.5.3p12:
6171 // If the function declarator is not part of a definition of that
6172 // function, parameters may have incomplete type and may use the [*]
6173 // notation in their sequences of declarator specifiers to specify
6174 // variable length array types.
6175 QualType PType = Param->getOriginalType();
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00006176 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigd17e3402010-02-01 05:02:49 +00006177 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitfc093362013-03-01 21:41:22 +00006178 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigd17e3402010-02-01 05:02:49 +00006179 // information is added for it.
6180 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00006181 break;
Sam Weinigd17e3402010-02-01 05:02:49 +00006182 }
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00006183 PType= AT->getElementType();
Sam Weinigd17e3402010-02-01 05:02:49 +00006184 }
Reid Kleckner9b601952013-06-21 12:45:15 +00006185
6186 // MSVC destroys objects passed by value in the callee. Therefore a
6187 // function definition which takes such a parameter must be able to call the
6188 // object's destructor.
6189 if (getLangOpts().CPlusPlus &&
6190 Context.getTargetInfo().getCXXABI().isArgumentDestroyedByCallee()) {
6191 if (const RecordType *RT = Param->getType()->getAs<RecordType>())
6192 FinalizeVarWithDestructor(Param, RT);
6193 }
Mike Stumpf8c49212010-01-21 03:59:47 +00006194 }
6195
6196 return HasInvalidParm;
6197}
John McCallb7f4ffe2010-08-12 21:44:57 +00006198
6199/// CheckCastAlign - Implements -Wcast-align, which warns when a
6200/// pointer cast increases the alignment requirements.
6201void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
6202 // This is actually a lot of work to potentially be doing on every
6203 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00006204 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
6205 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00006206 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00006207 return;
6208
6209 // Ignore dependent types.
6210 if (T->isDependentType() || Op->getType()->isDependentType())
6211 return;
6212
6213 // Require that the destination be a pointer type.
6214 const PointerType *DestPtr = T->getAs<PointerType>();
6215 if (!DestPtr) return;
6216
6217 // If the destination has alignment 1, we're done.
6218 QualType DestPointee = DestPtr->getPointeeType();
6219 if (DestPointee->isIncompleteType()) return;
6220 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
6221 if (DestAlign.isOne()) return;
6222
6223 // Require that the source be a pointer type.
6224 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
6225 if (!SrcPtr) return;
6226 QualType SrcPointee = SrcPtr->getPointeeType();
6227
6228 // Whitelist casts from cv void*. We already implicitly
6229 // whitelisted casts to cv void*, since they have alignment 1.
6230 // Also whitelist casts involving incomplete types, which implicitly
6231 // includes 'void'.
6232 if (SrcPointee->isIncompleteType()) return;
6233
6234 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
6235 if (SrcAlign >= DestAlign) return;
6236
6237 Diag(TRange.getBegin(), diag::warn_cast_align)
6238 << Op->getType() << T
6239 << static_cast<unsigned>(SrcAlign.getQuantity())
6240 << static_cast<unsigned>(DestAlign.getQuantity())
6241 << TRange << Op->getSourceRange();
6242}
6243
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006244static const Type* getElementType(const Expr *BaseExpr) {
6245 const Type* EltType = BaseExpr->getType().getTypePtr();
6246 if (EltType->isAnyPointerType())
6247 return EltType->getPointeeType().getTypePtr();
6248 else if (EltType->isArrayType())
6249 return EltType->getBaseElementTypeUnsafe();
6250 return EltType;
6251}
6252
Chandler Carruthc2684342011-08-05 09:10:50 +00006253/// \brief Check whether this array fits the idiom of a size-one tail padded
6254/// array member of a struct.
6255///
6256/// We avoid emitting out-of-bounds access warnings for such arrays as they are
6257/// commonly used to emulate flexible arrays in C89 code.
6258static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
6259 const NamedDecl *ND) {
6260 if (Size != 1 || !ND) return false;
6261
6262 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
6263 if (!FD) return false;
6264
6265 // Don't consider sizes resulting from macro expansions or template argument
6266 // substitution to form C89 tail-padded arrays.
Sean Callanand2cf3482012-05-04 18:22:53 +00006267
6268 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00006269 while (TInfo) {
6270 TypeLoc TL = TInfo->getTypeLoc();
6271 // Look through typedefs.
David Blaikie39e6ab42013-02-18 22:06:02 +00006272 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
6273 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00006274 TInfo = TDL->getTypeSourceInfo();
6275 continue;
6276 }
David Blaikie39e6ab42013-02-18 22:06:02 +00006277 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
6278 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier5e253012013-02-06 00:58:34 +00006279 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
6280 return false;
6281 }
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00006282 break;
Sean Callanand2cf3482012-05-04 18:22:53 +00006283 }
Chandler Carruthc2684342011-08-05 09:10:50 +00006284
6285 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00006286 if (!RD) return false;
6287 if (RD->isUnion()) return false;
6288 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
6289 if (!CRD->isStandardLayout()) return false;
6290 }
Chandler Carruthc2684342011-08-05 09:10:50 +00006291
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00006292 // See if this is the last field decl in the record.
6293 const Decl *D = FD;
6294 while ((D = D->getNextDeclInContext()))
6295 if (isa<FieldDecl>(D))
6296 return false;
6297 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00006298}
6299
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006300void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006301 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00006302 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman92b670e2012-02-27 21:21:40 +00006303 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006304 if (IndexExpr->isValueDependent())
6305 return;
6306
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00006307 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006308 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00006309 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006310 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00006311 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00006312 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00006313
Chandler Carruth34064582011-02-17 20:55:08 +00006314 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006315 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00006316 return;
Richard Smith25b009a2011-12-16 19:31:14 +00006317 if (IndexNegated)
6318 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00006319
Chandler Carruthba447122011-08-05 08:07:29 +00006320 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00006321 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6322 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00006323 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00006324 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00006325
Ted Kremenek9e060ca2011-02-23 23:06:04 +00006326 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00006327 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00006328 if (!size.isStrictlyPositive())
6329 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006330
6331 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00006332 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006333 // Make sure we're comparing apples to apples when comparing index to size
6334 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
6335 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00006336 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00006337 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006338 if (ptrarith_typesize != array_typesize) {
6339 // There's a cast to a different size type involved
6340 uint64_t ratio = array_typesize / ptrarith_typesize;
6341 // TODO: Be smarter about handling cases where array_typesize is not a
6342 // multiple of ptrarith_typesize
6343 if (ptrarith_typesize * ratio == array_typesize)
6344 size *= llvm::APInt(size.getBitWidth(), ratio);
6345 }
6346 }
6347
Chandler Carruth34064582011-02-17 20:55:08 +00006348 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00006349 index = index.zext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00006350 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00006351 size = size.zext(index.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00006352
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006353 // For array subscripting the index must be less than size, but for pointer
6354 // arithmetic also allow the index (offset) to be equal to size since
6355 // computing the next address after the end of the array is legal and
6356 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman92b670e2012-02-27 21:21:40 +00006357 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruthba447122011-08-05 08:07:29 +00006358 return;
6359
6360 // Also don't warn for arrays of size 1 which are members of some
6361 // structure. These are often used to approximate flexible arrays in C89
6362 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006363 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00006364 return;
Chandler Carruth34064582011-02-17 20:55:08 +00006365
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006366 // Suppress the warning if the subscript expression (as identified by the
6367 // ']' location) and the index expression are both from macro expansions
6368 // within a system header.
6369 if (ASE) {
6370 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
6371 ASE->getRBracketLoc());
6372 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
6373 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
6374 IndexExpr->getLocStart());
Eli Friedman24146972013-08-22 00:27:10 +00006375 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006376 return;
6377 }
6378 }
6379
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006380 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006381 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006382 DiagID = diag::warn_array_index_exceeds_bounds;
6383
6384 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6385 PDiag(DiagID) << index.toString(10, true)
6386 << size.toString(10, true)
6387 << (unsigned)size.getLimitedValue(~0U)
6388 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00006389 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006390 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006391 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006392 DiagID = diag::warn_ptr_arith_precedes_bounds;
6393 if (index.isNegative()) index = -index;
6394 }
6395
6396 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6397 PDiag(DiagID) << index.toString(10, true)
6398 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00006399 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00006400
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00006401 if (!ND) {
6402 // Try harder to find a NamedDecl to point at in the note.
6403 while (const ArraySubscriptExpr *ASE =
6404 dyn_cast<ArraySubscriptExpr>(BaseExpr))
6405 BaseExpr = ASE->getBase()->IgnoreParenCasts();
6406 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6407 ND = dyn_cast<NamedDecl>(DRE->getDecl());
6408 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
6409 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
6410 }
6411
Chandler Carruth35001ca2011-02-17 21:10:52 +00006412 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006413 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
6414 PDiag(diag::note_array_index_out_of_bounds)
6415 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00006416}
6417
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006418void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006419 int AllowOnePastEnd = 0;
6420 while (expr) {
6421 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006422 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006423 case Stmt::ArraySubscriptExprClass: {
6424 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006425 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006426 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006427 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006428 }
6429 case Stmt::UnaryOperatorClass: {
6430 // Only unwrap the * and & unary operators
6431 const UnaryOperator *UO = cast<UnaryOperator>(expr);
6432 expr = UO->getSubExpr();
6433 switch (UO->getOpcode()) {
6434 case UO_AddrOf:
6435 AllowOnePastEnd++;
6436 break;
6437 case UO_Deref:
6438 AllowOnePastEnd--;
6439 break;
6440 default:
6441 return;
6442 }
6443 break;
6444 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006445 case Stmt::ConditionalOperatorClass: {
6446 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
6447 if (const Expr *lhs = cond->getLHS())
6448 CheckArrayAccess(lhs);
6449 if (const Expr *rhs = cond->getRHS())
6450 CheckArrayAccess(rhs);
6451 return;
6452 }
6453 default:
6454 return;
6455 }
Peter Collingbournef111d932011-04-15 00:35:48 +00006456 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006457}
John McCallf85e1932011-06-15 23:02:42 +00006458
6459//===--- CHECK: Objective-C retain cycles ----------------------------------//
6460
6461namespace {
6462 struct RetainCycleOwner {
6463 RetainCycleOwner() : Variable(0), Indirect(false) {}
6464 VarDecl *Variable;
6465 SourceRange Range;
6466 SourceLocation Loc;
6467 bool Indirect;
6468
6469 void setLocsFrom(Expr *e) {
6470 Loc = e->getExprLoc();
6471 Range = e->getSourceRange();
6472 }
6473 };
6474}
6475
6476/// Consider whether capturing the given variable can possibly lead to
6477/// a retain cycle.
6478static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00006479 // In ARC, it's captured strongly iff the variable has __strong
John McCallf85e1932011-06-15 23:02:42 +00006480 // lifetime. In MRR, it's captured strongly if the variable is
6481 // __block and has an appropriate type.
6482 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6483 return false;
6484
6485 owner.Variable = var;
Jordan Rosee10f4d32012-09-15 02:48:31 +00006486 if (ref)
6487 owner.setLocsFrom(ref);
John McCallf85e1932011-06-15 23:02:42 +00006488 return true;
6489}
6490
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006491static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00006492 while (true) {
6493 e = e->IgnoreParens();
6494 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
6495 switch (cast->getCastKind()) {
6496 case CK_BitCast:
6497 case CK_LValueBitCast:
6498 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00006499 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00006500 e = cast->getSubExpr();
6501 continue;
6502
John McCallf85e1932011-06-15 23:02:42 +00006503 default:
6504 return false;
6505 }
6506 }
6507
6508 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
6509 ObjCIvarDecl *ivar = ref->getDecl();
6510 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6511 return false;
6512
6513 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006514 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00006515 return false;
6516
6517 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
6518 owner.Indirect = true;
6519 return true;
6520 }
6521
6522 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
6523 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
6524 if (!var) return false;
6525 return considerVariable(var, ref, owner);
6526 }
6527
John McCallf85e1932011-06-15 23:02:42 +00006528 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
6529 if (member->isArrow()) return false;
6530
6531 // Don't count this as an indirect ownership.
6532 e = member->getBase();
6533 continue;
6534 }
6535
John McCall4b9c2d22011-11-06 09:01:30 +00006536 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
6537 // Only pay attention to pseudo-objects on property references.
6538 ObjCPropertyRefExpr *pre
6539 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
6540 ->IgnoreParens());
6541 if (!pre) return false;
6542 if (pre->isImplicitProperty()) return false;
6543 ObjCPropertyDecl *property = pre->getExplicitProperty();
6544 if (!property->isRetaining() &&
6545 !(property->getPropertyIvarDecl() &&
6546 property->getPropertyIvarDecl()->getType()
6547 .getObjCLifetime() == Qualifiers::OCL_Strong))
6548 return false;
6549
6550 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006551 if (pre->isSuperReceiver()) {
6552 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
6553 if (!owner.Variable)
6554 return false;
6555 owner.Loc = pre->getLocation();
6556 owner.Range = pre->getSourceRange();
6557 return true;
6558 }
John McCall4b9c2d22011-11-06 09:01:30 +00006559 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
6560 ->getSourceExpr());
6561 continue;
6562 }
6563
John McCallf85e1932011-06-15 23:02:42 +00006564 // Array ivars?
6565
6566 return false;
6567 }
6568}
6569
6570namespace {
6571 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
6572 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
6573 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
6574 Variable(variable), Capturer(0) {}
6575
6576 VarDecl *Variable;
6577 Expr *Capturer;
6578
6579 void VisitDeclRefExpr(DeclRefExpr *ref) {
6580 if (ref->getDecl() == Variable && !Capturer)
6581 Capturer = ref;
6582 }
6583
John McCallf85e1932011-06-15 23:02:42 +00006584 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
6585 if (Capturer) return;
6586 Visit(ref->getBase());
6587 if (Capturer && ref->isFreeIvar())
6588 Capturer = ref;
6589 }
6590
6591 void VisitBlockExpr(BlockExpr *block) {
6592 // Look inside nested blocks
6593 if (block->getBlockDecl()->capturesVariable(Variable))
6594 Visit(block->getBlockDecl()->getBody());
6595 }
Fariborz Jahanian7e2e4c32012-08-31 20:04:47 +00006596
6597 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
6598 if (Capturer) return;
6599 if (OVE->getSourceExpr())
6600 Visit(OVE->getSourceExpr());
6601 }
John McCallf85e1932011-06-15 23:02:42 +00006602 };
6603}
6604
6605/// Check whether the given argument is a block which captures a
6606/// variable.
6607static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
6608 assert(owner.Variable && owner.Loc.isValid());
6609
6610 e = e->IgnoreParenCasts();
Jordan Rose1fac58a2012-09-17 17:54:30 +00006611
6612 // Look through [^{...} copy] and Block_copy(^{...}).
6613 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
6614 Selector Cmd = ME->getSelector();
6615 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
6616 e = ME->getInstanceReceiver();
6617 if (!e)
6618 return 0;
6619 e = e->IgnoreParenCasts();
6620 }
6621 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
6622 if (CE->getNumArgs() == 1) {
6623 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekd13eff62012-10-02 04:36:54 +00006624 if (Fn) {
6625 const IdentifierInfo *FnI = Fn->getIdentifier();
6626 if (FnI && FnI->isStr("_Block_copy")) {
6627 e = CE->getArg(0)->IgnoreParenCasts();
6628 }
6629 }
Jordan Rose1fac58a2012-09-17 17:54:30 +00006630 }
6631 }
6632
John McCallf85e1932011-06-15 23:02:42 +00006633 BlockExpr *block = dyn_cast<BlockExpr>(e);
6634 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
6635 return 0;
6636
6637 FindCaptureVisitor visitor(S.Context, owner.Variable);
6638 visitor.Visit(block->getBlockDecl()->getBody());
6639 return visitor.Capturer;
6640}
6641
6642static void diagnoseRetainCycle(Sema &S, Expr *capturer,
6643 RetainCycleOwner &owner) {
6644 assert(capturer);
6645 assert(owner.Variable && owner.Loc.isValid());
6646
6647 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
6648 << owner.Variable << capturer->getSourceRange();
6649 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
6650 << owner.Indirect << owner.Range;
6651}
6652
6653/// Check for a keyword selector that starts with the word 'add' or
6654/// 'set'.
6655static bool isSetterLikeSelector(Selector sel) {
6656 if (sel.isUnarySelector()) return false;
6657
Chris Lattner5f9e2722011-07-23 10:55:15 +00006658 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00006659 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00006660 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00006661 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00006662 else if (str.startswith("add")) {
6663 // Specially whitelist 'addOperationWithBlock:'.
6664 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
6665 return false;
6666 str = str.substr(3);
6667 }
John McCallf85e1932011-06-15 23:02:42 +00006668 else
6669 return false;
6670
6671 if (str.empty()) return true;
Jordan Rose3f6f51e2013-02-08 22:30:41 +00006672 return !isLowercase(str.front());
John McCallf85e1932011-06-15 23:02:42 +00006673}
6674
6675/// Check a message send to see if it's likely to cause a retain cycle.
6676void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
6677 // Only check instance methods whose selector looks like a setter.
6678 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
6679 return;
6680
6681 // Try to find a variable that the receiver is strongly owned by.
6682 RetainCycleOwner owner;
6683 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006684 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00006685 return;
6686 } else {
6687 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
6688 owner.Variable = getCurMethodDecl()->getSelfDecl();
6689 owner.Loc = msg->getSuperLoc();
6690 owner.Range = msg->getSuperLoc();
6691 }
6692
6693 // Check whether the receiver is captured by any of the arguments.
6694 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
6695 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
6696 return diagnoseRetainCycle(*this, capturer, owner);
6697}
6698
6699/// Check a property assign to see if it's likely to cause a retain cycle.
6700void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
6701 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006702 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00006703 return;
6704
6705 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
6706 diagnoseRetainCycle(*this, capturer, owner);
6707}
6708
Jordan Rosee10f4d32012-09-15 02:48:31 +00006709void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
6710 RetainCycleOwner Owner;
6711 if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
6712 return;
6713
6714 // Because we don't have an expression for the variable, we have to set the
6715 // location explicitly here.
6716 Owner.Loc = Var->getLocation();
6717 Owner.Range = Var->getSourceRange();
6718
6719 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
6720 diagnoseRetainCycle(*this, Capturer, Owner);
6721}
6722
Ted Kremenek9d084012012-12-21 08:04:28 +00006723static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
6724 Expr *RHS, bool isProperty) {
6725 // Check if RHS is an Objective-C object literal, which also can get
6726 // immediately zapped in a weak reference. Note that we explicitly
6727 // allow ObjCStringLiterals, since those are designed to never really die.
6728 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenekf530ff72012-12-21 21:59:39 +00006729
Ted Kremenekd3292c82012-12-21 22:46:35 +00006730 // This enum needs to match with the 'select' in
6731 // warn_objc_arc_literal_assign (off-by-1).
6732 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
6733 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
6734 return false;
Ted Kremenekf530ff72012-12-21 21:59:39 +00006735
6736 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenekd3292c82012-12-21 22:46:35 +00006737 << (unsigned) Kind
Ted Kremenek9d084012012-12-21 08:04:28 +00006738 << (isProperty ? 0 : 1)
6739 << RHS->getSourceRange();
Ted Kremenekf530ff72012-12-21 21:59:39 +00006740
6741 return true;
Ted Kremenek9d084012012-12-21 08:04:28 +00006742}
6743
Ted Kremenekb29b30f2012-12-21 19:45:30 +00006744static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
6745 Qualifiers::ObjCLifetime LT,
6746 Expr *RHS, bool isProperty) {
6747 // Strip off any implicit cast added to get to the one ARC-specific.
6748 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
6749 if (cast->getCastKind() == CK_ARCConsumeObject) {
6750 S.Diag(Loc, diag::warn_arc_retained_assign)
6751 << (LT == Qualifiers::OCL_ExplicitNone)
6752 << (isProperty ? 0 : 1)
6753 << RHS->getSourceRange();
6754 return true;
6755 }
6756 RHS = cast->getSubExpr();
6757 }
6758
6759 if (LT == Qualifiers::OCL_Weak &&
6760 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
6761 return true;
6762
6763 return false;
6764}
6765
Ted Kremenekb1ea5102012-12-21 08:04:20 +00006766bool Sema::checkUnsafeAssigns(SourceLocation Loc,
6767 QualType LHS, Expr *RHS) {
6768 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
6769
6770 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
6771 return false;
6772
6773 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
6774 return true;
6775
6776 return false;
6777}
6778
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006779void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
6780 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006781 QualType LHSType;
6782 // PropertyRef on LHS type need be directly obtained from
6783 // its declaration as it has a PsuedoType.
6784 ObjCPropertyRefExpr *PRE
6785 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
6786 if (PRE && !PRE->isImplicitProperty()) {
6787 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6788 if (PD)
6789 LHSType = PD->getType();
6790 }
6791
6792 if (LHSType.isNull())
6793 LHSType = LHS->getType();
Jordan Rose7a270482012-09-28 22:21:35 +00006794
6795 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
6796
6797 if (LT == Qualifiers::OCL_Weak) {
6798 DiagnosticsEngine::Level Level =
6799 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
6800 if (Level != DiagnosticsEngine::Ignored)
6801 getCurFunction()->markSafeWeakUse(LHS);
6802 }
6803
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006804 if (checkUnsafeAssigns(Loc, LHSType, RHS))
6805 return;
Jordan Rose7a270482012-09-28 22:21:35 +00006806
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006807 // FIXME. Check for other life times.
6808 if (LT != Qualifiers::OCL_None)
6809 return;
6810
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006811 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006812 if (PRE->isImplicitProperty())
6813 return;
6814 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6815 if (!PD)
6816 return;
6817
Bill Wendlingad017fa2012-12-20 19:22:21 +00006818 unsigned Attributes = PD->getPropertyAttributes();
6819 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006820 // when 'assign' attribute was not explicitly specified
6821 // by user, ignore it and rely on property type itself
6822 // for lifetime info.
6823 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
6824 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
6825 LHSType->isObjCRetainableType())
6826 return;
6827
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006828 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00006829 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006830 Diag(Loc, diag::warn_arc_retained_property_assign)
6831 << RHS->getSourceRange();
6832 return;
6833 }
6834 RHS = cast->getSubExpr();
6835 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006836 }
Bill Wendlingad017fa2012-12-20 19:22:21 +00006837 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb1ea5102012-12-21 08:04:20 +00006838 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
6839 return;
Fariborz Jahanianbd2e27e2012-07-06 21:09:27 +00006840 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006841 }
6842}
Dmitri Gribenko625bb562012-02-14 22:14:32 +00006843
6844//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
6845
6846namespace {
6847bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
6848 SourceLocation StmtLoc,
6849 const NullStmt *Body) {
6850 // Do not warn if the body is a macro that expands to nothing, e.g:
6851 //
6852 // #define CALL(x)
6853 // if (condition)
6854 // CALL(0);
6855 //
6856 if (Body->hasLeadingEmptyMacro())
6857 return false;
6858
6859 // Get line numbers of statement and body.
6860 bool StmtLineInvalid;
6861 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
6862 &StmtLineInvalid);
6863 if (StmtLineInvalid)
6864 return false;
6865
6866 bool BodyLineInvalid;
6867 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
6868 &BodyLineInvalid);
6869 if (BodyLineInvalid)
6870 return false;
6871
6872 // Warn if null statement and body are on the same line.
6873 if (StmtLine != BodyLine)
6874 return false;
6875
6876 return true;
6877}
6878} // Unnamed namespace
6879
6880void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
6881 const Stmt *Body,
6882 unsigned DiagID) {
6883 // Since this is a syntactic check, don't emit diagnostic for template
6884 // instantiations, this just adds noise.
6885 if (CurrentInstantiationScope)
6886 return;
6887
6888 // The body should be a null statement.
6889 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6890 if (!NBody)
6891 return;
6892
6893 // Do the usual checks.
6894 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6895 return;
6896
6897 Diag(NBody->getSemiLoc(), DiagID);
6898 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6899}
6900
6901void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
6902 const Stmt *PossibleBody) {
6903 assert(!CurrentInstantiationScope); // Ensured by caller
6904
6905 SourceLocation StmtLoc;
6906 const Stmt *Body;
6907 unsigned DiagID;
6908 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
6909 StmtLoc = FS->getRParenLoc();
6910 Body = FS->getBody();
6911 DiagID = diag::warn_empty_for_body;
6912 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
6913 StmtLoc = WS->getCond()->getSourceRange().getEnd();
6914 Body = WS->getBody();
6915 DiagID = diag::warn_empty_while_body;
6916 } else
6917 return; // Neither `for' nor `while'.
6918
6919 // The body should be a null statement.
6920 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6921 if (!NBody)
6922 return;
6923
6924 // Skip expensive checks if diagnostic is disabled.
6925 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
6926 DiagnosticsEngine::Ignored)
6927 return;
6928
6929 // Do the usual checks.
6930 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6931 return;
6932
6933 // `for(...);' and `while(...);' are popular idioms, so in order to keep
6934 // noise level low, emit diagnostics only if for/while is followed by a
6935 // CompoundStmt, e.g.:
6936 // for (int i = 0; i < n; i++);
6937 // {
6938 // a(i);
6939 // }
6940 // or if for/while is followed by a statement with more indentation
6941 // than for/while itself:
6942 // for (int i = 0; i < n; i++);
6943 // a(i);
6944 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
6945 if (!ProbableTypo) {
6946 bool BodyColInvalid;
6947 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
6948 PossibleBody->getLocStart(),
6949 &BodyColInvalid);
6950 if (BodyColInvalid)
6951 return;
6952
6953 bool StmtColInvalid;
6954 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
6955 S->getLocStart(),
6956 &StmtColInvalid);
6957 if (StmtColInvalid)
6958 return;
6959
6960 if (BodyCol > StmtCol)
6961 ProbableTypo = true;
6962 }
6963
6964 if (ProbableTypo) {
6965 Diag(NBody->getSemiLoc(), DiagID);
6966 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6967 }
6968}
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00006969
6970//===--- Layout compatibility ----------------------------------------------//
6971
6972namespace {
6973
6974bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
6975
6976/// \brief Check if two enumeration types are layout-compatible.
6977bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
6978 // C++11 [dcl.enum] p8:
6979 // Two enumeration types are layout-compatible if they have the same
6980 // underlying type.
6981 return ED1->isComplete() && ED2->isComplete() &&
6982 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
6983}
6984
6985/// \brief Check if two fields are layout-compatible.
6986bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
6987 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
6988 return false;
6989
6990 if (Field1->isBitField() != Field2->isBitField())
6991 return false;
6992
6993 if (Field1->isBitField()) {
6994 // Make sure that the bit-fields are the same length.
6995 unsigned Bits1 = Field1->getBitWidthValue(C);
6996 unsigned Bits2 = Field2->getBitWidthValue(C);
6997
6998 if (Bits1 != Bits2)
6999 return false;
7000 }
7001
7002 return true;
7003}
7004
7005/// \brief Check if two standard-layout structs are layout-compatible.
7006/// (C++11 [class.mem] p17)
7007bool isLayoutCompatibleStruct(ASTContext &C,
7008 RecordDecl *RD1,
7009 RecordDecl *RD2) {
7010 // If both records are C++ classes, check that base classes match.
7011 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
7012 // If one of records is a CXXRecordDecl we are in C++ mode,
7013 // thus the other one is a CXXRecordDecl, too.
7014 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
7015 // Check number of base classes.
7016 if (D1CXX->getNumBases() != D2CXX->getNumBases())
7017 return false;
7018
7019 // Check the base classes.
7020 for (CXXRecordDecl::base_class_const_iterator
7021 Base1 = D1CXX->bases_begin(),
7022 BaseEnd1 = D1CXX->bases_end(),
7023 Base2 = D2CXX->bases_begin();
7024 Base1 != BaseEnd1;
7025 ++Base1, ++Base2) {
7026 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
7027 return false;
7028 }
7029 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
7030 // If only RD2 is a C++ class, it should have zero base classes.
7031 if (D2CXX->getNumBases() > 0)
7032 return false;
7033 }
7034
7035 // Check the fields.
7036 RecordDecl::field_iterator Field2 = RD2->field_begin(),
7037 Field2End = RD2->field_end(),
7038 Field1 = RD1->field_begin(),
7039 Field1End = RD1->field_end();
7040 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
7041 if (!isLayoutCompatible(C, *Field1, *Field2))
7042 return false;
7043 }
7044 if (Field1 != Field1End || Field2 != Field2End)
7045 return false;
7046
7047 return true;
7048}
7049
7050/// \brief Check if two standard-layout unions are layout-compatible.
7051/// (C++11 [class.mem] p18)
7052bool isLayoutCompatibleUnion(ASTContext &C,
7053 RecordDecl *RD1,
7054 RecordDecl *RD2) {
7055 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
7056 for (RecordDecl::field_iterator Field2 = RD2->field_begin(),
7057 Field2End = RD2->field_end();
7058 Field2 != Field2End; ++Field2) {
7059 UnmatchedFields.insert(*Field2);
7060 }
7061
7062 for (RecordDecl::field_iterator Field1 = RD1->field_begin(),
7063 Field1End = RD1->field_end();
7064 Field1 != Field1End; ++Field1) {
7065 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
7066 I = UnmatchedFields.begin(),
7067 E = UnmatchedFields.end();
7068
7069 for ( ; I != E; ++I) {
7070 if (isLayoutCompatible(C, *Field1, *I)) {
7071 bool Result = UnmatchedFields.erase(*I);
7072 (void) Result;
7073 assert(Result);
7074 break;
7075 }
7076 }
7077 if (I == E)
7078 return false;
7079 }
7080
7081 return UnmatchedFields.empty();
7082}
7083
7084bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
7085 if (RD1->isUnion() != RD2->isUnion())
7086 return false;
7087
7088 if (RD1->isUnion())
7089 return isLayoutCompatibleUnion(C, RD1, RD2);
7090 else
7091 return isLayoutCompatibleStruct(C, RD1, RD2);
7092}
7093
7094/// \brief Check if two types are layout-compatible in C++11 sense.
7095bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
7096 if (T1.isNull() || T2.isNull())
7097 return false;
7098
7099 // C++11 [basic.types] p11:
7100 // If two types T1 and T2 are the same type, then T1 and T2 are
7101 // layout-compatible types.
7102 if (C.hasSameType(T1, T2))
7103 return true;
7104
7105 T1 = T1.getCanonicalType().getUnqualifiedType();
7106 T2 = T2.getCanonicalType().getUnqualifiedType();
7107
7108 const Type::TypeClass TC1 = T1->getTypeClass();
7109 const Type::TypeClass TC2 = T2->getTypeClass();
7110
7111 if (TC1 != TC2)
7112 return false;
7113
7114 if (TC1 == Type::Enum) {
7115 return isLayoutCompatible(C,
7116 cast<EnumType>(T1)->getDecl(),
7117 cast<EnumType>(T2)->getDecl());
7118 } else if (TC1 == Type::Record) {
7119 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
7120 return false;
7121
7122 return isLayoutCompatible(C,
7123 cast<RecordType>(T1)->getDecl(),
7124 cast<RecordType>(T2)->getDecl());
7125 }
7126
7127 return false;
7128}
7129}
7130
7131//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
7132
7133namespace {
7134/// \brief Given a type tag expression find the type tag itself.
7135///
7136/// \param TypeExpr Type tag expression, as it appears in user's code.
7137///
7138/// \param VD Declaration of an identifier that appears in a type tag.
7139///
7140/// \param MagicValue Type tag magic value.
7141bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
7142 const ValueDecl **VD, uint64_t *MagicValue) {
7143 while(true) {
7144 if (!TypeExpr)
7145 return false;
7146
7147 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
7148
7149 switch (TypeExpr->getStmtClass()) {
7150 case Stmt::UnaryOperatorClass: {
7151 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
7152 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
7153 TypeExpr = UO->getSubExpr();
7154 continue;
7155 }
7156 return false;
7157 }
7158
7159 case Stmt::DeclRefExprClass: {
7160 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
7161 *VD = DRE->getDecl();
7162 return true;
7163 }
7164
7165 case Stmt::IntegerLiteralClass: {
7166 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
7167 llvm::APInt MagicValueAPInt = IL->getValue();
7168 if (MagicValueAPInt.getActiveBits() <= 64) {
7169 *MagicValue = MagicValueAPInt.getZExtValue();
7170 return true;
7171 } else
7172 return false;
7173 }
7174
7175 case Stmt::BinaryConditionalOperatorClass:
7176 case Stmt::ConditionalOperatorClass: {
7177 const AbstractConditionalOperator *ACO =
7178 cast<AbstractConditionalOperator>(TypeExpr);
7179 bool Result;
7180 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
7181 if (Result)
7182 TypeExpr = ACO->getTrueExpr();
7183 else
7184 TypeExpr = ACO->getFalseExpr();
7185 continue;
7186 }
7187 return false;
7188 }
7189
7190 case Stmt::BinaryOperatorClass: {
7191 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
7192 if (BO->getOpcode() == BO_Comma) {
7193 TypeExpr = BO->getRHS();
7194 continue;
7195 }
7196 return false;
7197 }
7198
7199 default:
7200 return false;
7201 }
7202 }
7203}
7204
7205/// \brief Retrieve the C type corresponding to type tag TypeExpr.
7206///
7207/// \param TypeExpr Expression that specifies a type tag.
7208///
7209/// \param MagicValues Registered magic values.
7210///
7211/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
7212/// kind.
7213///
7214/// \param TypeInfo Information about the corresponding C type.
7215///
7216/// \returns true if the corresponding C type was found.
7217bool GetMatchingCType(
7218 const IdentifierInfo *ArgumentKind,
7219 const Expr *TypeExpr, const ASTContext &Ctx,
7220 const llvm::DenseMap<Sema::TypeTagMagicValue,
7221 Sema::TypeTagData> *MagicValues,
7222 bool &FoundWrongKind,
7223 Sema::TypeTagData &TypeInfo) {
7224 FoundWrongKind = false;
7225
7226 // Variable declaration that has type_tag_for_datatype attribute.
7227 const ValueDecl *VD = NULL;
7228
7229 uint64_t MagicValue;
7230
7231 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
7232 return false;
7233
7234 if (VD) {
7235 for (specific_attr_iterator<TypeTagForDatatypeAttr>
7236 I = VD->specific_attr_begin<TypeTagForDatatypeAttr>(),
7237 E = VD->specific_attr_end<TypeTagForDatatypeAttr>();
7238 I != E; ++I) {
7239 if (I->getArgumentKind() != ArgumentKind) {
7240 FoundWrongKind = true;
7241 return false;
7242 }
7243 TypeInfo.Type = I->getMatchingCType();
7244 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
7245 TypeInfo.MustBeNull = I->getMustBeNull();
7246 return true;
7247 }
7248 return false;
7249 }
7250
7251 if (!MagicValues)
7252 return false;
7253
7254 llvm::DenseMap<Sema::TypeTagMagicValue,
7255 Sema::TypeTagData>::const_iterator I =
7256 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
7257 if (I == MagicValues->end())
7258 return false;
7259
7260 TypeInfo = I->second;
7261 return true;
7262}
7263} // unnamed namespace
7264
7265void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
7266 uint64_t MagicValue, QualType Type,
7267 bool LayoutCompatible,
7268 bool MustBeNull) {
7269 if (!TypeTagForDatatypeMagicValues)
7270 TypeTagForDatatypeMagicValues.reset(
7271 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
7272
7273 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
7274 (*TypeTagForDatatypeMagicValues)[Magic] =
7275 TypeTagData(Type, LayoutCompatible, MustBeNull);
7276}
7277
7278namespace {
7279bool IsSameCharType(QualType T1, QualType T2) {
7280 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
7281 if (!BT1)
7282 return false;
7283
7284 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
7285 if (!BT2)
7286 return false;
7287
7288 BuiltinType::Kind T1Kind = BT1->getKind();
7289 BuiltinType::Kind T2Kind = BT2->getKind();
7290
7291 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
7292 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
7293 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
7294 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
7295}
7296} // unnamed namespace
7297
7298void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
7299 const Expr * const *ExprArgs) {
7300 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
7301 bool IsPointerAttr = Attr->getIsPointer();
7302
7303 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
7304 bool FoundWrongKind;
7305 TypeTagData TypeInfo;
7306 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
7307 TypeTagForDatatypeMagicValues.get(),
7308 FoundWrongKind, TypeInfo)) {
7309 if (FoundWrongKind)
7310 Diag(TypeTagExpr->getExprLoc(),
7311 diag::warn_type_tag_for_datatype_wrong_kind)
7312 << TypeTagExpr->getSourceRange();
7313 return;
7314 }
7315
7316 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
7317 if (IsPointerAttr) {
7318 // Skip implicit cast of pointer to `void *' (as a function argument).
7319 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5a249802012-11-03 16:07:49 +00007320 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkob57ce4e2012-11-03 22:10:18 +00007321 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00007322 ArgumentExpr = ICE->getSubExpr();
7323 }
7324 QualType ArgumentType = ArgumentExpr->getType();
7325
7326 // Passing a `void*' pointer shouldn't trigger a warning.
7327 if (IsPointerAttr && ArgumentType->isVoidPointerType())
7328 return;
7329
7330 if (TypeInfo.MustBeNull) {
7331 // Type tag with matching void type requires a null pointer.
7332 if (!ArgumentExpr->isNullPointerConstant(Context,
7333 Expr::NPC_ValueDependentIsNotNull)) {
7334 Diag(ArgumentExpr->getExprLoc(),
7335 diag::warn_type_safety_null_pointer_required)
7336 << ArgumentKind->getName()
7337 << ArgumentExpr->getSourceRange()
7338 << TypeTagExpr->getSourceRange();
7339 }
7340 return;
7341 }
7342
7343 QualType RequiredType = TypeInfo.Type;
7344 if (IsPointerAttr)
7345 RequiredType = Context.getPointerType(RequiredType);
7346
7347 bool mismatch = false;
7348 if (!TypeInfo.LayoutCompatible) {
7349 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
7350
7351 // C++11 [basic.fundamental] p1:
7352 // Plain char, signed char, and unsigned char are three distinct types.
7353 //
7354 // But we treat plain `char' as equivalent to `signed char' or `unsigned
7355 // char' depending on the current char signedness mode.
7356 if (mismatch)
7357 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
7358 RequiredType->getPointeeType())) ||
7359 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
7360 mismatch = false;
7361 } else
7362 if (IsPointerAttr)
7363 mismatch = !isLayoutCompatible(Context,
7364 ArgumentType->getPointeeType(),
7365 RequiredType->getPointeeType());
7366 else
7367 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
7368
7369 if (mismatch)
7370 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
7371 << ArgumentType << ArgumentKind->getName()
7372 << TypeInfo.LayoutCompatible << RequiredType
7373 << ArgumentExpr->getSourceRange()
7374 << TypeTagExpr->getSourceRange();
7375}