blob: 79782921808c8952d19b329763c35ca06451d9c8 [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;
559
560 TheCall->setArg(0, ValArg.get());
561 return false;
562}
563
Nate Begeman26a31422010-06-08 02:47:44 +0000564bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000565 llvm::APSInt Result;
566
Tim Northover09df2b02013-07-16 09:47:53 +0000567 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
568 BuiltinID == ARM::BI__builtin_arm_strex) {
569 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall);
570 }
571
Richard Smithf8ee6bc2012-08-14 01:28:02 +0000572 uint64_t mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000573 unsigned TV = 0;
Bob Wilson46482552011-11-16 21:32:23 +0000574 int PtrArgNum = -1;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000575 bool HasConstPtr = false;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000576 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000577#define GET_NEON_OVERLOAD_CHECK
578#include "clang/Basic/arm_neon.inc"
579#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000580 }
581
Nate Begeman0d15c532010-06-13 04:47:52 +0000582 // For NEON intrinsics which are overloaded on vector element type, validate
583 // the immediate which specifies which variant to emit.
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000584 unsigned ImmArg = TheCall->getNumArgs()-1;
Nate Begeman0d15c532010-06-13 04:47:52 +0000585 if (mask) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000586 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
Nate Begeman0d15c532010-06-13 04:47:52 +0000587 return true;
588
Bob Wilsonda95f732011-11-08 01:16:11 +0000589 TV = Result.getLimitedValue(64);
Richard Smithf8ee6bc2012-08-14 01:28:02 +0000590 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000591 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000592 << TheCall->getArg(ImmArg)->getSourceRange();
593 }
594
Bob Wilson46482552011-11-16 21:32:23 +0000595 if (PtrArgNum >= 0) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000596 // Check that pointer arguments have the specified type.
Bob Wilson46482552011-11-16 21:32:23 +0000597 Expr *Arg = TheCall->getArg(PtrArgNum);
598 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
599 Arg = ICE->getSubExpr();
600 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
601 QualType RHSTy = RHS.get()->getType();
602 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
603 if (HasConstPtr)
604 EltTy = EltTy.withConst();
605 QualType LHSTy = Context.getPointerType(EltTy);
606 AssignConvertType ConvTy;
607 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
608 if (RHS.isInvalid())
609 return true;
610 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
611 RHS.get(), AA_Assigning))
612 return true;
Nate Begeman0d15c532010-06-13 04:47:52 +0000613 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000614
Nate Begeman0d15c532010-06-13 04:47:52 +0000615 // For NEON intrinsics which take an immediate value as part of the
616 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000617 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000618 switch (BuiltinID) {
619 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000620 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
621 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000622 case ARM::BI__builtin_arm_vcvtr_f:
623 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000624#define GET_NEON_IMMEDIATE_CHECK
625#include "clang/Basic/arm_neon.inc"
626#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000627 };
628
Douglas Gregor592a4232012-06-29 01:05:22 +0000629 // We can't check the value of a dependent argument.
630 if (TheCall->getArg(i)->isTypeDependent() ||
631 TheCall->getArg(i)->isValueDependent())
632 return false;
633
Nate Begeman61eecf52010-06-14 05:21:25 +0000634 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000635 if (SemaBuiltinConstantArg(TheCall, i, Result))
636 return true;
637
Nate Begeman61eecf52010-06-14 05:21:25 +0000638 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000639 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000640 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000641 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000642 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000643
Nate Begeman99c40bb2010-08-03 21:32:34 +0000644 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000645 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000646}
Daniel Dunbarde454282008-10-02 18:44:07 +0000647
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000648bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
649 unsigned i = 0, l = 0, u = 0;
650 switch (BuiltinID) {
651 default: return false;
652 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
653 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyanbe22cb82012-08-27 12:29:20 +0000654 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
655 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
656 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
657 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
658 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000659 };
660
661 // We can't check the value of a dependent argument.
662 if (TheCall->getArg(i)->isTypeDependent() ||
663 TheCall->getArg(i)->isValueDependent())
664 return false;
665
666 // Check that the immediate argument is actually a constant.
667 llvm::APSInt Result;
668 if (SemaBuiltinConstantArg(TheCall, i, Result))
669 return true;
670
671 // Range check against the upper/lower values for this instruction.
672 unsigned Val = Result.getZExtValue();
673 if (Val < l || Val > u)
674 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
675 << l << u << TheCall->getArg(i)->getSourceRange();
676
677 return false;
678}
679
Richard Smith831421f2012-06-25 20:30:08 +0000680/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
681/// parameter with the FormatAttr's correct format_idx and firstDataArg.
682/// Returns true when the format fits the function and the FormatStringInfo has
683/// been populated.
684bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
685 FormatStringInfo *FSI) {
686 FSI->HasVAListArg = Format->getFirstArg() == 0;
687 FSI->FormatIdx = Format->getFormatIdx() - 1;
688 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssond406bf02009-08-16 01:56:34 +0000689
Richard Smith831421f2012-06-25 20:30:08 +0000690 // The way the format attribute works in GCC, the implicit this argument
691 // of member functions is counted. However, it doesn't appear in our own
692 // lists, so decrement format_idx in that case.
693 if (IsCXXMember) {
694 if(FSI->FormatIdx == 0)
695 return false;
696 --FSI->FormatIdx;
697 if (FSI->FirstDataArg != 0)
698 --FSI->FirstDataArg;
699 }
700 return true;
701}
Mike Stump1eb44332009-09-09 15:08:12 +0000702
Richard Smith831421f2012-06-25 20:30:08 +0000703/// Handles the checks for format strings, non-POD arguments to vararg
704/// functions, and NULL arguments passed to non-NULL parameters.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000705void Sema::checkCall(NamedDecl *FDecl,
706 ArrayRef<const Expr *> Args,
Richard Smith831421f2012-06-25 20:30:08 +0000707 unsigned NumProtoArgs,
708 bool IsMemberFunction,
709 SourceLocation Loc,
710 SourceRange Range,
711 VariadicCallType CallType) {
Richard Smith0e218972013-08-05 18:49:43 +0000712 // FIXME: We should check as much as we can in the template definition.
Jordan Rose66360e22012-10-02 01:49:54 +0000713 if (CurContext->isDependentContext())
714 return;
Daniel Dunbarde454282008-10-02 18:44:07 +0000715
Ted Kremenekc82faca2010-09-09 04:33:05 +0000716 // Printf and scanf checking.
Richard Smith0e218972013-08-05 18:49:43 +0000717 llvm::SmallBitVector CheckedVarArgs;
718 if (FDecl) {
Richard Trieu0538f0e2013-06-22 00:20:41 +0000719 for (specific_attr_iterator<FormatAttr>
Benjamin Kramer47abb252013-08-08 11:08:26 +0000720 I = FDecl->specific_attr_begin<FormatAttr>(),
721 E = FDecl->specific_attr_end<FormatAttr>();
Benjamin Kramer541a28f2013-08-09 09:39:17 +0000722 I != E; ++I) {
723 // Only create vector if there are format attributes.
724 CheckedVarArgs.resize(Args.size());
725
Benjamin Kramer47abb252013-08-08 11:08:26 +0000726 CheckFormatArguments(*I, Args, IsMemberFunction, CallType, Loc, Range,
727 CheckedVarArgs);
Benjamin Kramer541a28f2013-08-09 09:39:17 +0000728 }
Richard Smith0e218972013-08-05 18:49:43 +0000729 }
Richard Smith831421f2012-06-25 20:30:08 +0000730
731 // Refuse POD arguments that weren't caught by the format string
732 // checks above.
Richard Smith0e218972013-08-05 18:49:43 +0000733 if (CallType != VariadicDoesNotApply) {
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000734 for (unsigned ArgIdx = NumProtoArgs; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek0234bfa2012-10-11 19:06:43 +0000735 // Args[ArgIdx] can be null in malformed code.
Richard Smith0e218972013-08-05 18:49:43 +0000736 if (const Expr *Arg = Args[ArgIdx]) {
737 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
738 checkVariadicArgument(Arg, CallType);
739 }
Ted Kremenek0234bfa2012-10-11 19:06:43 +0000740 }
Richard Smith0e218972013-08-05 18:49:43 +0000741 }
Mike Stump1eb44332009-09-09 15:08:12 +0000742
Richard Trieu0538f0e2013-06-22 00:20:41 +0000743 if (FDecl) {
744 for (specific_attr_iterator<NonNullAttr>
745 I = FDecl->specific_attr_begin<NonNullAttr>(),
746 E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I)
747 CheckNonNullArguments(*I, Args.data(), Loc);
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +0000748
Richard Trieu0538f0e2013-06-22 00:20:41 +0000749 // Type safety checking.
750 for (specific_attr_iterator<ArgumentWithTypeTagAttr>
751 i = FDecl->specific_attr_begin<ArgumentWithTypeTagAttr>(),
752 e = FDecl->specific_attr_end<ArgumentWithTypeTagAttr>();
753 i != e; ++i) {
754 CheckArgumentWithTypeTag(*i, Args.data());
755 }
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +0000756 }
Richard Smith831421f2012-06-25 20:30:08 +0000757}
758
759/// CheckConstructorCall - Check a constructor call for correctness and safety
760/// properties not enforced by the C type system.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000761void Sema::CheckConstructorCall(FunctionDecl *FDecl,
762 ArrayRef<const Expr *> Args,
Richard Smith831421f2012-06-25 20:30:08 +0000763 const FunctionProtoType *Proto,
764 SourceLocation Loc) {
765 VariadicCallType CallType =
766 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000767 checkCall(FDecl, Args, Proto->getNumArgs(),
Richard Smith831421f2012-06-25 20:30:08 +0000768 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
769}
770
771/// CheckFunctionCall - Check a direct function call for various correctness
772/// and safety properties not strictly enforced by the C type system.
773bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
774 const FunctionProtoType *Proto) {
Eli Friedman2edcde82012-10-11 00:30:58 +0000775 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
776 isa<CXXMethodDecl>(FDecl);
777 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
778 IsMemberOperatorCall;
Richard Smith831421f2012-06-25 20:30:08 +0000779 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
780 TheCall->getCallee());
781 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
Eli Friedman2edcde82012-10-11 00:30:58 +0000782 Expr** Args = TheCall->getArgs();
783 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmandf75b0c2012-10-11 00:34:15 +0000784 if (IsMemberOperatorCall) {
Eli Friedman2edcde82012-10-11 00:30:58 +0000785 // If this is a call to a member operator, hide the first argument
786 // from checkCall.
787 // FIXME: Our choice of AST representation here is less than ideal.
788 ++Args;
789 --NumArgs;
790 }
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000791 checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs),
792 NumProtoArgs,
Richard Smith831421f2012-06-25 20:30:08 +0000793 IsMemberFunction, TheCall->getRParenLoc(),
794 TheCall->getCallee()->getSourceRange(), CallType);
795
796 IdentifierInfo *FnInfo = FDecl->getIdentifier();
797 // None of the checks below are needed for functions that don't have
798 // simple names (e.g., C++ conversion functions).
799 if (!FnInfo)
800 return false;
Sebastian Redl0eb23302009-01-19 00:08:26 +0000801
Anna Zaks0a151a12012-01-17 00:37:07 +0000802 unsigned CMId = FDecl->getMemoryFunctionKind();
803 if (CMId == 0)
Anna Zaksd9b859a2012-01-13 21:52:01 +0000804 return false;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000805
Anna Zaksd9b859a2012-01-13 21:52:01 +0000806 // Handle memory setting and copying functions.
Anna Zaks0a151a12012-01-17 00:37:07 +0000807 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000808 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaksc36bedc2012-02-01 19:08:57 +0000809 else if (CMId == Builtin::BIstrncat)
810 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaksd9b859a2012-01-13 21:52:01 +0000811 else
Anna Zaks0a151a12012-01-17 00:37:07 +0000812 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000813
Anders Carlssond406bf02009-08-16 01:56:34 +0000814 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000815}
816
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000817bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko287f24d2013-05-05 19:42:09 +0000818 ArrayRef<const Expr *> Args) {
Richard Smith831421f2012-06-25 20:30:08 +0000819 VariadicCallType CallType =
820 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000821
Dmitri Gribenko287f24d2013-05-05 19:42:09 +0000822 checkCall(Method, Args, Method->param_size(),
Richard Smith831421f2012-06-25 20:30:08 +0000823 /*IsMemberFunction=*/false,
824 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000825
826 return false;
827}
828
Richard Trieuf462b012013-06-20 21:03:13 +0000829bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
830 const FunctionProtoType *Proto) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000831 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
832 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000833 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000834
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000835 QualType Ty = V->getType();
Richard Trieuf462b012013-06-20 21:03:13 +0000836 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000837 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000838
Richard Trieuf462b012013-06-20 21:03:13 +0000839 VariadicCallType CallType;
Richard Trieua4993772013-06-20 23:21:54 +0000840 if (!Proto || !Proto->isVariadic()) {
Richard Trieuf462b012013-06-20 21:03:13 +0000841 CallType = VariadicDoesNotApply;
842 } else if (Ty->isBlockPointerType()) {
843 CallType = VariadicBlock;
844 } else { // Ty->isFunctionPointerType()
845 CallType = VariadicFunction;
846 }
Richard Smith831421f2012-06-25 20:30:08 +0000847 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
Anders Carlssond406bf02009-08-16 01:56:34 +0000848
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000849 checkCall(NDecl,
850 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
851 TheCall->getNumArgs()),
Richard Smith831421f2012-06-25 20:30:08 +0000852 NumProtoArgs, /*IsMemberFunction=*/false,
853 TheCall->getRParenLoc(),
854 TheCall->getCallee()->getSourceRange(), CallType);
855
Anders Carlssond406bf02009-08-16 01:56:34 +0000856 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000857}
858
Richard Trieu0538f0e2013-06-22 00:20:41 +0000859/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
860/// such as function pointers returned from functions.
861bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
862 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/0, Proto,
863 TheCall->getCallee());
864 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
865
866 checkCall(/*FDecl=*/0,
867 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
868 TheCall->getNumArgs()),
869 NumProtoArgs, /*IsMemberFunction=*/false,
870 TheCall->getRParenLoc(),
871 TheCall->getCallee()->getSourceRange(), CallType);
872
873 return false;
874}
875
Richard Smithff34d402012-04-12 05:08:17 +0000876ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
877 AtomicExpr::AtomicOp Op) {
Eli Friedman276b0612011-10-11 02:20:01 +0000878 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
879 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000880
Richard Smithff34d402012-04-12 05:08:17 +0000881 // All these operations take one of the following forms:
882 enum {
883 // C __c11_atomic_init(A *, C)
884 Init,
885 // C __c11_atomic_load(A *, int)
886 Load,
887 // void __atomic_load(A *, CP, int)
888 Copy,
889 // C __c11_atomic_add(A *, M, int)
890 Arithmetic,
891 // C __atomic_exchange_n(A *, CP, int)
892 Xchg,
893 // void __atomic_exchange(A *, C *, CP, int)
894 GNUXchg,
895 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
896 C11CmpXchg,
897 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
898 GNUCmpXchg
899 } Form = Init;
900 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
901 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
902 // where:
903 // C is an appropriate type,
904 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
905 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
906 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
907 // the int parameters are for orderings.
Eli Friedman276b0612011-10-11 02:20:01 +0000908
Richard Smithff34d402012-04-12 05:08:17 +0000909 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
910 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
911 && "need to update code for modified C11 atomics");
912 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
913 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
914 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
915 Op == AtomicExpr::AO__atomic_store_n ||
916 Op == AtomicExpr::AO__atomic_exchange_n ||
917 Op == AtomicExpr::AO__atomic_compare_exchange_n;
918 bool IsAddSub = false;
919
920 switch (Op) {
921 case AtomicExpr::AO__c11_atomic_init:
922 Form = Init;
923 break;
924
925 case AtomicExpr::AO__c11_atomic_load:
926 case AtomicExpr::AO__atomic_load_n:
927 Form = Load;
928 break;
929
930 case AtomicExpr::AO__c11_atomic_store:
931 case AtomicExpr::AO__atomic_load:
932 case AtomicExpr::AO__atomic_store:
933 case AtomicExpr::AO__atomic_store_n:
934 Form = Copy;
935 break;
936
937 case AtomicExpr::AO__c11_atomic_fetch_add:
938 case AtomicExpr::AO__c11_atomic_fetch_sub:
939 case AtomicExpr::AO__atomic_fetch_add:
940 case AtomicExpr::AO__atomic_fetch_sub:
941 case AtomicExpr::AO__atomic_add_fetch:
942 case AtomicExpr::AO__atomic_sub_fetch:
943 IsAddSub = true;
944 // Fall through.
945 case AtomicExpr::AO__c11_atomic_fetch_and:
946 case AtomicExpr::AO__c11_atomic_fetch_or:
947 case AtomicExpr::AO__c11_atomic_fetch_xor:
948 case AtomicExpr::AO__atomic_fetch_and:
949 case AtomicExpr::AO__atomic_fetch_or:
950 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smith51b92402012-04-13 06:31:38 +0000951 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithff34d402012-04-12 05:08:17 +0000952 case AtomicExpr::AO__atomic_and_fetch:
953 case AtomicExpr::AO__atomic_or_fetch:
954 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smith51b92402012-04-13 06:31:38 +0000955 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithff34d402012-04-12 05:08:17 +0000956 Form = Arithmetic;
957 break;
958
959 case AtomicExpr::AO__c11_atomic_exchange:
960 case AtomicExpr::AO__atomic_exchange_n:
961 Form = Xchg;
962 break;
963
964 case AtomicExpr::AO__atomic_exchange:
965 Form = GNUXchg;
966 break;
967
968 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
969 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
970 Form = C11CmpXchg;
971 break;
972
973 case AtomicExpr::AO__atomic_compare_exchange:
974 case AtomicExpr::AO__atomic_compare_exchange_n:
975 Form = GNUCmpXchg;
976 break;
977 }
978
979 // Check we have the right number of arguments.
980 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedman276b0612011-10-11 02:20:01 +0000981 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithff34d402012-04-12 05:08:17 +0000982 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000983 << TheCall->getCallee()->getSourceRange();
984 return ExprError();
Richard Smithff34d402012-04-12 05:08:17 +0000985 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
986 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedman276b0612011-10-11 02:20:01 +0000987 diag::err_typecheck_call_too_many_args)
Richard Smithff34d402012-04-12 05:08:17 +0000988 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000989 << TheCall->getCallee()->getSourceRange();
990 return ExprError();
991 }
992
Richard Smithff34d402012-04-12 05:08:17 +0000993 // Inspect the first argument of the atomic operation.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000994 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +0000995 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
996 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
997 if (!pointerType) {
Richard Smithff34d402012-04-12 05:08:17 +0000998 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedman276b0612011-10-11 02:20:01 +0000999 << Ptr->getType() << Ptr->getSourceRange();
1000 return ExprError();
1001 }
1002
Richard Smithff34d402012-04-12 05:08:17 +00001003 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1004 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1005 QualType ValType = AtomTy; // 'C'
1006 if (IsC11) {
1007 if (!AtomTy->isAtomicType()) {
1008 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1009 << Ptr->getType() << Ptr->getSourceRange();
1010 return ExprError();
1011 }
Richard Smithbc57b102012-09-15 06:09:58 +00001012 if (AtomTy.isConstQualified()) {
1013 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1014 << Ptr->getType() << Ptr->getSourceRange();
1015 return ExprError();
1016 }
Richard Smithff34d402012-04-12 05:08:17 +00001017 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedman276b0612011-10-11 02:20:01 +00001018 }
Eli Friedman276b0612011-10-11 02:20:01 +00001019
Richard Smithff34d402012-04-12 05:08:17 +00001020 // For an arithmetic operation, the implied arithmetic must be well-formed.
1021 if (Form == Arithmetic) {
1022 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1023 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1024 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1025 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1026 return ExprError();
1027 }
1028 if (!IsAddSub && !ValType->isIntegerType()) {
1029 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1030 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1031 return ExprError();
1032 }
1033 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1034 // For __atomic_*_n operations, the value type must be a scalar integral or
1035 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedman276b0612011-10-11 02:20:01 +00001036 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithff34d402012-04-12 05:08:17 +00001037 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1038 return ExprError();
1039 }
1040
1041 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context)) {
1042 // For GNU atomics, require a trivially-copyable type. This is not part of
1043 // the GNU atomics specification, but we enforce it for sanity.
1044 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedman276b0612011-10-11 02:20:01 +00001045 << Ptr->getType() << Ptr->getSourceRange();
1046 return ExprError();
1047 }
1048
Richard Smithff34d402012-04-12 05:08:17 +00001049 // FIXME: For any builtin other than a load, the ValType must not be
1050 // const-qualified.
Eli Friedman276b0612011-10-11 02:20:01 +00001051
1052 switch (ValType.getObjCLifetime()) {
1053 case Qualifiers::OCL_None:
1054 case Qualifiers::OCL_ExplicitNone:
1055 // okay
1056 break;
1057
1058 case Qualifiers::OCL_Weak:
1059 case Qualifiers::OCL_Strong:
1060 case Qualifiers::OCL_Autoreleasing:
Richard Smithff34d402012-04-12 05:08:17 +00001061 // FIXME: Can this happen? By this point, ValType should be known
1062 // to be trivially copyable.
Eli Friedman276b0612011-10-11 02:20:01 +00001063 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1064 << ValType << Ptr->getSourceRange();
1065 return ExprError();
1066 }
1067
1068 QualType ResultType = ValType;
Richard Smithff34d402012-04-12 05:08:17 +00001069 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedman276b0612011-10-11 02:20:01 +00001070 ResultType = Context.VoidTy;
Richard Smithff34d402012-04-12 05:08:17 +00001071 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedman276b0612011-10-11 02:20:01 +00001072 ResultType = Context.BoolTy;
1073
Richard Smithff34d402012-04-12 05:08:17 +00001074 // The type of a parameter passed 'by value'. In the GNU atomics, such
1075 // arguments are actually passed as pointers.
1076 QualType ByValType = ValType; // 'CP'
1077 if (!IsC11 && !IsN)
1078 ByValType = Ptr->getType();
1079
Eli Friedman276b0612011-10-11 02:20:01 +00001080 // The first argument --- the pointer --- has a fixed type; we
1081 // deduce the types of the rest of the arguments accordingly. Walk
1082 // the remaining arguments, converting them to the deduced value type.
Richard Smithff34d402012-04-12 05:08:17 +00001083 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedman276b0612011-10-11 02:20:01 +00001084 QualType Ty;
Richard Smithff34d402012-04-12 05:08:17 +00001085 if (i < NumVals[Form] + 1) {
1086 switch (i) {
1087 case 1:
1088 // The second argument is the non-atomic operand. For arithmetic, this
1089 // is always passed by value, and for a compare_exchange it is always
1090 // passed by address. For the rest, GNU uses by-address and C11 uses
1091 // by-value.
1092 assert(Form != Load);
1093 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1094 Ty = ValType;
1095 else if (Form == Copy || Form == Xchg)
1096 Ty = ByValType;
1097 else if (Form == Arithmetic)
1098 Ty = Context.getPointerDiffType();
1099 else
1100 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1101 break;
1102 case 2:
1103 // The third argument to compare_exchange / GNU exchange is a
1104 // (pointer to a) desired value.
1105 Ty = ByValType;
1106 break;
1107 case 3:
1108 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1109 Ty = Context.BoolTy;
1110 break;
1111 }
Eli Friedman276b0612011-10-11 02:20:01 +00001112 } else {
1113 // The order(s) are always converted to int.
1114 Ty = Context.IntTy;
1115 }
Richard Smithff34d402012-04-12 05:08:17 +00001116
Eli Friedman276b0612011-10-11 02:20:01 +00001117 InitializedEntity Entity =
1118 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithff34d402012-04-12 05:08:17 +00001119 ExprResult Arg = TheCall->getArg(i);
Eli Friedman276b0612011-10-11 02:20:01 +00001120 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1121 if (Arg.isInvalid())
1122 return true;
1123 TheCall->setArg(i, Arg.get());
1124 }
1125
Richard Smithff34d402012-04-12 05:08:17 +00001126 // Permute the arguments into a 'consistent' order.
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001127 SmallVector<Expr*, 5> SubExprs;
1128 SubExprs.push_back(Ptr);
Richard Smithff34d402012-04-12 05:08:17 +00001129 switch (Form) {
1130 case Init:
1131 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnall7a7ee302012-01-16 17:27:18 +00001132 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +00001133 break;
1134 case Load:
1135 SubExprs.push_back(TheCall->getArg(1)); // Order
1136 break;
1137 case Copy:
1138 case Arithmetic:
1139 case Xchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001140 SubExprs.push_back(TheCall->getArg(2)); // Order
1141 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +00001142 break;
1143 case GNUXchg:
1144 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1145 SubExprs.push_back(TheCall->getArg(3)); // Order
1146 SubExprs.push_back(TheCall->getArg(1)); // Val1
1147 SubExprs.push_back(TheCall->getArg(2)); // Val2
1148 break;
1149 case C11CmpXchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001150 SubExprs.push_back(TheCall->getArg(3)); // Order
1151 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001152 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall2ebb98a2012-03-29 17:58:59 +00001153 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithff34d402012-04-12 05:08:17 +00001154 break;
1155 case GNUCmpXchg:
1156 SubExprs.push_back(TheCall->getArg(4)); // Order
1157 SubExprs.push_back(TheCall->getArg(1)); // Val1
1158 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1159 SubExprs.push_back(TheCall->getArg(2)); // Val2
1160 SubExprs.push_back(TheCall->getArg(3)); // Weak
1161 break;
Eli Friedman276b0612011-10-11 02:20:01 +00001162 }
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00001163
1164 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1165 SubExprs, ResultType, Op,
1166 TheCall->getRParenLoc());
1167
1168 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1169 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1170 Context.AtomicUsesUnsupportedLibcall(AE))
1171 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1172 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001173
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00001174 return Owned(AE);
Eli Friedman276b0612011-10-11 02:20:01 +00001175}
1176
1177
John McCall5f8d6042011-08-27 01:09:30 +00001178/// checkBuiltinArgument - Given a call to a builtin function, perform
1179/// normal type-checking on the given argument, updating the call in
1180/// place. This is useful when a builtin function requires custom
1181/// type-checking for some of its arguments but not necessarily all of
1182/// them.
1183///
1184/// Returns true on error.
1185static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1186 FunctionDecl *Fn = E->getDirectCallee();
1187 assert(Fn && "builtin call without direct callee!");
1188
1189 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1190 InitializedEntity Entity =
1191 InitializedEntity::InitializeParameter(S.Context, Param);
1192
1193 ExprResult Arg = E->getArg(0);
1194 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1195 if (Arg.isInvalid())
1196 return true;
1197
1198 E->setArg(ArgIndex, Arg.take());
1199 return false;
1200}
1201
Chris Lattner5caa3702009-05-08 06:58:22 +00001202/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1203/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1204/// type of its first argument. The main ActOnCallExpr routines have already
1205/// promoted the types of arguments because all of these calls are prototyped as
1206/// void(...).
1207///
1208/// This function goes through and does final semantic checking for these
1209/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +00001210ExprResult
1211Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +00001212 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +00001213 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1214 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1215
1216 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +00001217 if (TheCall->getNumArgs() < 1) {
1218 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1219 << 0 << 1 << TheCall->getNumArgs()
1220 << TheCall->getCallee()->getSourceRange();
1221 return ExprError();
1222 }
Mike Stump1eb44332009-09-09 15:08:12 +00001223
Chris Lattner5caa3702009-05-08 06:58:22 +00001224 // Inspect the first argument of the atomic builtin. This should always be
1225 // a pointer type, whose element is an integral scalar or pointer type.
1226 // Because it is a pointer type, we don't have to worry about any implicit
1227 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +00001228 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +00001229 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman8c382062012-01-23 02:35:22 +00001230 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1231 if (FirstArgResult.isInvalid())
1232 return ExprError();
1233 FirstArg = FirstArgResult.take();
1234 TheCall->setArg(0, FirstArg);
1235
John McCallf85e1932011-06-15 23:02:42 +00001236 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1237 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +00001238 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1239 << FirstArg->getType() << FirstArg->getSourceRange();
1240 return ExprError();
1241 }
Mike Stump1eb44332009-09-09 15:08:12 +00001242
John McCallf85e1932011-06-15 23:02:42 +00001243 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +00001244 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +00001245 !ValType->isBlockPointerType()) {
1246 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1247 << FirstArg->getType() << FirstArg->getSourceRange();
1248 return ExprError();
1249 }
Chris Lattner5caa3702009-05-08 06:58:22 +00001250
John McCallf85e1932011-06-15 23:02:42 +00001251 switch (ValType.getObjCLifetime()) {
1252 case Qualifiers::OCL_None:
1253 case Qualifiers::OCL_ExplicitNone:
1254 // okay
1255 break;
1256
1257 case Qualifiers::OCL_Weak:
1258 case Qualifiers::OCL_Strong:
1259 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001260 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001261 << ValType << FirstArg->getSourceRange();
1262 return ExprError();
1263 }
1264
John McCallb45ae252011-10-05 07:41:44 +00001265 // Strip any qualifiers off ValType.
1266 ValType = ValType.getUnqualifiedType();
1267
Chandler Carruth8d13d222010-07-18 20:54:12 +00001268 // The majority of builtins return a value, but a few have special return
1269 // types, so allow them to override appropriately below.
1270 QualType ResultType = ValType;
1271
Chris Lattner5caa3702009-05-08 06:58:22 +00001272 // We need to figure out which concrete builtin this maps onto. For example,
1273 // __sync_fetch_and_add with a 2 byte object turns into
1274 // __sync_fetch_and_add_2.
1275#define BUILTIN_ROW(x) \
1276 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1277 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +00001278
Chris Lattner5caa3702009-05-08 06:58:22 +00001279 static const unsigned BuiltinIndices[][5] = {
1280 BUILTIN_ROW(__sync_fetch_and_add),
1281 BUILTIN_ROW(__sync_fetch_and_sub),
1282 BUILTIN_ROW(__sync_fetch_and_or),
1283 BUILTIN_ROW(__sync_fetch_and_and),
1284 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +00001285
Chris Lattner5caa3702009-05-08 06:58:22 +00001286 BUILTIN_ROW(__sync_add_and_fetch),
1287 BUILTIN_ROW(__sync_sub_and_fetch),
1288 BUILTIN_ROW(__sync_and_and_fetch),
1289 BUILTIN_ROW(__sync_or_and_fetch),
1290 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +00001291
Chris Lattner5caa3702009-05-08 06:58:22 +00001292 BUILTIN_ROW(__sync_val_compare_and_swap),
1293 BUILTIN_ROW(__sync_bool_compare_and_swap),
1294 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +00001295 BUILTIN_ROW(__sync_lock_release),
1296 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +00001297 };
Mike Stump1eb44332009-09-09 15:08:12 +00001298#undef BUILTIN_ROW
1299
Chris Lattner5caa3702009-05-08 06:58:22 +00001300 // Determine the index of the size.
1301 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +00001302 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +00001303 case 1: SizeIndex = 0; break;
1304 case 2: SizeIndex = 1; break;
1305 case 4: SizeIndex = 2; break;
1306 case 8: SizeIndex = 3; break;
1307 case 16: SizeIndex = 4; break;
1308 default:
Chandler Carruthd2014572010-07-09 18:59:35 +00001309 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1310 << FirstArg->getType() << FirstArg->getSourceRange();
1311 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +00001312 }
Mike Stump1eb44332009-09-09 15:08:12 +00001313
Chris Lattner5caa3702009-05-08 06:58:22 +00001314 // Each of these builtins has one pointer argument, followed by some number of
1315 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1316 // that we ignore. Find out which row of BuiltinIndices to read from as well
1317 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00001318 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +00001319 unsigned BuiltinIndex, NumFixed = 1;
1320 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001321 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +00001322 case Builtin::BI__sync_fetch_and_add:
1323 case Builtin::BI__sync_fetch_and_add_1:
1324 case Builtin::BI__sync_fetch_and_add_2:
1325 case Builtin::BI__sync_fetch_and_add_4:
1326 case Builtin::BI__sync_fetch_and_add_8:
1327 case Builtin::BI__sync_fetch_and_add_16:
1328 BuiltinIndex = 0;
1329 break;
1330
1331 case Builtin::BI__sync_fetch_and_sub:
1332 case Builtin::BI__sync_fetch_and_sub_1:
1333 case Builtin::BI__sync_fetch_and_sub_2:
1334 case Builtin::BI__sync_fetch_and_sub_4:
1335 case Builtin::BI__sync_fetch_and_sub_8:
1336 case Builtin::BI__sync_fetch_and_sub_16:
1337 BuiltinIndex = 1;
1338 break;
1339
1340 case Builtin::BI__sync_fetch_and_or:
1341 case Builtin::BI__sync_fetch_and_or_1:
1342 case Builtin::BI__sync_fetch_and_or_2:
1343 case Builtin::BI__sync_fetch_and_or_4:
1344 case Builtin::BI__sync_fetch_and_or_8:
1345 case Builtin::BI__sync_fetch_and_or_16:
1346 BuiltinIndex = 2;
1347 break;
1348
1349 case Builtin::BI__sync_fetch_and_and:
1350 case Builtin::BI__sync_fetch_and_and_1:
1351 case Builtin::BI__sync_fetch_and_and_2:
1352 case Builtin::BI__sync_fetch_and_and_4:
1353 case Builtin::BI__sync_fetch_and_and_8:
1354 case Builtin::BI__sync_fetch_and_and_16:
1355 BuiltinIndex = 3;
1356 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001357
Douglas Gregora9766412011-11-28 16:30:08 +00001358 case Builtin::BI__sync_fetch_and_xor:
1359 case Builtin::BI__sync_fetch_and_xor_1:
1360 case Builtin::BI__sync_fetch_and_xor_2:
1361 case Builtin::BI__sync_fetch_and_xor_4:
1362 case Builtin::BI__sync_fetch_and_xor_8:
1363 case Builtin::BI__sync_fetch_and_xor_16:
1364 BuiltinIndex = 4;
1365 break;
1366
1367 case Builtin::BI__sync_add_and_fetch:
1368 case Builtin::BI__sync_add_and_fetch_1:
1369 case Builtin::BI__sync_add_and_fetch_2:
1370 case Builtin::BI__sync_add_and_fetch_4:
1371 case Builtin::BI__sync_add_and_fetch_8:
1372 case Builtin::BI__sync_add_and_fetch_16:
1373 BuiltinIndex = 5;
1374 break;
1375
1376 case Builtin::BI__sync_sub_and_fetch:
1377 case Builtin::BI__sync_sub_and_fetch_1:
1378 case Builtin::BI__sync_sub_and_fetch_2:
1379 case Builtin::BI__sync_sub_and_fetch_4:
1380 case Builtin::BI__sync_sub_and_fetch_8:
1381 case Builtin::BI__sync_sub_and_fetch_16:
1382 BuiltinIndex = 6;
1383 break;
1384
1385 case Builtin::BI__sync_and_and_fetch:
1386 case Builtin::BI__sync_and_and_fetch_1:
1387 case Builtin::BI__sync_and_and_fetch_2:
1388 case Builtin::BI__sync_and_and_fetch_4:
1389 case Builtin::BI__sync_and_and_fetch_8:
1390 case Builtin::BI__sync_and_and_fetch_16:
1391 BuiltinIndex = 7;
1392 break;
1393
1394 case Builtin::BI__sync_or_and_fetch:
1395 case Builtin::BI__sync_or_and_fetch_1:
1396 case Builtin::BI__sync_or_and_fetch_2:
1397 case Builtin::BI__sync_or_and_fetch_4:
1398 case Builtin::BI__sync_or_and_fetch_8:
1399 case Builtin::BI__sync_or_and_fetch_16:
1400 BuiltinIndex = 8;
1401 break;
1402
1403 case Builtin::BI__sync_xor_and_fetch:
1404 case Builtin::BI__sync_xor_and_fetch_1:
1405 case Builtin::BI__sync_xor_and_fetch_2:
1406 case Builtin::BI__sync_xor_and_fetch_4:
1407 case Builtin::BI__sync_xor_and_fetch_8:
1408 case Builtin::BI__sync_xor_and_fetch_16:
1409 BuiltinIndex = 9;
1410 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001411
Chris Lattner5caa3702009-05-08 06:58:22 +00001412 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001413 case Builtin::BI__sync_val_compare_and_swap_1:
1414 case Builtin::BI__sync_val_compare_and_swap_2:
1415 case Builtin::BI__sync_val_compare_and_swap_4:
1416 case Builtin::BI__sync_val_compare_and_swap_8:
1417 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001418 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +00001419 NumFixed = 2;
1420 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001421
Chris Lattner5caa3702009-05-08 06:58:22 +00001422 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001423 case Builtin::BI__sync_bool_compare_and_swap_1:
1424 case Builtin::BI__sync_bool_compare_and_swap_2:
1425 case Builtin::BI__sync_bool_compare_and_swap_4:
1426 case Builtin::BI__sync_bool_compare_and_swap_8:
1427 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001428 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +00001429 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001430 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001431 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001432
1433 case Builtin::BI__sync_lock_test_and_set:
1434 case Builtin::BI__sync_lock_test_and_set_1:
1435 case Builtin::BI__sync_lock_test_and_set_2:
1436 case Builtin::BI__sync_lock_test_and_set_4:
1437 case Builtin::BI__sync_lock_test_and_set_8:
1438 case Builtin::BI__sync_lock_test_and_set_16:
1439 BuiltinIndex = 12;
1440 break;
1441
Chris Lattner5caa3702009-05-08 06:58:22 +00001442 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +00001443 case Builtin::BI__sync_lock_release_1:
1444 case Builtin::BI__sync_lock_release_2:
1445 case Builtin::BI__sync_lock_release_4:
1446 case Builtin::BI__sync_lock_release_8:
1447 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001448 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +00001449 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001450 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001451 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001452
1453 case Builtin::BI__sync_swap:
1454 case Builtin::BI__sync_swap_1:
1455 case Builtin::BI__sync_swap_2:
1456 case Builtin::BI__sync_swap_4:
1457 case Builtin::BI__sync_swap_8:
1458 case Builtin::BI__sync_swap_16:
1459 BuiltinIndex = 14;
1460 break;
Chris Lattner5caa3702009-05-08 06:58:22 +00001461 }
Mike Stump1eb44332009-09-09 15:08:12 +00001462
Chris Lattner5caa3702009-05-08 06:58:22 +00001463 // Now that we know how many fixed arguments we expect, first check that we
1464 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +00001465 if (TheCall->getNumArgs() < 1+NumFixed) {
1466 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1467 << 0 << 1+NumFixed << TheCall->getNumArgs()
1468 << TheCall->getCallee()->getSourceRange();
1469 return ExprError();
1470 }
Mike Stump1eb44332009-09-09 15:08:12 +00001471
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001472 // Get the decl for the concrete builtin from this, we can tell what the
1473 // concrete integer type we should convert to is.
1474 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1475 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara2ad11cd2012-09-22 09:05:22 +00001476 FunctionDecl *NewBuiltinDecl;
1477 if (NewBuiltinID == BuiltinID)
1478 NewBuiltinDecl = FDecl;
1479 else {
1480 // Perform builtin lookup to avoid redeclaring it.
1481 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1482 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1483 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1484 assert(Res.getFoundDecl());
1485 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1486 if (NewBuiltinDecl == 0)
1487 return ExprError();
1488 }
Chandler Carruthd2014572010-07-09 18:59:35 +00001489
John McCallf871d0c2010-08-07 06:22:56 +00001490 // The first argument --- the pointer --- has a fixed type; we
1491 // deduce the types of the rest of the arguments accordingly. Walk
1492 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +00001493 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +00001494 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +00001495
Chris Lattner5caa3702009-05-08 06:58:22 +00001496 // GCC does an implicit conversion to the pointer or integer ValType. This
1497 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +00001498 // Initialize the argument.
1499 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1500 ValType, /*consume*/ false);
1501 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +00001502 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +00001503 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001504
Chris Lattner5caa3702009-05-08 06:58:22 +00001505 // Okay, we have something that *can* be converted to the right type. Check
1506 // to see if there is a potentially weird extension going on here. This can
1507 // happen when you do an atomic operation on something like an char* and
1508 // pass in 42. The 42 gets converted to char. This is even more strange
1509 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +00001510 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +00001511 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +00001512 }
Mike Stump1eb44332009-09-09 15:08:12 +00001513
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001514 ASTContext& Context = this->getASTContext();
1515
1516 // Create a new DeclRefExpr to refer to the new decl.
1517 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1518 Context,
1519 DRE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001520 SourceLocation(),
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001521 NewBuiltinDecl,
John McCallf4b88a42012-03-10 09:33:50 +00001522 /*enclosing*/ false,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001523 DRE->getLocation(),
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001524 Context.BuiltinFnTy,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001525 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +00001526
Chris Lattner5caa3702009-05-08 06:58:22 +00001527 // Set the callee in the CallExpr.
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001528 // FIXME: This loses syntactic information.
1529 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1530 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1531 CK_BuiltinFnToFnPtr);
John Wiegley429bb272011-04-08 18:41:53 +00001532 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001533
Chandler Carruthdb4325b2010-07-18 07:23:17 +00001534 // Change the result type of the call to match the original value type. This
1535 // is arbitrary, but the codegen for these builtins ins design to handle it
1536 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +00001537 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001538
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001539 return TheCallResult;
Chris Lattner5caa3702009-05-08 06:58:22 +00001540}
1541
Chris Lattner69039812009-02-18 06:01:06 +00001542/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00001543/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00001544/// Note: It might also make sense to do the UTF-16 conversion here (would
1545/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00001546bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00001547 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00001548 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1549
Douglas Gregor5cee1192011-07-27 05:40:30 +00001550 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001551 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1552 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001553 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001554 }
Mike Stump1eb44332009-09-09 15:08:12 +00001555
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001556 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001557 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001558 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001559 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divacky31ba6132012-09-06 15:59:27 +00001560 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001561 UTF16 *ToPtr = &ToBuf[0];
1562
1563 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1564 &ToPtr, ToPtr + NumBytes,
1565 strictConversion);
1566 // Check for conversion failure.
1567 if (Result != conversionOK)
1568 Diag(Arg->getLocStart(),
1569 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1570 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001571 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00001572}
1573
Chris Lattnerc27c6652007-12-20 00:05:45 +00001574/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1575/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00001576bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1577 Expr *Fn = TheCall->getCallee();
1578 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001579 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001580 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001581 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1582 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00001583 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001584 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00001585 return true;
1586 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00001587
1588 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00001589 return Diag(TheCall->getLocEnd(),
1590 diag::err_typecheck_call_too_few_args_at_least)
1591 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00001592 }
1593
John McCall5f8d6042011-08-27 01:09:30 +00001594 // Type-check the first argument normally.
1595 if (checkBuiltinArgument(*this, TheCall, 0))
1596 return true;
1597
Chris Lattnerc27c6652007-12-20 00:05:45 +00001598 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001599 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00001600 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001601 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00001602 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00001603 else if (FunctionDecl *FD = getCurFunctionDecl())
1604 isVariadic = FD->isVariadic();
1605 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001606 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00001607
Chris Lattnerc27c6652007-12-20 00:05:45 +00001608 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001609 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1610 return true;
1611 }
Mike Stump1eb44332009-09-09 15:08:12 +00001612
Chris Lattner30ce3442007-12-19 23:59:04 +00001613 // Verify that the second argument to the builtin is the last argument of the
1614 // current function or method.
1615 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00001616 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001617
Nico Weberb07d4482013-05-24 23:31:57 +00001618 // These are valid if SecondArgIsLastNamedArgument is false after the next
1619 // block.
1620 QualType Type;
1621 SourceLocation ParamLoc;
1622
Anders Carlsson88cf2262008-02-11 04:20:54 +00001623 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1624 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001625 // FIXME: This isn't correct for methods (results in bogus warning).
1626 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00001627 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001628 if (CurBlock)
1629 LastArg = *(CurBlock->TheDecl->param_end()-1);
1630 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00001631 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001632 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001633 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001634 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weberb07d4482013-05-24 23:31:57 +00001635
1636 Type = PV->getType();
1637 ParamLoc = PV->getLocation();
Chris Lattner30ce3442007-12-19 23:59:04 +00001638 }
1639 }
Mike Stump1eb44332009-09-09 15:08:12 +00001640
Chris Lattner30ce3442007-12-19 23:59:04 +00001641 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001642 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00001643 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weberb07d4482013-05-24 23:31:57 +00001644 else if (Type->isReferenceType()) {
1645 Diag(Arg->getLocStart(),
1646 diag::warn_va_start_of_reference_type_is_undefined);
1647 Diag(ParamLoc, diag::note_parameter_type) << Type;
1648 }
1649
Chris Lattner30ce3442007-12-19 23:59:04 +00001650 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00001651}
Chris Lattner30ce3442007-12-19 23:59:04 +00001652
Chris Lattner1b9a0792007-12-20 00:26:33 +00001653/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1654/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00001655bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1656 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001657 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001658 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001659 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001660 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001661 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001662 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001663 << SourceRange(TheCall->getArg(2)->getLocStart(),
1664 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001665
John Wiegley429bb272011-04-08 18:41:53 +00001666 ExprResult OrigArg0 = TheCall->getArg(0);
1667 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001668
Chris Lattner1b9a0792007-12-20 00:26:33 +00001669 // Do standard promotions between the two arguments, returning their common
1670 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001671 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001672 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1673 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001674
1675 // Make sure any conversions are pushed back into the call; this is
1676 // type safe since unordered compare builtins are declared as "_Bool
1677 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001678 TheCall->setArg(0, OrigArg0.get());
1679 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001680
John Wiegley429bb272011-04-08 18:41:53 +00001681 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001682 return false;
1683
Chris Lattner1b9a0792007-12-20 00:26:33 +00001684 // If the common type isn't a real floating type, then the arguments were
1685 // invalid for this operation.
Eli Friedman860a3192012-06-16 02:19:17 +00001686 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001687 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001688 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001689 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1690 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001691
Chris Lattner1b9a0792007-12-20 00:26:33 +00001692 return false;
1693}
1694
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001695/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1696/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001697/// to check everything. We expect the last argument to be a floating point
1698/// value.
1699bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1700 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001701 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001702 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001703 if (TheCall->getNumArgs() > NumArgs)
1704 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001705 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001706 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001707 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001708 (*(TheCall->arg_end()-1))->getLocEnd());
1709
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001710 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001711
Eli Friedman9ac6f622009-08-31 20:06:00 +00001712 if (OrigArg->isTypeDependent())
1713 return false;
1714
Chris Lattner81368fb2010-05-06 05:50:07 +00001715 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001716 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001717 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001718 diag::err_typecheck_call_invalid_unary_fp)
1719 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001720
Chris Lattner81368fb2010-05-06 05:50:07 +00001721 // If this is an implicit conversion from float -> double, remove it.
1722 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1723 Expr *CastArg = Cast->getSubExpr();
1724 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1725 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1726 "promotion from float to double is the only expected cast here");
1727 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001728 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner81368fb2010-05-06 05:50:07 +00001729 }
1730 }
1731
Eli Friedman9ac6f622009-08-31 20:06:00 +00001732 return false;
1733}
1734
Eli Friedmand38617c2008-05-14 19:38:39 +00001735/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1736// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001737ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001738 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001739 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001740 diag::err_typecheck_call_too_few_args_at_least)
Craig Topperb44545a2013-07-28 21:50:10 +00001741 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1742 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001743
Nate Begeman37b6a572010-06-08 00:16:34 +00001744 // Determine which of the following types of shufflevector we're checking:
1745 // 1) unary, vector mask: (lhs, mask)
1746 // 2) binary, vector mask: (lhs, rhs, mask)
1747 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1748 QualType resType = TheCall->getArg(0)->getType();
1749 unsigned numElements = 0;
Craig Toppere3fbbe92013-07-19 04:46:31 +00001750
Douglas Gregorcde01732009-05-19 22:10:17 +00001751 if (!TheCall->getArg(0)->isTypeDependent() &&
1752 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001753 QualType LHSType = TheCall->getArg(0)->getType();
1754 QualType RHSType = TheCall->getArg(1)->getType();
Craig Toppere3fbbe92013-07-19 04:46:31 +00001755
Craig Topperbbe759c2013-07-29 06:47:04 +00001756 if (!LHSType->isVectorType() || !RHSType->isVectorType())
1757 return ExprError(Diag(TheCall->getLocStart(),
1758 diag::err_shufflevector_non_vector)
1759 << SourceRange(TheCall->getArg(0)->getLocStart(),
1760 TheCall->getArg(1)->getLocEnd()));
Craig Toppere3fbbe92013-07-19 04:46:31 +00001761
Nate Begeman37b6a572010-06-08 00:16:34 +00001762 numElements = LHSType->getAs<VectorType>()->getNumElements();
1763 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001764
Nate Begeman37b6a572010-06-08 00:16:34 +00001765 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1766 // with mask. If so, verify that RHS is an integer vector type with the
1767 // same number of elts as lhs.
1768 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru4cb3d902013-07-06 08:00:09 +00001769 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001770 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbbe759c2013-07-29 06:47:04 +00001771 return ExprError(Diag(TheCall->getLocStart(),
1772 diag::err_shufflevector_incompatible_vector)
1773 << SourceRange(TheCall->getArg(1)->getLocStart(),
1774 TheCall->getArg(1)->getLocEnd()));
Craig Toppere3fbbe92013-07-19 04:46:31 +00001775 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbbe759c2013-07-29 06:47:04 +00001776 return ExprError(Diag(TheCall->getLocStart(),
1777 diag::err_shufflevector_incompatible_vector)
1778 << SourceRange(TheCall->getArg(0)->getLocStart(),
1779 TheCall->getArg(1)->getLocEnd()));
Nate Begeman37b6a572010-06-08 00:16:34 +00001780 } else if (numElements != numResElements) {
1781 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001782 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001783 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001784 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001785 }
1786
1787 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001788 if (TheCall->getArg(i)->isTypeDependent() ||
1789 TheCall->getArg(i)->isValueDependent())
1790 continue;
1791
Nate Begeman37b6a572010-06-08 00:16:34 +00001792 llvm::APSInt Result(32);
1793 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1794 return ExprError(Diag(TheCall->getLocStart(),
Craig Topperb44545a2013-07-28 21:50:10 +00001795 diag::err_shufflevector_nonconstant_argument)
1796 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001797
Craig Topper6f4f8082013-08-03 17:40:38 +00001798 // Allow -1 which will be translated to undef in the IR.
1799 if (Result.isSigned() && Result.isAllOnesValue())
1800 continue;
1801
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001802 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001803 return ExprError(Diag(TheCall->getLocStart(),
Craig Topperb44545a2013-07-28 21:50:10 +00001804 diag::err_shufflevector_argument_too_large)
1805 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001806 }
1807
Chris Lattner5f9e2722011-07-23 10:55:15 +00001808 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001809
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001810 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001811 exprs.push_back(TheCall->getArg(i));
1812 TheCall->setArg(i, 0);
1813 }
1814
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001815 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001816 TheCall->getCallee()->getLocStart(),
1817 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001818}
Chris Lattner30ce3442007-12-19 23:59:04 +00001819
Daniel Dunbar4493f792008-07-21 22:59:13 +00001820/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1821// This is declared to take (const void*, ...) and can take two
1822// optional constant int args.
1823bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001824 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001825
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001826 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001827 return Diag(TheCall->getLocEnd(),
1828 diag::err_typecheck_call_too_many_args_at_most)
1829 << 0 /*function call*/ << 3 << NumArgs
1830 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001831
1832 // Argument 0 is checked for us and the remaining arguments must be
1833 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001834 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001835 Expr *Arg = TheCall->getArg(i);
Douglas Gregor592a4232012-06-29 01:05:22 +00001836
1837 // We can't check the value of a dependent argument.
1838 if (Arg->isTypeDependent() || Arg->isValueDependent())
1839 continue;
1840
Eli Friedman9aef7262009-12-04 00:30:06 +00001841 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001842 if (SemaBuiltinConstantArg(TheCall, i, Result))
1843 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001844
Daniel Dunbar4493f792008-07-21 22:59:13 +00001845 // FIXME: gcc issues a warning and rewrites these to 0. These
1846 // seems especially odd for the third argument since the default
1847 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001848 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001849 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001850 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001851 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001852 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001853 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001854 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001855 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001856 }
1857 }
1858
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001859 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001860}
1861
Eric Christopher691ebc32010-04-17 02:26:23 +00001862/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1863/// TheCall is a constant expression.
1864bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1865 llvm::APSInt &Result) {
1866 Expr *Arg = TheCall->getArg(ArgNum);
1867 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1868 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1869
1870 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1871
1872 if (!Arg->isIntegerConstantExpr(Result, Context))
1873 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001874 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001875
Chris Lattner21fb98e2009-09-23 06:06:36 +00001876 return false;
1877}
1878
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001879/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1880/// int type). This simply type checks that type is one of the defined
1881/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001882// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001883bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001884 llvm::APSInt Result;
Douglas Gregor592a4232012-06-29 01:05:22 +00001885
1886 // We can't check the value of a dependent argument.
1887 if (TheCall->getArg(1)->isTypeDependent() ||
1888 TheCall->getArg(1)->isValueDependent())
1889 return false;
1890
Eric Christopher691ebc32010-04-17 02:26:23 +00001891 // Check constant-ness first.
1892 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1893 return true;
1894
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001895 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001896 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001897 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1898 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001899 }
1900
1901 return false;
1902}
1903
Eli Friedman586d6a82009-05-03 06:04:26 +00001904/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001905/// This checks that val is a constant 1.
1906bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1907 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001908 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001909
Eric Christopher691ebc32010-04-17 02:26:23 +00001910 // TODO: This is less than ideal. Overload this to take a value.
1911 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1912 return true;
1913
1914 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001915 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1916 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1917
1918 return false;
1919}
1920
Richard Smith0e218972013-08-05 18:49:43 +00001921namespace {
1922enum StringLiteralCheckType {
1923 SLCT_NotALiteral,
1924 SLCT_UncheckedLiteral,
1925 SLCT_CheckedLiteral
1926};
1927}
1928
Richard Smith831421f2012-06-25 20:30:08 +00001929// Determine if an expression is a string literal or constant string.
1930// If this function returns false on the arguments to a function expecting a
1931// format string, we will usually need to emit a warning.
1932// True string literals are then checked by CheckFormatString.
Richard Smith0e218972013-08-05 18:49:43 +00001933static StringLiteralCheckType
1934checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
1935 bool HasVAListArg, unsigned format_idx,
1936 unsigned firstDataArg, Sema::FormatStringType Type,
1937 Sema::VariadicCallType CallType, bool InFunctionCall,
1938 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001939 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001940 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith831421f2012-06-25 20:30:08 +00001941 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001942
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001943 E = E->IgnoreParenCasts();
Peter Collingbournef111d932011-04-15 00:35:48 +00001944
Richard Smith0e218972013-08-05 18:49:43 +00001945 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikiea73cdcb2012-02-10 21:07:25 +00001946 // Technically -Wformat-nonliteral does not warn about this case.
1947 // The behavior of printf and friends in this case is implementation
1948 // dependent. Ideally if the format string cannot be null then
1949 // it should have a 'nonnull' attribute in the function prototype.
Richard Smith0e218972013-08-05 18:49:43 +00001950 return SLCT_UncheckedLiteral;
David Blaikiea73cdcb2012-02-10 21:07:25 +00001951
Ted Kremenekd30ef872009-01-12 23:09:09 +00001952 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001953 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001954 case Stmt::ConditionalOperatorClass: {
Richard Smith831421f2012-06-25 20:30:08 +00001955 // The expression is a literal if both sub-expressions were, and it was
1956 // completely checked only if both sub-expressions were checked.
1957 const AbstractConditionalOperator *C =
1958 cast<AbstractConditionalOperator>(E);
1959 StringLiteralCheckType Left =
Richard Smith0e218972013-08-05 18:49:43 +00001960 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00001961 HasVAListArg, format_idx, firstDataArg,
Richard Smith0e218972013-08-05 18:49:43 +00001962 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00001963 if (Left == SLCT_NotALiteral)
1964 return SLCT_NotALiteral;
1965 StringLiteralCheckType Right =
Richard Smith0e218972013-08-05 18:49:43 +00001966 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00001967 HasVAListArg, format_idx, firstDataArg,
Richard Smith0e218972013-08-05 18:49:43 +00001968 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00001969 return Left < Right ? Left : Right;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001970 }
1971
1972 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001973 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1974 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001975 }
1976
John McCall56ca35d2011-02-17 10:25:35 +00001977 case Stmt::OpaqueValueExprClass:
1978 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1979 E = src;
1980 goto tryAgain;
1981 }
Richard Smith831421f2012-06-25 20:30:08 +00001982 return SLCT_NotALiteral;
John McCall56ca35d2011-02-17 10:25:35 +00001983
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001984 case Stmt::PredefinedExprClass:
1985 // While __func__, etc., are technically not string literals, they
1986 // cannot contain format specifiers and thus are not a security
1987 // liability.
Richard Smith831421f2012-06-25 20:30:08 +00001988 return SLCT_UncheckedLiteral;
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001989
Ted Kremenek082d9362009-03-20 21:35:28 +00001990 case Stmt::DeclRefExprClass: {
1991 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001992
Ted Kremenek082d9362009-03-20 21:35:28 +00001993 // As an exception, do not flag errors for variables binding to
1994 // const string literals.
1995 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1996 bool isConstant = false;
1997 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001998
Richard Smith0e218972013-08-05 18:49:43 +00001999 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2000 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002001 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smith0e218972013-08-05 18:49:43 +00002002 isConstant = T.isConstant(S.Context) &&
2003 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupase98e5b52012-01-25 10:35:33 +00002004 } else if (T->isObjCObjectPointerType()) {
2005 // In ObjC, there is usually no "const ObjectPointer" type,
2006 // so don't check if the pointee type is constant.
Richard Smith0e218972013-08-05 18:49:43 +00002007 isConstant = T.isConstant(S.Context);
Ted Kremenek082d9362009-03-20 21:35:28 +00002008 }
Mike Stump1eb44332009-09-09 15:08:12 +00002009
Ted Kremenek082d9362009-03-20 21:35:28 +00002010 if (isConstant) {
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00002011 if (const Expr *Init = VD->getAnyInitializer()) {
2012 // Look through initializers like const char c[] = { "foo" }
2013 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2014 if (InitList->isStringLiteralInit())
2015 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2016 }
Richard Smith0e218972013-08-05 18:49:43 +00002017 return checkFormatStringExpr(S, Init, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002018 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002019 firstDataArg, Type, CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002020 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00002021 }
Ted Kremenek082d9362009-03-20 21:35:28 +00002022 }
Mike Stump1eb44332009-09-09 15:08:12 +00002023
Anders Carlssond966a552009-06-28 19:55:58 +00002024 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2025 // special check to see if the format string is a function parameter
2026 // of the function calling the printf function. If the function
2027 // has an attribute indicating it is a printf-like function, then we
2028 // should suppress warnings concerning non-literals being used in a call
2029 // to a vprintf function. For example:
2030 //
2031 // void
2032 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2033 // va_list ap;
2034 // va_start(ap, fmt);
2035 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2036 // ...
Richard Smith0e218972013-08-05 18:49:43 +00002037 // }
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00002038 if (HasVAListArg) {
2039 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2040 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2041 int PVIndex = PV->getFunctionScopeIndex() + 1;
2042 for (specific_attr_iterator<FormatAttr>
2043 i = ND->specific_attr_begin<FormatAttr>(),
2044 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
2045 FormatAttr *PVFormat = *i;
2046 // adjust for implicit parameter
2047 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2048 if (MD->isInstance())
2049 ++PVIndex;
2050 // We also check if the formats are compatible.
2051 // We can't pass a 'scanf' string to a 'printf' function.
2052 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smith0e218972013-08-05 18:49:43 +00002053 Type == S.GetFormatStringType(PVFormat))
Richard Smith831421f2012-06-25 20:30:08 +00002054 return SLCT_UncheckedLiteral;
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00002055 }
2056 }
2057 }
2058 }
Ted Kremenek082d9362009-03-20 21:35:28 +00002059 }
Mike Stump1eb44332009-09-09 15:08:12 +00002060
Richard Smith831421f2012-06-25 20:30:08 +00002061 return SLCT_NotALiteral;
Ted Kremenek082d9362009-03-20 21:35:28 +00002062 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00002063
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00002064 case Stmt::CallExprClass:
2065 case Stmt::CXXMemberCallExprClass: {
Anders Carlsson8f031b32009-06-27 04:05:33 +00002066 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00002067 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2068 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2069 unsigned ArgIndex = FA->getFormatIdx();
2070 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2071 if (MD->isInstance())
2072 --ArgIndex;
2073 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00002074
Richard Smith0e218972013-08-05 18:49:43 +00002075 return checkFormatStringExpr(S, Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002076 HasVAListArg, format_idx, firstDataArg,
Richard Smith0e218972013-08-05 18:49:43 +00002077 Type, CallType, InFunctionCall,
2078 CheckedVarArgs);
Jordan Rose50687312012-06-04 23:52:23 +00002079 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2080 unsigned BuiltinID = FD->getBuiltinID();
2081 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2082 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2083 const Expr *Arg = CE->getArg(0);
Richard Smith0e218972013-08-05 18:49:43 +00002084 return checkFormatStringExpr(S, Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002085 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002086 firstDataArg, Type, CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002087 InFunctionCall, CheckedVarArgs);
Jordan Rose50687312012-06-04 23:52:23 +00002088 }
Anders Carlsson8f031b32009-06-27 04:05:33 +00002089 }
2090 }
Mike Stump1eb44332009-09-09 15:08:12 +00002091
Richard Smith831421f2012-06-25 20:30:08 +00002092 return SLCT_NotALiteral;
Anders Carlsson8f031b32009-06-27 04:05:33 +00002093 }
Ted Kremenek082d9362009-03-20 21:35:28 +00002094 case Stmt::ObjCStringLiteralClass:
2095 case Stmt::StringLiteralClass: {
2096 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00002097
Ted Kremenek082d9362009-03-20 21:35:28 +00002098 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00002099 StrE = ObjCFExpr->getString();
2100 else
Ted Kremenek082d9362009-03-20 21:35:28 +00002101 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002102
Ted Kremenekd30ef872009-01-12 23:09:09 +00002103 if (StrE) {
Richard Smith0e218972013-08-05 18:49:43 +00002104 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2105 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002106 return SLCT_CheckedLiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002107 }
Mike Stump1eb44332009-09-09 15:08:12 +00002108
Richard Smith831421f2012-06-25 20:30:08 +00002109 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002110 }
Mike Stump1eb44332009-09-09 15:08:12 +00002111
Ted Kremenek082d9362009-03-20 21:35:28 +00002112 default:
Richard Smith831421f2012-06-25 20:30:08 +00002113 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002114 }
2115}
2116
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00002117void
Mike Stump1eb44332009-09-09 15:08:12 +00002118Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00002119 const Expr * const *ExprArgs,
2120 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00002121 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
2122 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00002123 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00002124 const Expr *ArgExpr = ExprArgs[*i];
Nick Lewycky3edf3872013-01-23 05:08:29 +00002125
2126 // As a special case, transparent unions initialized with zero are
2127 // considered null for the purposes of the nonnull attribute.
2128 if (const RecordType *UT = ArgExpr->getType()->getAsUnionType()) {
2129 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2130 if (const CompoundLiteralExpr *CLE =
2131 dyn_cast<CompoundLiteralExpr>(ArgExpr))
2132 if (const InitListExpr *ILE =
2133 dyn_cast<InitListExpr>(CLE->getInitializer()))
2134 ArgExpr = ILE->getInit(0);
2135 }
2136
2137 bool Result;
2138 if (ArgExpr->EvaluateAsBooleanCondition(Result, Context) && !Result)
Nick Lewycky909a70d2011-03-25 01:44:32 +00002139 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00002140 }
2141}
Ted Kremenekd30ef872009-01-12 23:09:09 +00002142
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002143Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
2144 return llvm::StringSwitch<FormatStringType>(Format->getType())
2145 .Case("scanf", FST_Scanf)
2146 .Cases("printf", "printf0", FST_Printf)
2147 .Cases("NSString", "CFString", FST_NSString)
2148 .Case("strftime", FST_Strftime)
2149 .Case("strfmon", FST_Strfmon)
2150 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2151 .Default(FST_Unknown);
2152}
2153
Jordan Roseddcfbc92012-07-19 18:10:23 +00002154/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek826a3452010-07-16 02:11:22 +00002155/// functions) for correct use of format strings.
Richard Smith831421f2012-06-25 20:30:08 +00002156/// Returns true if a format string has been fully checked.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002157bool Sema::CheckFormatArguments(const FormatAttr *Format,
2158 ArrayRef<const Expr *> Args,
2159 bool IsCXXMember,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002160 VariadicCallType CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002161 SourceLocation Loc, SourceRange Range,
2162 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith831421f2012-06-25 20:30:08 +00002163 FormatStringInfo FSI;
2164 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002165 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith831421f2012-06-25 20:30:08 +00002166 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smith0e218972013-08-05 18:49:43 +00002167 CallType, Loc, Range, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002168 return false;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002169}
Sebastian Redl4a2614e2009-11-17 18:02:24 +00002170
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002171bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002172 bool HasVAListArg, unsigned format_idx,
2173 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002174 VariadicCallType CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002175 SourceLocation Loc, SourceRange Range,
2176 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002177 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002178 if (format_idx >= Args.size()) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002179 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith831421f2012-06-25 20:30:08 +00002180 return false;
Ted Kremenek71895b92007-08-14 17:39:48 +00002181 }
Mike Stump1eb44332009-09-09 15:08:12 +00002182
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002183 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00002184
Chris Lattner59907c42007-08-10 20:18:51 +00002185 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00002186 //
Ted Kremenek71895b92007-08-14 17:39:48 +00002187 // Dynamically generated format strings are difficult to
2188 // automatically vet at compile time. Requiring that format strings
2189 // are string literals: (1) permits the checking of format strings by
2190 // the compiler and thereby (2) can practically remove the source of
2191 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002192
Mike Stump1eb44332009-09-09 15:08:12 +00002193 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002194 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00002195 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002196 // the same format string checking logic for both ObjC and C strings.
Richard Smith831421f2012-06-25 20:30:08 +00002197 StringLiteralCheckType CT =
Richard Smith0e218972013-08-05 18:49:43 +00002198 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2199 format_idx, firstDataArg, Type, CallType,
2200 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002201 if (CT != SLCT_NotALiteral)
2202 // Literal format string found, check done!
2203 return CT == SLCT_CheckedLiteral;
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002204
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00002205 // Strftime is particular as it always uses a single 'time' argument,
2206 // so it is safe to pass a non-literal string.
2207 if (Type == FST_Strftime)
Richard Smith831421f2012-06-25 20:30:08 +00002208 return false;
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00002209
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00002210 // Do not emit diag when the string param is a macro expansion and the
2211 // format is either NSString or CFString. This is a hack to prevent
2212 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2213 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupasdc170202012-05-04 21:08:08 +00002214 if (Type == FST_NSString &&
2215 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith831421f2012-06-25 20:30:08 +00002216 return false;
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00002217
Chris Lattner655f1412009-04-29 04:59:47 +00002218 // If there are no arguments specified, warn with -Wformat-security, otherwise
2219 // warn only with -Wformat-nonliteral.
Eli Friedman2243e782013-06-18 18:10:01 +00002220 if (Args.size() == firstDataArg)
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002221 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00002222 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00002223 << OrigFormatExpr->getSourceRange();
2224 else
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002225 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00002226 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00002227 << OrigFormatExpr->getSourceRange();
Richard Smith831421f2012-06-25 20:30:08 +00002228 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002229}
Ted Kremenek71895b92007-08-14 17:39:48 +00002230
Ted Kremeneke0e53132010-01-28 23:39:18 +00002231namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00002232class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2233protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00002234 Sema &S;
2235 const StringLiteral *FExpr;
2236 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00002237 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00002238 const unsigned NumDataArgs;
Ted Kremeneke0e53132010-01-28 23:39:18 +00002239 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00002240 const bool HasVAListArg;
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002241 ArrayRef<const Expr *> Args;
Ted Kremenek0d277352010-01-29 01:06:55 +00002242 unsigned FormatIdx;
Richard Smith0e218972013-08-05 18:49:43 +00002243 llvm::SmallBitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00002244 bool usesPositionalArgs;
2245 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00002246 bool inFunctionCall;
Jordan Roseddcfbc92012-07-19 18:10:23 +00002247 Sema::VariadicCallType CallType;
Richard Smith0e218972013-08-05 18:49:43 +00002248 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002249public:
Ted Kremenek826a3452010-07-16 02:11:22 +00002250 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00002251 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002252 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002253 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002254 unsigned formatIdx, bool inFunctionCall,
Richard Smith0e218972013-08-05 18:49:43 +00002255 Sema::VariadicCallType callType,
2256 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremeneke0e53132010-01-28 23:39:18 +00002257 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose50687312012-06-04 23:52:23 +00002258 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2259 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002260 Args(Args), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00002261 usesPositionalArgs(false), atFirstArg(true),
Richard Smith0e218972013-08-05 18:49:43 +00002262 inFunctionCall(inFunctionCall), CallType(callType),
2263 CheckedVarArgs(CheckedVarArgs) {
2264 CoveredArgs.resize(numDataArgs);
2265 CoveredArgs.reset();
2266 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002267
Ted Kremenek07d161f2010-01-29 01:50:07 +00002268 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002269
Ted Kremenek826a3452010-07-16 02:11:22 +00002270 void HandleIncompleteSpecifier(const char *startSpecifier,
2271 unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00002272
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002273 void HandleInvalidLengthModifier(
2274 const analyze_format_string::FormatSpecifier &FS,
2275 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00002276 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002277
Hans Wennborg76517422012-02-22 10:17:01 +00002278 void HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00002279 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00002280 const char *startSpecifier, unsigned specifierLen);
2281
2282 void HandleNonStandardConversionSpecifier(
2283 const analyze_format_string::ConversionSpecifier &CS,
2284 const char *startSpecifier, unsigned specifierLen);
2285
Hans Wennborgf8562642012-03-09 10:10:54 +00002286 virtual void HandlePosition(const char *startPos, unsigned posLen);
2287
Ted Kremenekefaff192010-02-27 01:41:03 +00002288 virtual void HandleInvalidPosition(const char *startSpecifier,
2289 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00002290 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00002291
2292 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
2293
Ted Kremeneke0e53132010-01-28 23:39:18 +00002294 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002295
Richard Trieu55733de2011-10-28 00:41:25 +00002296 template <typename Range>
2297 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2298 const Expr *ArgumentExpr,
2299 PartialDiagnostic PDiag,
2300 SourceLocation StringLoc,
2301 bool IsStringLocation, Range StringRange,
Dmitri Gribenko55431692013-05-05 00:41:58 +00002302 ArrayRef<FixItHint> Fixit = None);
Richard Trieu55733de2011-10-28 00:41:25 +00002303
Ted Kremenek826a3452010-07-16 02:11:22 +00002304protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002305 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2306 const char *startSpec,
2307 unsigned specifierLen,
2308 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00002309
2310 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2311 const char *startSpec,
2312 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002313
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002314 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00002315 CharSourceRange getSpecifierRange(const char *startSpecifier,
2316 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002317 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002318
Ted Kremenek0d277352010-01-29 01:06:55 +00002319 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00002320
2321 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2322 const analyze_format_string::ConversionSpecifier &CS,
2323 const char *startSpecifier, unsigned specifierLen,
2324 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00002325
2326 template <typename Range>
2327 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2328 bool IsStringLocation, Range StringRange,
Dmitri Gribenko55431692013-05-05 00:41:58 +00002329 ArrayRef<FixItHint> Fixit = None);
Richard Trieu55733de2011-10-28 00:41:25 +00002330
2331 void CheckPositionalAndNonpositionalArgs(
2332 const analyze_format_string::FormatSpecifier *FS);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002333};
2334}
2335
Ted Kremenek826a3452010-07-16 02:11:22 +00002336SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00002337 return OrigFormatExpr->getSourceRange();
2338}
2339
Ted Kremenek826a3452010-07-16 02:11:22 +00002340CharSourceRange CheckFormatHandler::
2341getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002342 SourceLocation Start = getLocationOfByte(startSpecifier);
2343 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2344
2345 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002346 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00002347
2348 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002349}
2350
Ted Kremenek826a3452010-07-16 02:11:22 +00002351SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002352 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002353}
2354
Ted Kremenek826a3452010-07-16 02:11:22 +00002355void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2356 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00002357 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2358 getLocationOfByte(startSpecifier),
2359 /*IsStringLocation*/true,
2360 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00002361}
2362
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002363void CheckFormatHandler::HandleInvalidLengthModifier(
2364 const analyze_format_string::FormatSpecifier &FS,
2365 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00002366 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002367 using namespace analyze_format_string;
2368
2369 const LengthModifier &LM = FS.getLengthModifier();
2370 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2371
2372 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002373 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002374 if (FixedLM) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002375 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002376 getLocationOfByte(LM.getStart()),
2377 /*IsStringLocation*/true,
2378 getSpecifierRange(startSpecifier, specifierLen));
2379
2380 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2381 << FixedLM->toString()
2382 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2383
2384 } else {
Jordan Rose8be066e2012-09-08 04:00:12 +00002385 FixItHint Hint;
2386 if (DiagID == diag::warn_format_nonsensical_length)
2387 Hint = FixItHint::CreateRemoval(LMRange);
2388
2389 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002390 getLocationOfByte(LM.getStart()),
2391 /*IsStringLocation*/true,
2392 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose8be066e2012-09-08 04:00:12 +00002393 Hint);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002394 }
2395}
2396
Hans Wennborg76517422012-02-22 10:17:01 +00002397void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00002398 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00002399 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002400 using namespace analyze_format_string;
2401
2402 const LengthModifier &LM = FS.getLengthModifier();
2403 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2404
2405 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002406 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose8be066e2012-09-08 04:00:12 +00002407 if (FixedLM) {
2408 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2409 << LM.toString() << 0,
2410 getLocationOfByte(LM.getStart()),
2411 /*IsStringLocation*/true,
2412 getSpecifierRange(startSpecifier, specifierLen));
2413
2414 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2415 << FixedLM->toString()
2416 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2417
2418 } else {
2419 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2420 << LM.toString() << 0,
2421 getLocationOfByte(LM.getStart()),
2422 /*IsStringLocation*/true,
2423 getSpecifierRange(startSpecifier, specifierLen));
2424 }
Hans Wennborg76517422012-02-22 10:17:01 +00002425}
2426
2427void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2428 const analyze_format_string::ConversionSpecifier &CS,
2429 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose670941c2012-09-13 02:11:15 +00002430 using namespace analyze_format_string;
2431
2432 // See if we know how to fix this conversion specifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002433 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose670941c2012-09-13 02:11:15 +00002434 if (FixedCS) {
2435 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2436 << CS.toString() << /*conversion specifier*/1,
2437 getLocationOfByte(CS.getStart()),
2438 /*IsStringLocation*/true,
2439 getSpecifierRange(startSpecifier, specifierLen));
2440
2441 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2442 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2443 << FixedCS->toString()
2444 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2445 } else {
2446 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2447 << CS.toString() << /*conversion specifier*/1,
2448 getLocationOfByte(CS.getStart()),
2449 /*IsStringLocation*/true,
2450 getSpecifierRange(startSpecifier, specifierLen));
2451 }
Hans Wennborg76517422012-02-22 10:17:01 +00002452}
2453
Hans Wennborgf8562642012-03-09 10:10:54 +00002454void CheckFormatHandler::HandlePosition(const char *startPos,
2455 unsigned posLen) {
2456 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2457 getLocationOfByte(startPos),
2458 /*IsStringLocation*/true,
2459 getSpecifierRange(startPos, posLen));
2460}
2461
Ted Kremenekefaff192010-02-27 01:41:03 +00002462void
Ted Kremenek826a3452010-07-16 02:11:22 +00002463CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2464 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00002465 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2466 << (unsigned) p,
2467 getLocationOfByte(startPos), /*IsStringLocation*/true,
2468 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002469}
2470
Ted Kremenek826a3452010-07-16 02:11:22 +00002471void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00002472 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00002473 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2474 getLocationOfByte(startPos),
2475 /*IsStringLocation*/true,
2476 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002477}
2478
Ted Kremenek826a3452010-07-16 02:11:22 +00002479void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose50687312012-06-04 23:52:23 +00002480 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0c069442011-03-15 21:18:48 +00002481 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00002482 EmitFormatDiagnostic(
2483 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2484 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2485 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00002486 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002487}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002488
Jordan Rose48716662012-07-19 18:10:08 +00002489// Note that this may return NULL if there was an error parsing or building
2490// one of the argument expressions.
Ted Kremenek826a3452010-07-16 02:11:22 +00002491const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002492 return Args[FirstDataArg + i];
Ted Kremenek826a3452010-07-16 02:11:22 +00002493}
2494
2495void CheckFormatHandler::DoneProcessing() {
2496 // Does the number of data arguments exceed the number of
2497 // format conversions in the format string?
2498 if (!HasVAListArg) {
2499 // Find any arguments that weren't covered.
2500 CoveredArgs.flip();
2501 signed notCoveredArg = CoveredArgs.find_first();
2502 if (notCoveredArg >= 0) {
2503 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose48716662012-07-19 18:10:08 +00002504 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2505 SourceLocation Loc = E->getLocStart();
2506 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2507 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2508 Loc, /*IsStringLocation*/false,
2509 getFormatStringRange());
2510 }
Bob Wilsonc03f2df2012-05-03 19:47:19 +00002511 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002512 }
2513 }
2514}
2515
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002516bool
2517CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2518 SourceLocation Loc,
2519 const char *startSpec,
2520 unsigned specifierLen,
2521 const char *csStart,
2522 unsigned csLen) {
2523
2524 bool keepGoing = true;
2525 if (argIndex < NumDataArgs) {
2526 // Consider the argument coverered, even though the specifier doesn't
2527 // make sense.
2528 CoveredArgs.set(argIndex);
2529 }
2530 else {
2531 // If argIndex exceeds the number of data arguments we
2532 // don't issue a warning because that is just a cascade of warnings (and
2533 // they may have intended '%%' anyway). We don't want to continue processing
2534 // the format string after this point, however, as we will like just get
2535 // gibberish when trying to match arguments.
2536 keepGoing = false;
2537 }
2538
Richard Trieu55733de2011-10-28 00:41:25 +00002539 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2540 << StringRef(csStart, csLen),
2541 Loc, /*IsStringLocation*/true,
2542 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002543
2544 return keepGoing;
2545}
2546
Richard Trieu55733de2011-10-28 00:41:25 +00002547void
2548CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2549 const char *startSpec,
2550 unsigned specifierLen) {
2551 EmitFormatDiagnostic(
2552 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2553 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2554}
2555
Ted Kremenek666a1972010-07-26 19:45:42 +00002556bool
2557CheckFormatHandler::CheckNumArgs(
2558 const analyze_format_string::FormatSpecifier &FS,
2559 const analyze_format_string::ConversionSpecifier &CS,
2560 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2561
2562 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002563 PartialDiagnostic PDiag = FS.usesPositionalArg()
2564 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2565 << (argIndex+1) << NumDataArgs)
2566 : S.PDiag(diag::warn_printf_insufficient_data_args);
2567 EmitFormatDiagnostic(
2568 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2569 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00002570 return false;
2571 }
2572 return true;
2573}
2574
Richard Trieu55733de2011-10-28 00:41:25 +00002575template<typename Range>
2576void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2577 SourceLocation Loc,
2578 bool IsStringLocation,
2579 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002580 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002581 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu55733de2011-10-28 00:41:25 +00002582 Loc, IsStringLocation, StringRange, FixIt);
2583}
2584
2585/// \brief If the format string is not within the funcion call, emit a note
2586/// so that the function call and string are in diagnostic messages.
2587///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002588/// \param InFunctionCall if true, the format string is within the function
Richard Trieu55733de2011-10-28 00:41:25 +00002589/// call and only one diagnostic message will be produced. Otherwise, an
2590/// extra note will be emitted pointing to location of the format string.
2591///
2592/// \param ArgumentExpr the expression that is passed as the format string
2593/// argument in the function call. Used for getting locations when two
2594/// diagnostics are emitted.
2595///
2596/// \param PDiag the callee should already have provided any strings for the
2597/// diagnostic message. This function only adds locations and fixits
2598/// to diagnostics.
2599///
2600/// \param Loc primary location for diagnostic. If two diagnostics are
2601/// required, one will be at Loc and a new SourceLocation will be created for
2602/// the other one.
2603///
2604/// \param IsStringLocation if true, Loc points to the format string should be
2605/// used for the note. Otherwise, Loc points to the argument list and will
2606/// be used with PDiag.
2607///
2608/// \param StringRange some or all of the string to highlight. This is
2609/// templated so it can accept either a CharSourceRange or a SourceRange.
2610///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002611/// \param FixIt optional fix it hint for the format string.
Richard Trieu55733de2011-10-28 00:41:25 +00002612template<typename Range>
2613void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2614 const Expr *ArgumentExpr,
2615 PartialDiagnostic PDiag,
2616 SourceLocation Loc,
2617 bool IsStringLocation,
2618 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002619 ArrayRef<FixItHint> FixIt) {
2620 if (InFunctionCall) {
2621 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2622 D << StringRange;
2623 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2624 I != E; ++I) {
2625 D << *I;
2626 }
2627 } else {
Richard Trieu55733de2011-10-28 00:41:25 +00002628 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2629 << ArgumentExpr->getSourceRange();
Jordan Roseec087352012-09-05 22:56:26 +00002630
2631 const Sema::SemaDiagnosticBuilder &Note =
2632 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2633 diag::note_format_string_defined);
2634
2635 Note << StringRange;
2636 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2637 I != E; ++I) {
2638 Note << *I;
2639 }
Richard Trieu55733de2011-10-28 00:41:25 +00002640 }
2641}
2642
Ted Kremenek826a3452010-07-16 02:11:22 +00002643//===--- CHECK: Printf format string checking ------------------------------===//
2644
2645namespace {
2646class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose50687312012-06-04 23:52:23 +00002647 bool ObjCContext;
Ted Kremenek826a3452010-07-16 02:11:22 +00002648public:
2649 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2650 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002651 unsigned numDataArgs, bool isObjC,
Ted Kremenek826a3452010-07-16 02:11:22 +00002652 const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002653 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002654 unsigned formatIdx, bool inFunctionCall,
Richard Smith0e218972013-08-05 18:49:43 +00002655 Sema::VariadicCallType CallType,
2656 llvm::SmallBitVector &CheckedVarArgs)
2657 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2658 numDataArgs, beg, hasVAListArg, Args,
2659 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
2660 ObjCContext(isObjC)
Jordan Roseddcfbc92012-07-19 18:10:23 +00002661 {}
2662
Ted Kremenek826a3452010-07-16 02:11:22 +00002663
2664 bool HandleInvalidPrintfConversionSpecifier(
2665 const analyze_printf::PrintfSpecifier &FS,
2666 const char *startSpecifier,
2667 unsigned specifierLen);
2668
2669 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2670 const char *startSpecifier,
2671 unsigned specifierLen);
Richard Smith831421f2012-06-25 20:30:08 +00002672 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2673 const char *StartSpecifier,
2674 unsigned SpecifierLen,
2675 const Expr *E);
2676
Ted Kremenek826a3452010-07-16 02:11:22 +00002677 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2678 const char *startSpecifier, unsigned specifierLen);
2679 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2680 const analyze_printf::OptionalAmount &Amt,
2681 unsigned type,
2682 const char *startSpecifier, unsigned specifierLen);
2683 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2684 const analyze_printf::OptionalFlag &flag,
2685 const char *startSpecifier, unsigned specifierLen);
2686 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2687 const analyze_printf::OptionalFlag &ignoredFlag,
2688 const analyze_printf::OptionalFlag &flag,
2689 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgf3749f42012-08-07 08:11:26 +00002690 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith831421f2012-06-25 20:30:08 +00002691 const Expr *E, const CharSourceRange &CSR);
2692
Ted Kremenek826a3452010-07-16 02:11:22 +00002693};
2694}
2695
2696bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2697 const analyze_printf::PrintfSpecifier &FS,
2698 const char *startSpecifier,
2699 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002700 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002701 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002702
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002703 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2704 getLocationOfByte(CS.getStart()),
2705 startSpecifier, specifierLen,
2706 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00002707}
2708
Ted Kremenek826a3452010-07-16 02:11:22 +00002709bool CheckPrintfHandler::HandleAmount(
2710 const analyze_format_string::OptionalAmount &Amt,
2711 unsigned k, const char *startSpecifier,
2712 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002713
2714 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002715 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002716 unsigned argIndex = Amt.getArgIndex();
2717 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002718 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2719 << k,
2720 getLocationOfByte(Amt.getStart()),
2721 /*IsStringLocation*/true,
2722 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002723 // Don't do any more checking. We will just emit
2724 // spurious errors.
2725 return false;
2726 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002727
Ted Kremenek0d277352010-01-29 01:06:55 +00002728 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00002729 // Although not in conformance with C99, we also allow the argument to be
2730 // an 'unsigned int' as that is a reasonably safe case. GCC also
2731 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002732 CoveredArgs.set(argIndex);
2733 const Expr *Arg = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00002734 if (!Arg)
2735 return false;
2736
Ted Kremenek0d277352010-01-29 01:06:55 +00002737 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002738
Hans Wennborgf3749f42012-08-07 08:11:26 +00002739 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2740 assert(AT.isValid());
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002741
Hans Wennborgf3749f42012-08-07 08:11:26 +00002742 if (!AT.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00002743 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgf3749f42012-08-07 08:11:26 +00002744 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00002745 << T << Arg->getSourceRange(),
2746 getLocationOfByte(Amt.getStart()),
2747 /*IsStringLocation*/true,
2748 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002749 // Don't do any more checking. We will just emit
2750 // spurious errors.
2751 return false;
2752 }
2753 }
2754 }
2755 return true;
2756}
Ted Kremenek0d277352010-01-29 01:06:55 +00002757
Tom Caree4ee9662010-06-17 19:00:27 +00002758void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00002759 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002760 const analyze_printf::OptionalAmount &Amt,
2761 unsigned type,
2762 const char *startSpecifier,
2763 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002764 const analyze_printf::PrintfConversionSpecifier &CS =
2765 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00002766
Richard Trieu55733de2011-10-28 00:41:25 +00002767 FixItHint fixit =
2768 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2769 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2770 Amt.getConstantLength()))
2771 : FixItHint();
2772
2773 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2774 << type << CS.toString(),
2775 getLocationOfByte(Amt.getStart()),
2776 /*IsStringLocation*/true,
2777 getSpecifierRange(startSpecifier, specifierLen),
2778 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00002779}
2780
Ted Kremenek826a3452010-07-16 02:11:22 +00002781void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002782 const analyze_printf::OptionalFlag &flag,
2783 const char *startSpecifier,
2784 unsigned specifierLen) {
2785 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002786 const analyze_printf::PrintfConversionSpecifier &CS =
2787 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00002788 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2789 << flag.toString() << CS.toString(),
2790 getLocationOfByte(flag.getPosition()),
2791 /*IsStringLocation*/true,
2792 getSpecifierRange(startSpecifier, specifierLen),
2793 FixItHint::CreateRemoval(
2794 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002795}
2796
2797void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00002798 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002799 const analyze_printf::OptionalFlag &ignoredFlag,
2800 const analyze_printf::OptionalFlag &flag,
2801 const char *startSpecifier,
2802 unsigned specifierLen) {
2803 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00002804 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2805 << ignoredFlag.toString() << flag.toString(),
2806 getLocationOfByte(ignoredFlag.getPosition()),
2807 /*IsStringLocation*/true,
2808 getSpecifierRange(startSpecifier, specifierLen),
2809 FixItHint::CreateRemoval(
2810 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002811}
2812
Richard Smith831421f2012-06-25 20:30:08 +00002813// Determines if the specified is a C++ class or struct containing
2814// a member with the specified name and kind (e.g. a CXXMethodDecl named
2815// "c_str()").
2816template<typename MemberKind>
2817static llvm::SmallPtrSet<MemberKind*, 1>
2818CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2819 const RecordType *RT = Ty->getAs<RecordType>();
2820 llvm::SmallPtrSet<MemberKind*, 1> Results;
2821
2822 if (!RT)
2823 return Results;
2824 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2825 if (!RD)
2826 return Results;
2827
2828 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2829 Sema::LookupMemberName);
2830
2831 // We just need to include all members of the right kind turned up by the
2832 // filter, at this point.
2833 if (S.LookupQualifiedName(R, RT->getDecl()))
2834 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2835 NamedDecl *decl = (*I)->getUnderlyingDecl();
2836 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2837 Results.insert(FK);
2838 }
2839 return Results;
2840}
2841
2842// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgf3749f42012-08-07 08:11:26 +00002843// better diagnostic if so. AT is assumed to be valid.
Richard Smith831421f2012-06-25 20:30:08 +00002844// Returns true when a c_str() conversion method is found.
2845bool CheckPrintfHandler::checkForCStrMembers(
Hans Wennborgf3749f42012-08-07 08:11:26 +00002846 const analyze_printf::ArgType &AT, const Expr *E,
Richard Smith831421f2012-06-25 20:30:08 +00002847 const CharSourceRange &CSR) {
2848 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2849
2850 MethodSet Results =
2851 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2852
2853 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2854 MI != ME; ++MI) {
2855 const CXXMethodDecl *Method = *MI;
2856 if (Method->getNumParams() == 0 &&
Hans Wennborgf3749f42012-08-07 08:11:26 +00002857 AT.matchesType(S.Context, Method->getResultType())) {
Richard Smith831421f2012-06-25 20:30:08 +00002858 // FIXME: Suggest parens if the expression needs them.
2859 SourceLocation EndLoc =
2860 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2861 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2862 << "c_str()"
2863 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2864 return true;
2865 }
2866 }
2867
2868 return false;
2869}
2870
Ted Kremeneke0e53132010-01-28 23:39:18 +00002871bool
Ted Kremenek826a3452010-07-16 02:11:22 +00002872CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002873 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00002874 const char *startSpecifier,
2875 unsigned specifierLen) {
2876
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002877 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00002878 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002879 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00002880
Ted Kremenekbaa40062010-07-19 22:01:06 +00002881 if (FS.consumesDataArgument()) {
2882 if (atFirstArg) {
2883 atFirstArg = false;
2884 usesPositionalArgs = FS.usesPositionalArg();
2885 }
2886 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002887 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2888 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002889 return false;
2890 }
Ted Kremenek0d277352010-01-29 01:06:55 +00002891 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002892
Ted Kremenekefaff192010-02-27 01:41:03 +00002893 // First check if the field width, precision, and conversion specifier
2894 // have matching data arguments.
2895 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2896 startSpecifier, specifierLen)) {
2897 return false;
2898 }
2899
2900 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2901 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002902 return false;
2903 }
2904
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002905 if (!CS.consumesDataArgument()) {
2906 // FIXME: Technically specifying a precision or field width here
2907 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002908 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002909 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002910
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002911 // Consume the argument.
2912 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00002913 if (argIndex < NumDataArgs) {
2914 // The check to see if the argIndex is valid will come later.
2915 // We set the bit here because we may exit early from this
2916 // function if we encounter some other error.
2917 CoveredArgs.set(argIndex);
2918 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002919
2920 // Check for using an Objective-C specific conversion specifier
2921 // in a non-ObjC literal.
Jordan Rose50687312012-06-04 23:52:23 +00002922 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002923 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2924 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002925 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002926
Tom Caree4ee9662010-06-17 19:00:27 +00002927 // Check for invalid use of field width
2928 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002929 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00002930 startSpecifier, specifierLen);
2931 }
2932
2933 // Check for invalid use of precision
2934 if (!FS.hasValidPrecision()) {
2935 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2936 startSpecifier, specifierLen);
2937 }
2938
2939 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00002940 if (!FS.hasValidThousandsGroupingPrefix())
2941 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002942 if (!FS.hasValidLeadingZeros())
2943 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2944 if (!FS.hasValidPlusPrefix())
2945 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00002946 if (!FS.hasValidSpacePrefix())
2947 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002948 if (!FS.hasValidAlternativeForm())
2949 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2950 if (!FS.hasValidLeftJustified())
2951 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2952
2953 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00002954 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2955 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2956 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002957 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2958 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2959 startSpecifier, specifierLen);
2960
2961 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002962 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00002963 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2964 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002965 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00002966 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002967 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00002968 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2969 diag::warn_format_non_standard_conversion_spec);
Tom Caree4ee9662010-06-17 19:00:27 +00002970
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002971 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
2972 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2973
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002974 // The remaining checks depend on the data arguments.
2975 if (HasVAListArg)
2976 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002977
Ted Kremenek666a1972010-07-26 19:45:42 +00002978 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002979 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002980
Jordan Rose48716662012-07-19 18:10:08 +00002981 const Expr *Arg = getDataArg(argIndex);
2982 if (!Arg)
2983 return true;
2984
2985 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith831421f2012-06-25 20:30:08 +00002986}
2987
Jordan Roseec087352012-09-05 22:56:26 +00002988static bool requiresParensToAddCast(const Expr *E) {
2989 // FIXME: We should have a general way to reason about operator
2990 // precedence and whether parens are actually needed here.
2991 // Take care of a few common cases where they aren't.
2992 const Expr *Inside = E->IgnoreImpCasts();
2993 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
2994 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
2995
2996 switch (Inside->getStmtClass()) {
2997 case Stmt::ArraySubscriptExprClass:
2998 case Stmt::CallExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002999 case Stmt::CharacterLiteralClass:
3000 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00003001 case Stmt::DeclRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003002 case Stmt::FloatingLiteralClass:
3003 case Stmt::IntegerLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00003004 case Stmt::MemberExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003005 case Stmt::ObjCArrayLiteralClass:
3006 case Stmt::ObjCBoolLiteralExprClass:
3007 case Stmt::ObjCBoxedExprClass:
3008 case Stmt::ObjCDictionaryLiteralClass:
3009 case Stmt::ObjCEncodeExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00003010 case Stmt::ObjCIvarRefExprClass:
3011 case Stmt::ObjCMessageExprClass:
3012 case Stmt::ObjCPropertyRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003013 case Stmt::ObjCStringLiteralClass:
3014 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00003015 case Stmt::ParenExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003016 case Stmt::StringLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00003017 case Stmt::UnaryOperatorClass:
3018 return false;
3019 default:
3020 return true;
3021 }
3022}
3023
Richard Smith831421f2012-06-25 20:30:08 +00003024bool
3025CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3026 const char *StartSpecifier,
3027 unsigned SpecifierLen,
3028 const Expr *E) {
3029 using namespace analyze_format_string;
3030 using namespace analyze_printf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003031 // Now type check the data expression that matches the
3032 // format specifier.
Hans Wennborgf3749f42012-08-07 08:11:26 +00003033 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3034 ObjCContext);
Jordan Rose614a8652012-09-05 22:56:19 +00003035 if (!AT.isValid())
3036 return true;
Jordan Roseec087352012-09-05 22:56:26 +00003037
Jordan Rose448ac3e2012-12-05 18:44:40 +00003038 QualType ExprTy = E->getType();
Ted Kremenek02be9682013-04-10 06:26:26 +00003039 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3040 ExprTy = TET->getUnderlyingExpr()->getType();
3041 }
3042
Jordan Rose448ac3e2012-12-05 18:44:40 +00003043 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00003044 return true;
Jordan Roseee0259d2012-06-04 22:48:57 +00003045
Jordan Rose614a8652012-09-05 22:56:19 +00003046 // Look through argument promotions for our error message's reported type.
3047 // This includes the integral and floating promotions, but excludes array
3048 // and function pointer decay; seeing that an argument intended to be a
3049 // string has type 'char [6]' is probably more confusing than 'char *'.
3050 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3051 if (ICE->getCastKind() == CK_IntegralCast ||
3052 ICE->getCastKind() == CK_FloatingCast) {
3053 E = ICE->getSubExpr();
Jordan Rose448ac3e2012-12-05 18:44:40 +00003054 ExprTy = E->getType();
Jordan Rose614a8652012-09-05 22:56:19 +00003055
3056 // Check if we didn't match because of an implicit cast from a 'char'
3057 // or 'short' to an 'int'. This is done because printf is a varargs
3058 // function.
3059 if (ICE->getType() == S.Context.IntTy ||
3060 ICE->getType() == S.Context.UnsignedIntTy) {
3061 // All further checking is done on the subexpression.
Jordan Rose448ac3e2012-12-05 18:44:40 +00003062 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00003063 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00003064 }
Jordan Roseee0259d2012-06-04 22:48:57 +00003065 }
Jordan Rose448ac3e2012-12-05 18:44:40 +00003066 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3067 // Special case for 'a', which has type 'int' in C.
3068 // Note, however, that we do /not/ want to treat multibyte constants like
3069 // 'MooV' as characters! This form is deprecated but still exists.
3070 if (ExprTy == S.Context.IntTy)
3071 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3072 ExprTy = S.Context.CharTy;
Jordan Rose614a8652012-09-05 22:56:19 +00003073 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003074
Jordan Rose2cd34402012-12-05 18:44:49 +00003075 // %C in an Objective-C context prints a unichar, not a wchar_t.
3076 // If the argument is an integer of some kind, believe the %C and suggest
3077 // a cast instead of changing the conversion specifier.
Jordan Rose448ac3e2012-12-05 18:44:40 +00003078 QualType IntendedTy = ExprTy;
Jordan Rose2cd34402012-12-05 18:44:49 +00003079 if (ObjCContext &&
3080 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3081 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3082 !ExprTy->isCharType()) {
3083 // 'unichar' is defined as a typedef of unsigned short, but we should
3084 // prefer using the typedef if it is visible.
3085 IntendedTy = S.Context.UnsignedShortTy;
3086
3087 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3088 Sema::LookupOrdinaryName);
3089 if (S.LookupName(Result, S.getCurScope())) {
3090 NamedDecl *ND = Result.getFoundDecl();
3091 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3092 if (TD->getUnderlyingType() == IntendedTy)
3093 IntendedTy = S.Context.getTypedefType(TD);
3094 }
3095 }
3096 }
3097
3098 // Special-case some of Darwin's platform-independence types by suggesting
3099 // casts to primitive types that are known to be large enough.
3100 bool ShouldNotPrintDirectly = false;
Jordan Roseec087352012-09-05 22:56:26 +00003101 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Ted Kremenek6edb0292013-03-25 22:28:37 +00003102 // Use a 'while' to peel off layers of typedefs.
3103 QualType TyTy = IntendedTy;
3104 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
Jordan Roseec087352012-09-05 22:56:26 +00003105 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose2cd34402012-12-05 18:44:49 +00003106 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseec087352012-09-05 22:56:26 +00003107 .Case("NSInteger", S.Context.LongTy)
3108 .Case("NSUInteger", S.Context.UnsignedLongTy)
3109 .Case("SInt32", S.Context.IntTy)
3110 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose2cd34402012-12-05 18:44:49 +00003111 .Default(QualType());
3112
3113 if (!CastTy.isNull()) {
3114 ShouldNotPrintDirectly = true;
3115 IntendedTy = CastTy;
Ted Kremenek6edb0292013-03-25 22:28:37 +00003116 break;
Jordan Rose2cd34402012-12-05 18:44:49 +00003117 }
Ted Kremenek6edb0292013-03-25 22:28:37 +00003118 TyTy = UserTy->desugar();
Jordan Roseec087352012-09-05 22:56:26 +00003119 }
3120 }
3121
Jordan Rose614a8652012-09-05 22:56:19 +00003122 // We may be able to offer a FixItHint if it is a supported type.
3123 PrintfSpecifier fixedFS = FS;
Jordan Roseec087352012-09-05 22:56:26 +00003124 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose614a8652012-09-05 22:56:19 +00003125 S.Context, ObjCContext);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003126
Jordan Rose614a8652012-09-05 22:56:19 +00003127 if (success) {
3128 // Get the fix string from the fixed format specifier
3129 SmallString<16> buf;
3130 llvm::raw_svector_ostream os(buf);
3131 fixedFS.toString(os);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003132
Jordan Roseec087352012-09-05 22:56:26 +00003133 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3134
Jordan Rose2cd34402012-12-05 18:44:49 +00003135 if (IntendedTy == ExprTy) {
3136 // In this case, the specifier is wrong and should be changed to match
3137 // the argument.
3138 EmitFormatDiagnostic(
3139 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3140 << AT.getRepresentativeTypeName(S.Context) << IntendedTy
3141 << E->getSourceRange(),
3142 E->getLocStart(),
3143 /*IsStringLocation*/false,
3144 SpecRange,
3145 FixItHint::CreateReplacement(SpecRange, os.str()));
3146
3147 } else {
Jordan Roseec087352012-09-05 22:56:26 +00003148 // The canonical type for formatting this value is different from the
3149 // actual type of the expression. (This occurs, for example, with Darwin's
3150 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3151 // should be printed as 'long' for 64-bit compatibility.)
3152 // Rather than emitting a normal format/argument mismatch, we want to
3153 // add a cast to the recommended type (and correct the format string
3154 // if necessary).
3155 SmallString<16> CastBuf;
3156 llvm::raw_svector_ostream CastFix(CastBuf);
3157 CastFix << "(";
3158 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3159 CastFix << ")";
3160
3161 SmallVector<FixItHint,4> Hints;
3162 if (!AT.matchesType(S.Context, IntendedTy))
3163 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3164
3165 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3166 // If there's already a cast present, just replace it.
3167 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3168 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3169
3170 } else if (!requiresParensToAddCast(E)) {
3171 // If the expression has high enough precedence,
3172 // just write the C-style cast.
3173 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3174 CastFix.str()));
3175 } else {
3176 // Otherwise, add parens around the expression as well as the cast.
3177 CastFix << "(";
3178 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3179 CastFix.str()));
3180
3181 SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
3182 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3183 }
3184
Jordan Rose2cd34402012-12-05 18:44:49 +00003185 if (ShouldNotPrintDirectly) {
3186 // The expression has a type that should not be printed directly.
3187 // We extract the name from the typedef because we don't want to show
3188 // the underlying type in the diagnostic.
3189 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseec087352012-09-05 22:56:26 +00003190
Jordan Rose2cd34402012-12-05 18:44:49 +00003191 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
3192 << Name << IntendedTy
3193 << E->getSourceRange(),
3194 E->getLocStart(), /*IsStringLocation=*/false,
3195 SpecRange, Hints);
3196 } else {
3197 // In this case, the expression could be printed using a different
3198 // specifier, but we've decided that the specifier is probably correct
3199 // and we should cast instead. Just use the normal warning message.
3200 EmitFormatDiagnostic(
3201 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3202 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3203 << E->getSourceRange(),
3204 E->getLocStart(), /*IsStringLocation*/false,
3205 SpecRange, Hints);
3206 }
Jordan Roseec087352012-09-05 22:56:26 +00003207 }
Jordan Rose614a8652012-09-05 22:56:19 +00003208 } else {
3209 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3210 SpecifierLen);
3211 // Since the warning for passing non-POD types to variadic functions
3212 // was deferred until now, we emit a warning for non-POD
3213 // arguments here.
Richard Smith0e218972013-08-05 18:49:43 +00003214 switch (S.isValidVarArgType(ExprTy)) {
3215 case Sema::VAK_Valid:
3216 case Sema::VAK_ValidInCXX11:
Jordan Rose614a8652012-09-05 22:56:19 +00003217 EmitFormatDiagnostic(
Richard Smith0e218972013-08-05 18:49:43 +00003218 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3219 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3220 << CSR
3221 << E->getSourceRange(),
3222 E->getLocStart(), /*IsStringLocation*/false, CSR);
3223 break;
3224
3225 case Sema::VAK_Undefined:
3226 EmitFormatDiagnostic(
3227 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith80ad52f2013-01-02 11:42:31 +00003228 << S.getLangOpts().CPlusPlus11
Jordan Rose448ac3e2012-12-05 18:44:40 +00003229 << ExprTy
Jordan Rose614a8652012-09-05 22:56:19 +00003230 << CallType
3231 << AT.getRepresentativeTypeName(S.Context)
3232 << CSR
3233 << E->getSourceRange(),
3234 E->getLocStart(), /*IsStringLocation*/false, CSR);
Jordan Rose614a8652012-09-05 22:56:19 +00003235 checkForCStrMembers(AT, E, CSR);
Richard Smith0e218972013-08-05 18:49:43 +00003236 break;
3237
3238 case Sema::VAK_Invalid:
3239 if (ExprTy->isObjCObjectType())
3240 EmitFormatDiagnostic(
3241 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3242 << S.getLangOpts().CPlusPlus11
3243 << ExprTy
3244 << CallType
3245 << AT.getRepresentativeTypeName(S.Context)
3246 << CSR
3247 << E->getSourceRange(),
3248 E->getLocStart(), /*IsStringLocation*/false, CSR);
3249 else
3250 // FIXME: If this is an initializer list, suggest removing the braces
3251 // or inserting a cast to the target type.
3252 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3253 << isa<InitListExpr>(E) << ExprTy << CallType
3254 << AT.getRepresentativeTypeName(S.Context)
3255 << E->getSourceRange();
3256 break;
3257 }
3258
3259 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3260 "format string specifier index out of range");
3261 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003262 }
3263
Ted Kremeneke0e53132010-01-28 23:39:18 +00003264 return true;
3265}
3266
Ted Kremenek826a3452010-07-16 02:11:22 +00003267//===--- CHECK: Scanf format string checking ------------------------------===//
3268
3269namespace {
3270class CheckScanfHandler : public CheckFormatHandler {
3271public:
3272 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3273 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003274 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003275 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003276 unsigned formatIdx, bool inFunctionCall,
Richard Smith0e218972013-08-05 18:49:43 +00003277 Sema::VariadicCallType CallType,
3278 llvm::SmallBitVector &CheckedVarArgs)
3279 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3280 numDataArgs, beg, hasVAListArg,
3281 Args, formatIdx, inFunctionCall, CallType,
3282 CheckedVarArgs)
Jordan Roseddcfbc92012-07-19 18:10:23 +00003283 {}
Ted Kremenek826a3452010-07-16 02:11:22 +00003284
3285 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3286 const char *startSpecifier,
3287 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003288
3289 bool HandleInvalidScanfConversionSpecifier(
3290 const analyze_scanf::ScanfSpecifier &FS,
3291 const char *startSpecifier,
3292 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00003293
3294 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00003295};
Ted Kremenek07d161f2010-01-29 01:50:07 +00003296}
Ted Kremeneke0e53132010-01-28 23:39:18 +00003297
Ted Kremenekb7c21012010-07-16 18:28:03 +00003298void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3299 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00003300 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3301 getLocationOfByte(end), /*IsStringLocation*/true,
3302 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00003303}
3304
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003305bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3306 const analyze_scanf::ScanfSpecifier &FS,
3307 const char *startSpecifier,
3308 unsigned specifierLen) {
3309
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003310 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003311 FS.getConversionSpecifier();
3312
3313 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3314 getLocationOfByte(CS.getStart()),
3315 startSpecifier, specifierLen,
3316 CS.getStart(), CS.getLength());
3317}
3318
Ted Kremenek826a3452010-07-16 02:11:22 +00003319bool CheckScanfHandler::HandleScanfSpecifier(
3320 const analyze_scanf::ScanfSpecifier &FS,
3321 const char *startSpecifier,
3322 unsigned specifierLen) {
3323
3324 using namespace analyze_scanf;
3325 using namespace analyze_format_string;
3326
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003327 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00003328
Ted Kremenekbaa40062010-07-19 22:01:06 +00003329 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3330 // be used to decide if we are using positional arguments consistently.
3331 if (FS.consumesDataArgument()) {
3332 if (atFirstArg) {
3333 atFirstArg = false;
3334 usesPositionalArgs = FS.usesPositionalArg();
3335 }
3336 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003337 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3338 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00003339 return false;
3340 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003341 }
3342
3343 // Check if the field with is non-zero.
3344 const OptionalAmount &Amt = FS.getFieldWidth();
3345 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3346 if (Amt.getConstantAmount() == 0) {
3347 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3348 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00003349 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3350 getLocationOfByte(Amt.getStart()),
3351 /*IsStringLocation*/true, R,
3352 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00003353 }
3354 }
3355
3356 if (!FS.consumesDataArgument()) {
3357 // FIXME: Technically specifying a precision or field width here
3358 // makes no sense. Worth issuing a warning at some point.
3359 return true;
3360 }
3361
3362 // Consume the argument.
3363 unsigned argIndex = FS.getArgIndex();
3364 if (argIndex < NumDataArgs) {
3365 // The check to see if the argIndex is valid will come later.
3366 // We set the bit here because we may exit early from this
3367 // function if we encounter some other error.
3368 CoveredArgs.set(argIndex);
3369 }
3370
Ted Kremenek1e51c202010-07-20 20:04:47 +00003371 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003372 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00003373 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3374 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003375 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00003376 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003377 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00003378 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3379 diag::warn_format_non_standard_conversion_spec);
Hans Wennborg76517422012-02-22 10:17:01 +00003380
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003381 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3382 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3383
Ted Kremenek826a3452010-07-16 02:11:22 +00003384 // The remaining checks depend on the data arguments.
3385 if (HasVAListArg)
3386 return true;
3387
Ted Kremenek666a1972010-07-26 19:45:42 +00003388 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00003389 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00003390
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003391 // Check that the argument type matches the format specifier.
3392 const Expr *Ex = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00003393 if (!Ex)
3394 return true;
3395
Hans Wennborg58e1e542012-08-07 08:59:46 +00003396 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3397 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003398 ScanfSpecifier fixedFS = FS;
David Blaikie4e4d0842012-03-11 07:00:24 +00003399 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgbe6126a2012-02-15 09:59:46 +00003400 S.Context);
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003401
3402 if (success) {
3403 // Get the fix string from the fixed format specifier.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003404 SmallString<128> buf;
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003405 llvm::raw_svector_ostream os(buf);
3406 fixedFS.toString(os);
3407
3408 EmitFormatDiagnostic(
3409 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003410 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003411 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003412 Ex->getLocStart(),
3413 /*IsStringLocation*/false,
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003414 getSpecifierRange(startSpecifier, specifierLen),
3415 FixItHint::CreateReplacement(
3416 getSpecifierRange(startSpecifier, specifierLen),
3417 os.str()));
3418 } else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003419 EmitFormatDiagnostic(
3420 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003421 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003422 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003423 Ex->getLocStart(),
3424 /*IsStringLocation*/false,
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003425 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003426 }
3427 }
3428
Ted Kremenek826a3452010-07-16 02:11:22 +00003429 return true;
3430}
3431
3432void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00003433 const Expr *OrigFormatExpr,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003434 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003435 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003436 unsigned firstDataArg, FormatStringType Type,
Richard Smith0e218972013-08-05 18:49:43 +00003437 bool inFunctionCall, VariadicCallType CallType,
3438 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003439
Ted Kremeneke0e53132010-01-28 23:39:18 +00003440 // CHECK: is the format string a wide literal?
Richard Smithdf9ef1b2012-06-13 05:37:23 +00003441 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003442 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003443 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003444 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3445 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003446 return;
3447 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003448
Ted Kremeneke0e53132010-01-28 23:39:18 +00003449 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00003450 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00003451 const char *Str = StrRef.data();
3452 unsigned StrLen = StrRef.size();
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003453 const unsigned numDataArgs = Args.size() - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00003454
Ted Kremeneke0e53132010-01-28 23:39:18 +00003455 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00003456 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00003457 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003458 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003459 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3460 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003461 return;
3462 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003463
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003464 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003465 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003466 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003467 Str, HasVAListArg, Args, format_idx,
Richard Smith0e218972013-08-05 18:49:43 +00003468 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek826a3452010-07-16 02:11:22 +00003469
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003470 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003471 getLangOpts(),
3472 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003473 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003474 } else if (Type == FST_Scanf) {
Jordan Rose50687312012-06-04 23:52:23 +00003475 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003476 Str, HasVAListArg, Args, format_idx,
Richard Smith0e218972013-08-05 18:49:43 +00003477 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek826a3452010-07-16 02:11:22 +00003478
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003479 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003480 getLangOpts(),
3481 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003482 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003483 } // TODO: handle other formats
Ted Kremenekce7024e2010-01-28 01:18:22 +00003484}
3485
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003486//===--- CHECK: Standard memory functions ---------------------------------===//
3487
Douglas Gregor2a053a32011-05-03 20:05:22 +00003488/// \brief Determine whether the given type is a dynamic class type (e.g.,
3489/// whether it has a vtable).
3490static bool isDynamicClassType(QualType T) {
3491 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3492 if (CXXRecordDecl *Definition = Record->getDefinition())
3493 if (Definition->isDynamicClass())
3494 return true;
3495
3496 return false;
3497}
3498
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003499/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00003500/// otherwise returns NULL.
3501static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00003502 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00003503 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3504 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
3505 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003506
Chandler Carruth000d4282011-06-16 09:09:40 +00003507 return 0;
3508}
3509
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003510/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00003511static QualType getSizeOfArgType(const Expr* E) {
3512 if (const UnaryExprOrTypeTraitExpr *SizeOf =
3513 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3514 if (SizeOf->getKind() == clang::UETT_SizeOf)
3515 return SizeOf->getTypeOfArgument();
3516
3517 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00003518}
3519
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003520/// \brief Check for dangerous or invalid arguments to memset().
3521///
Chandler Carruth929f0132011-06-03 06:23:57 +00003522/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003523/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3524/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003525///
3526/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003527void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00003528 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003529 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00003530 assert(BId != 0);
3531
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003532 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00003533 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00003534 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00003535 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003536 return;
3537
Anna Zaks0a151a12012-01-17 00:37:07 +00003538 unsigned LastArg = (BId == Builtin::BImemset ||
3539 BId == Builtin::BIstrndup ? 1 : 2);
3540 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00003541 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00003542
3543 // We have special checking when the length is a sizeof expression.
3544 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
3545 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
3546 llvm::FoldingSetNodeID SizeOfArgID;
3547
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003548 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
3549 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003550 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003551
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003552 QualType DestTy = Dest->getType();
3553 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
3554 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00003555
Chandler Carruth000d4282011-06-16 09:09:40 +00003556 // Never warn about void type pointers. This can be used to suppress
3557 // false positives.
3558 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003559 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003560
Chandler Carruth000d4282011-06-16 09:09:40 +00003561 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
3562 // actually comparing the expressions for equality. Because computing the
3563 // expression IDs can be expensive, we only do this if the diagnostic is
3564 // enabled.
3565 if (SizeOfArg &&
3566 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
3567 SizeOfArg->getExprLoc())) {
3568 // We only compute IDs for expressions if the warning is enabled, and
3569 // cache the sizeof arg's ID.
3570 if (SizeOfArgID == llvm::FoldingSetNodeID())
3571 SizeOfArg->Profile(SizeOfArgID, Context, true);
3572 llvm::FoldingSetNodeID DestID;
3573 Dest->Profile(DestID, Context, true);
3574 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00003575 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
3576 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00003577 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003578 StringRef ReadableName = FnName->getName();
3579
Chandler Carruth000d4282011-06-16 09:09:40 +00003580 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaks90c78322012-05-30 23:14:52 +00003581 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth000d4282011-06-16 09:09:40 +00003582 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian7adf4172013-01-30 01:12:44 +00003583 if (!PointeeTy->isIncompleteType() &&
3584 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth000d4282011-06-16 09:09:40 +00003585 ActionIdx = 2; // If the pointee's size is sizeof(char),
3586 // suggest an explicit length.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003587
3588 // If the function is defined as a builtin macro, do not show macro
3589 // expansion.
3590 SourceLocation SL = SizeOfArg->getExprLoc();
3591 SourceRange DSR = Dest->getSourceRange();
3592 SourceRange SSR = SizeOfArg->getSourceRange();
3593 SourceManager &SM = PP.getSourceManager();
3594
3595 if (SM.isMacroArgExpansion(SL)) {
3596 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
3597 SL = SM.getSpellingLoc(SL);
3598 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
3599 SM.getSpellingLoc(DSR.getEnd()));
3600 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
3601 SM.getSpellingLoc(SSR.getEnd()));
3602 }
3603
Anna Zaks90c78322012-05-30 23:14:52 +00003604 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth000d4282011-06-16 09:09:40 +00003605 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks6fcb3722012-05-30 00:34:21 +00003606 << ReadableName
Anna Zaks90c78322012-05-30 23:14:52 +00003607 << PointeeTy
3608 << DestTy
Anna Zaks6fcb3722012-05-30 00:34:21 +00003609 << DSR
Anna Zaks90c78322012-05-30 23:14:52 +00003610 << SSR);
3611 DiagRuntimeBehavior(SL, SizeOfArg,
3612 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
3613 << ActionIdx
3614 << SSR);
3615
Chandler Carruth000d4282011-06-16 09:09:40 +00003616 break;
3617 }
3618 }
3619
3620 // Also check for cases where the sizeof argument is the exact same
3621 // type as the memory argument, and where it points to a user-defined
3622 // record type.
3623 if (SizeOfArgTy != QualType()) {
3624 if (PointeeTy->isRecordType() &&
3625 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
3626 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
3627 PDiag(diag::warn_sizeof_pointer_type_memaccess)
3628 << FnName << SizeOfArgTy << ArgIdx
3629 << PointeeTy << Dest->getSourceRange()
3630 << LenExpr->getSourceRange());
3631 break;
3632 }
Nico Webere4a1c642011-06-14 16:14:58 +00003633 }
3634
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003635 // Always complain about dynamic classes.
Anna Zaks0a151a12012-01-17 00:37:07 +00003636 if (isDynamicClassType(PointeeTy)) {
3637
3638 unsigned OperationType = 0;
3639 // "overwritten" if we're warning about the destination for any call
3640 // but memcmp; otherwise a verb appropriate to the call.
3641 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
3642 if (BId == Builtin::BImemcpy)
3643 OperationType = 1;
3644 else if(BId == Builtin::BImemmove)
3645 OperationType = 2;
3646 else if (BId == Builtin::BImemcmp)
3647 OperationType = 3;
3648 }
3649
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003650 DiagRuntimeBehavior(
3651 Dest->getExprLoc(), Dest,
3652 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks0a151a12012-01-17 00:37:07 +00003653 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaksd9b859a2012-01-13 21:52:01 +00003654 << FnName << PointeeTy
Anna Zaks0a151a12012-01-17 00:37:07 +00003655 << OperationType
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003656 << Call->getCallee()->getSourceRange());
Anna Zaks0a151a12012-01-17 00:37:07 +00003657 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
3658 BId != Builtin::BImemset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003659 DiagRuntimeBehavior(
3660 Dest->getExprLoc(), Dest,
3661 PDiag(diag::warn_arc_object_memaccess)
3662 << ArgIdx << FnName << PointeeTy
3663 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00003664 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003665 continue;
John McCallf85e1932011-06-15 23:02:42 +00003666
3667 DiagRuntimeBehavior(
3668 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00003669 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003670 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
3671 break;
3672 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003673 }
3674}
3675
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003676// A little helper routine: ignore addition and subtraction of integer literals.
3677// This intentionally does not ignore all integer constant expressions because
3678// we don't want to remove sizeof().
3679static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
3680 Ex = Ex->IgnoreParenCasts();
3681
3682 for (;;) {
3683 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
3684 if (!BO || !BO->isAdditiveOp())
3685 break;
3686
3687 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
3688 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
3689
3690 if (isa<IntegerLiteral>(RHS))
3691 Ex = LHS;
3692 else if (isa<IntegerLiteral>(LHS))
3693 Ex = RHS;
3694 else
3695 break;
3696 }
3697
3698 return Ex;
3699}
3700
Anna Zaks0f38ace2012-08-08 21:42:23 +00003701static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
3702 ASTContext &Context) {
3703 // Only handle constant-sized or VLAs, but not flexible members.
3704 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
3705 // Only issue the FIXIT for arrays of size > 1.
3706 if (CAT->getSize().getSExtValue() <= 1)
3707 return false;
3708 } else if (!Ty->isVariableArrayType()) {
3709 return false;
3710 }
3711 return true;
3712}
3713
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003714// Warn if the user has made the 'size' argument to strlcpy or strlcat
3715// be the size of the source, instead of the destination.
3716void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
3717 IdentifierInfo *FnName) {
3718
3719 // Don't crash if the user has the wrong number of arguments
3720 if (Call->getNumArgs() != 3)
3721 return;
3722
3723 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
3724 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
3725 const Expr *CompareWithSrc = NULL;
3726
3727 // Look for 'strlcpy(dst, x, sizeof(x))'
3728 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
3729 CompareWithSrc = Ex;
3730 else {
3731 // Look for 'strlcpy(dst, x, strlen(x))'
3732 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smith180f4792011-11-10 06:34:14 +00003733 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003734 && SizeCall->getNumArgs() == 1)
3735 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
3736 }
3737 }
3738
3739 if (!CompareWithSrc)
3740 return;
3741
3742 // Determine if the argument to sizeof/strlen is equal to the source
3743 // argument. In principle there's all kinds of things you could do
3744 // here, for instance creating an == expression and evaluating it with
3745 // EvaluateAsBooleanCondition, but this uses a more direct technique:
3746 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
3747 if (!SrcArgDRE)
3748 return;
3749
3750 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
3751 if (!CompareWithSrcDRE ||
3752 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
3753 return;
3754
3755 const Expr *OriginalSizeArg = Call->getArg(2);
3756 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
3757 << OriginalSizeArg->getSourceRange() << FnName;
3758
3759 // Output a FIXIT hint if the destination is an array (rather than a
3760 // pointer to an array). This could be enhanced to handle some
3761 // pointers if we know the actual size, like if DstArg is 'array+2'
3762 // we could say 'sizeof(array)-2'.
3763 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks0f38ace2012-08-08 21:42:23 +00003764 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek8f746222011-08-18 22:48:41 +00003765 return;
Ted Kremenek8f746222011-08-18 22:48:41 +00003766
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003767 SmallString<128> sizeString;
Ted Kremenek8f746222011-08-18 22:48:41 +00003768 llvm::raw_svector_ostream OS(sizeString);
3769 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003770 DstArg->printPretty(OS, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00003771 OS << ")";
3772
3773 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
3774 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
3775 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003776}
3777
Anna Zaksc36bedc2012-02-01 19:08:57 +00003778/// Check if two expressions refer to the same declaration.
3779static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
3780 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
3781 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
3782 return D1->getDecl() == D2->getDecl();
3783 return false;
3784}
3785
3786static const Expr *getStrlenExprArg(const Expr *E) {
3787 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
3788 const FunctionDecl *FD = CE->getDirectCallee();
3789 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
3790 return 0;
3791 return CE->getArg(0)->IgnoreParenCasts();
3792 }
3793 return 0;
3794}
3795
3796// Warn on anti-patterns as the 'size' argument to strncat.
3797// The correct size argument should look like following:
3798// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3799void Sema::CheckStrncatArguments(const CallExpr *CE,
3800 IdentifierInfo *FnName) {
3801 // Don't crash if the user has the wrong number of arguments.
3802 if (CE->getNumArgs() < 3)
3803 return;
3804 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
3805 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
3806 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
3807
3808 // Identify common expressions, which are wrongly used as the size argument
3809 // to strncat and may lead to buffer overflows.
3810 unsigned PatternType = 0;
3811 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
3812 // - sizeof(dst)
3813 if (referToTheSameDecl(SizeOfArg, DstArg))
3814 PatternType = 1;
3815 // - sizeof(src)
3816 else if (referToTheSameDecl(SizeOfArg, SrcArg))
3817 PatternType = 2;
3818 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
3819 if (BE->getOpcode() == BO_Sub) {
3820 const Expr *L = BE->getLHS()->IgnoreParenCasts();
3821 const Expr *R = BE->getRHS()->IgnoreParenCasts();
3822 // - sizeof(dst) - strlen(dst)
3823 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
3824 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
3825 PatternType = 1;
3826 // - sizeof(src) - (anything)
3827 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
3828 PatternType = 2;
3829 }
3830 }
3831
3832 if (PatternType == 0)
3833 return;
3834
Anna Zaksafdb0412012-02-03 01:27:37 +00003835 // Generate the diagnostic.
3836 SourceLocation SL = LenArg->getLocStart();
3837 SourceRange SR = LenArg->getSourceRange();
3838 SourceManager &SM = PP.getSourceManager();
3839
3840 // If the function is defined as a builtin macro, do not show macro expansion.
3841 if (SM.isMacroArgExpansion(SL)) {
3842 SL = SM.getSpellingLoc(SL);
3843 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
3844 SM.getSpellingLoc(SR.getEnd()));
3845 }
3846
Anna Zaks0f38ace2012-08-08 21:42:23 +00003847 // Check if the destination is an array (rather than a pointer to an array).
3848 QualType DstTy = DstArg->getType();
3849 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
3850 Context);
3851 if (!isKnownSizeArray) {
3852 if (PatternType == 1)
3853 Diag(SL, diag::warn_strncat_wrong_size) << SR;
3854 else
3855 Diag(SL, diag::warn_strncat_src_size) << SR;
3856 return;
3857 }
3858
Anna Zaksc36bedc2012-02-01 19:08:57 +00003859 if (PatternType == 1)
Anna Zaksafdb0412012-02-03 01:27:37 +00003860 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003861 else
Anna Zaksafdb0412012-02-03 01:27:37 +00003862 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003863
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003864 SmallString<128> sizeString;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003865 llvm::raw_svector_ostream OS(sizeString);
3866 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003867 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003868 OS << ") - ";
3869 OS << "strlen(";
Richard Smithd1420c62012-08-16 03:56:14 +00003870 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003871 OS << ") - 1";
3872
Anna Zaksafdb0412012-02-03 01:27:37 +00003873 Diag(SL, diag::note_strncat_wrong_size)
3874 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003875}
3876
Ted Kremenek06de2762007-08-17 16:46:58 +00003877//===--- CHECK: Return Address of Stack Variable --------------------------===//
3878
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003879static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3880 Decl *ParentDecl);
3881static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
3882 Decl *ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003883
3884/// CheckReturnStackAddr - Check if a return statement returns the address
3885/// of a stack variable.
3886void
3887Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
3888 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00003889
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003890 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003891 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003892
3893 // Perform checking for returned stack addresses, local blocks,
3894 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00003895 if (lhsType->isPointerType() ||
David Blaikie4e4d0842012-03-11 07:00:24 +00003896 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003897 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003898 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003899 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003900 }
3901
3902 if (stackE == 0)
3903 return; // Nothing suspicious was found.
3904
3905 SourceLocation diagLoc;
3906 SourceRange diagRange;
3907 if (refVars.empty()) {
3908 diagLoc = stackE->getLocStart();
3909 diagRange = stackE->getSourceRange();
3910 } else {
3911 // We followed through a reference variable. 'stackE' contains the
3912 // problematic expression but we will warn at the return statement pointing
3913 // at the reference variable. We will later display the "trail" of
3914 // reference variables using notes.
3915 diagLoc = refVars[0]->getLocStart();
3916 diagRange = refVars[0]->getSourceRange();
3917 }
3918
3919 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
3920 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
3921 : diag::warn_ret_stack_addr)
3922 << DR->getDecl()->getDeclName() << diagRange;
3923 } else if (isa<BlockExpr>(stackE)) { // local block.
3924 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
3925 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
3926 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
3927 } else { // local temporary.
3928 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
3929 : diag::warn_ret_local_temp_addr)
3930 << diagRange;
3931 }
3932
3933 // Display the "trail" of reference variables that we followed until we
3934 // found the problematic expression using notes.
3935 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
3936 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
3937 // If this var binds to another reference var, show the range of the next
3938 // var, otherwise the var binds to the problematic expression, in which case
3939 // show the range of the expression.
3940 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
3941 : stackE->getSourceRange();
3942 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
3943 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00003944 }
3945}
3946
3947/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
3948/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003949/// to a location on the stack, a local block, an address of a label, or a
3950/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00003951/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003952/// encounter a subexpression that (1) clearly does not lead to one of the
3953/// above problematic expressions (2) is something we cannot determine leads to
3954/// a problematic expression based on such local checking.
3955///
3956/// Both EvalAddr and EvalVal follow through reference variables to evaluate
3957/// the expression that they point to. Such variables are added to the
3958/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00003959///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003960/// EvalAddr processes expressions that are pointers that are used as
3961/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003962/// At the base case of the recursion is a check for the above problematic
3963/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00003964///
3965/// This implementation handles:
3966///
3967/// * pointer-to-pointer casts
3968/// * implicit conversions from array references to pointers
3969/// * taking the address of fields
3970/// * arbitrary interplay between "&" and "*" operators
3971/// * pointer arithmetic from an address of a stack variable
3972/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003973static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3974 Decl *ParentDecl) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003975 if (E->isTypeDependent())
Craig Topperb61c2942013-08-02 05:10:31 +00003976 return NULL;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003977
Ted Kremenek06de2762007-08-17 16:46:58 +00003978 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00003979 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00003980 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003981 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003982 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00003983
Peter Collingbournef111d932011-04-15 00:35:48 +00003984 E = E->IgnoreParens();
3985
Ted Kremenek06de2762007-08-17 16:46:58 +00003986 // Our "symbolic interpreter" is just a dispatch off the currently
3987 // viewed AST node. We then recursively traverse the AST by calling
3988 // EvalAddr and EvalVal appropriately.
3989 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003990 case Stmt::DeclRefExprClass: {
3991 DeclRefExpr *DR = cast<DeclRefExpr>(E);
3992
3993 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
3994 // If this is a reference variable, follow through to the expression that
3995 // it points to.
3996 if (V->hasLocalStorage() &&
3997 V->getType()->isReferenceType() && V->hasInit()) {
3998 // Add the reference variable to the "trail".
3999 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004000 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004001 }
4002
4003 return NULL;
4004 }
Ted Kremenek06de2762007-08-17 16:46:58 +00004005
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004006 case Stmt::UnaryOperatorClass: {
4007 // The only unary operator that make sense to handle here
4008 // is AddrOf. All others don't make sense as pointers.
4009 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004010
John McCall2de56d12010-08-25 11:45:40 +00004011 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004012 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004013 else
Ted Kremenek06de2762007-08-17 16:46:58 +00004014 return NULL;
4015 }
Mike Stump1eb44332009-09-09 15:08:12 +00004016
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004017 case Stmt::BinaryOperatorClass: {
4018 // Handle pointer arithmetic. All other binary operators are not valid
4019 // in this context.
4020 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00004021 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00004022
John McCall2de56d12010-08-25 11:45:40 +00004023 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004024 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00004025
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004026 Expr *Base = B->getLHS();
4027
4028 // Determine which argument is the real pointer base. It could be
4029 // the RHS argument instead of the LHS.
4030 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00004031
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004032 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004033 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004034 }
Steve Naroff61f40a22008-09-10 19:17:48 +00004035
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004036 // For conditional operators we need to see if either the LHS or RHS are
4037 // valid DeclRefExpr*s. If one of them is valid, we return it.
4038 case Stmt::ConditionalOperatorClass: {
4039 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004040
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004041 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00004042 if (Expr *lhsExpr = C->getLHS()) {
4043 // In C++, we can have a throw-expression, which has 'void' type.
4044 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004045 if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00004046 return LHS;
4047 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004048
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00004049 // In C++, we can have a throw-expression, which has 'void' type.
4050 if (C->getRHS()->getType()->isVoidType())
4051 return NULL;
4052
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004053 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004054 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004055
4056 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00004057 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004058 return E; // local block.
4059 return NULL;
4060
4061 case Stmt::AddrLabelExprClass:
4062 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00004063
John McCall80ee6e82011-11-10 05:35:25 +00004064 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004065 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4066 ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00004067
Ted Kremenek54b52742008-08-07 00:49:01 +00004068 // For casts, we need to handle conversions from arrays to
4069 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00004070 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00004071 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00004072 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8b9414e2012-02-23 23:04:32 +00004073 case Stmt::ObjCBridgedCastExprClass:
Mike Stump1eb44332009-09-09 15:08:12 +00004074 case Stmt::CXXStaticCastExprClass:
4075 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00004076 case Stmt::CXXConstCastExprClass:
4077 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8b9414e2012-02-23 23:04:32 +00004078 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4079 switch (cast<CastExpr>(E)->getCastKind()) {
4080 case CK_BitCast:
4081 case CK_LValueToRValue:
4082 case CK_NoOp:
4083 case CK_BaseToDerived:
4084 case CK_DerivedToBase:
4085 case CK_UncheckedDerivedToBase:
4086 case CK_Dynamic:
4087 case CK_CPointerToObjCPointerCast:
4088 case CK_BlockPointerToObjCPointerCast:
4089 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004090 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00004091
4092 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004093 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00004094
4095 default:
4096 return 0;
4097 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004098 }
Mike Stump1eb44332009-09-09 15:08:12 +00004099
Douglas Gregor03e80032011-06-21 17:03:29 +00004100 case Stmt::MaterializeTemporaryExprClass:
4101 if (Expr *Result = EvalAddr(
4102 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004103 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00004104 return Result;
4105
4106 return E;
4107
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004108 // Everything else: we simply don't reason about them.
4109 default:
4110 return NULL;
4111 }
Ted Kremenek06de2762007-08-17 16:46:58 +00004112}
Mike Stump1eb44332009-09-09 15:08:12 +00004113
Ted Kremenek06de2762007-08-17 16:46:58 +00004114
4115/// EvalVal - This function is complements EvalAddr in the mutual recursion.
4116/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004117static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4118 Decl *ParentDecl) {
Ted Kremenek68957a92010-08-04 20:01:07 +00004119do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00004120 // We should only be called for evaluating non-pointer expressions, or
4121 // expressions with a pointer type that are not used as references but instead
4122 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00004123
Ted Kremenek06de2762007-08-17 16:46:58 +00004124 // Our "symbolic interpreter" is just a dispatch off the currently
4125 // viewed AST node. We then recursively traverse the AST by calling
4126 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00004127
4128 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00004129 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00004130 case Stmt::ImplicitCastExprClass: {
4131 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00004132 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00004133 E = IE->getSubExpr();
4134 continue;
4135 }
4136 return NULL;
4137 }
4138
John McCall80ee6e82011-11-10 05:35:25 +00004139 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004140 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00004141
Douglas Gregora2813ce2009-10-23 18:54:35 +00004142 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004143 // When we hit a DeclRefExpr we are looking at code that refers to a
4144 // variable's name. If it's not a reference variable we check if it has
4145 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00004146 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004147
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004148 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
4149 // Check if it refers to itself, e.g. "int& i = i;".
4150 if (V == ParentDecl)
4151 return DR;
4152
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004153 if (V->hasLocalStorage()) {
4154 if (!V->getType()->isReferenceType())
4155 return DR;
4156
4157 // Reference variable, follow through to the expression that
4158 // it points to.
4159 if (V->hasInit()) {
4160 // Add the reference variable to the "trail".
4161 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004162 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004163 }
4164 }
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004165 }
Mike Stump1eb44332009-09-09 15:08:12 +00004166
Ted Kremenek06de2762007-08-17 16:46:58 +00004167 return NULL;
4168 }
Mike Stump1eb44332009-09-09 15:08:12 +00004169
Ted Kremenek06de2762007-08-17 16:46:58 +00004170 case Stmt::UnaryOperatorClass: {
4171 // The only unary operator that make sense to handle here
4172 // is Deref. All others don't resolve to a "name." This includes
4173 // handling all sorts of rvalues passed to a unary operator.
4174 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004175
John McCall2de56d12010-08-25 11:45:40 +00004176 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004177 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004178
4179 return NULL;
4180 }
Mike Stump1eb44332009-09-09 15:08:12 +00004181
Ted Kremenek06de2762007-08-17 16:46:58 +00004182 case Stmt::ArraySubscriptExprClass: {
4183 // Array subscripts are potential references to data on the stack. We
4184 // retrieve the DeclRefExpr* for the array variable if it indeed
4185 // has local storage.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004186 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004187 }
Mike Stump1eb44332009-09-09 15:08:12 +00004188
Ted Kremenek06de2762007-08-17 16:46:58 +00004189 case Stmt::ConditionalOperatorClass: {
4190 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004191 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00004192 ConditionalOperator *C = cast<ConditionalOperator>(E);
4193
Anders Carlsson39073232007-11-30 19:04:31 +00004194 // Handle the GNU extension for missing LHS.
4195 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004196 if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl))
Anders Carlsson39073232007-11-30 19:04:31 +00004197 return LHS;
4198
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004199 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004200 }
Mike Stump1eb44332009-09-09 15:08:12 +00004201
Ted Kremenek06de2762007-08-17 16:46:58 +00004202 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00004203 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00004204 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004205
Ted Kremenek06de2762007-08-17 16:46:58 +00004206 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00004207 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00004208 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00004209
4210 // Check whether the member type is itself a reference, in which case
4211 // we're not going to refer to the member, but to what the member refers to.
4212 if (M->getMemberDecl()->getType()->isReferenceType())
4213 return NULL;
4214
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004215 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004216 }
Mike Stump1eb44332009-09-09 15:08:12 +00004217
Douglas Gregor03e80032011-06-21 17:03:29 +00004218 case Stmt::MaterializeTemporaryExprClass:
4219 if (Expr *Result = EvalVal(
4220 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004221 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00004222 return Result;
4223
4224 return E;
4225
Ted Kremenek06de2762007-08-17 16:46:58 +00004226 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004227 // Check that we don't return or take the address of a reference to a
4228 // temporary. This is only useful in C++.
4229 if (!E->isTypeDependent() && E->isRValue())
4230 return E;
4231
4232 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00004233 return NULL;
4234 }
Ted Kremenek68957a92010-08-04 20:01:07 +00004235} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00004236}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004237
4238//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
4239
4240/// Check for comparisons of floating point operands using != and ==.
4241/// Issue a warning if these are no self-comparisons, as they are not likely
4242/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00004243void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieudd225092011-09-15 21:56:47 +00004244 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
4245 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004246
4247 // Special case: check for x == x (which is OK).
4248 // Do not emit warnings for such cases.
4249 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
4250 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
4251 if (DRL->getDecl() == DRR->getDecl())
David Blaikie980343b2012-07-16 20:47:22 +00004252 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004253
4254
Ted Kremenek1b500bb2007-11-29 00:59:04 +00004255 // Special case: check for comparisons against literals that can be exactly
4256 // represented by APFloat. In such cases, do not emit a warning. This
4257 // is a heuristic: often comparison against such literals are used to
4258 // detect if a value in a variable has not changed. This clearly can
4259 // lead to false negatives.
David Blaikie980343b2012-07-16 20:47:22 +00004260 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
4261 if (FLL->isExact())
4262 return;
4263 } else
4264 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
4265 if (FLR->isExact())
4266 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004267
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004268 // Check for comparisons with builtin types.
David Blaikie980343b2012-07-16 20:47:22 +00004269 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
4270 if (CL->isBuiltinCall())
4271 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004272
David Blaikie980343b2012-07-16 20:47:22 +00004273 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
4274 if (CR->isBuiltinCall())
4275 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004276
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004277 // Emit the diagnostic.
David Blaikie980343b2012-07-16 20:47:22 +00004278 Diag(Loc, diag::warn_floatingpoint_eq)
4279 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004280}
John McCallba26e582010-01-04 23:21:16 +00004281
John McCallf2370c92010-01-06 05:24:50 +00004282//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
4283//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00004284
John McCallf2370c92010-01-06 05:24:50 +00004285namespace {
John McCallba26e582010-01-04 23:21:16 +00004286
John McCallf2370c92010-01-06 05:24:50 +00004287/// Structure recording the 'active' range of an integer-valued
4288/// expression.
4289struct IntRange {
4290 /// The number of bits active in the int.
4291 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00004292
John McCallf2370c92010-01-06 05:24:50 +00004293 /// True if the int is known not to have negative values.
4294 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00004295
John McCallf2370c92010-01-06 05:24:50 +00004296 IntRange(unsigned Width, bool NonNegative)
4297 : Width(Width), NonNegative(NonNegative)
4298 {}
John McCallba26e582010-01-04 23:21:16 +00004299
John McCall1844a6e2010-11-10 23:38:19 +00004300 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00004301 static IntRange forBoolType() {
4302 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00004303 }
4304
John McCall1844a6e2010-11-10 23:38:19 +00004305 /// Returns the range of an opaque value of the given integral type.
4306 static IntRange forValueOfType(ASTContext &C, QualType T) {
4307 return forValueOfCanonicalType(C,
4308 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00004309 }
4310
John McCall1844a6e2010-11-10 23:38:19 +00004311 /// Returns the range of an opaque value of a canonical integral type.
4312 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00004313 assert(T->isCanonicalUnqualified());
4314
4315 if (const VectorType *VT = dyn_cast<VectorType>(T))
4316 T = VT->getElementType().getTypePtr();
4317 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4318 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00004319
David Majnemerf9eaf982013-06-07 22:07:20 +00004320 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00004321 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemerf9eaf982013-06-07 22:07:20 +00004322 EnumDecl *Enum = ET->getDecl();
4323 if (!Enum->isCompleteDefinition())
4324 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall091f23f2010-11-09 22:22:12 +00004325
David Majnemerf9eaf982013-06-07 22:07:20 +00004326 unsigned NumPositive = Enum->getNumPositiveBits();
4327 unsigned NumNegative = Enum->getNumNegativeBits();
John McCall323ed742010-05-06 08:58:33 +00004328
David Majnemerf9eaf982013-06-07 22:07:20 +00004329 if (NumNegative == 0)
4330 return IntRange(NumPositive, true/*NonNegative*/);
4331 else
4332 return IntRange(std::max(NumPositive + 1, NumNegative),
4333 false/*NonNegative*/);
John McCall323ed742010-05-06 08:58:33 +00004334 }
John McCallf2370c92010-01-06 05:24:50 +00004335
4336 const BuiltinType *BT = cast<BuiltinType>(T);
4337 assert(BT->isInteger());
4338
4339 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4340 }
4341
John McCall1844a6e2010-11-10 23:38:19 +00004342 /// Returns the "target" range of a canonical integral type, i.e.
4343 /// the range of values expressible in the type.
4344 ///
4345 /// This matches forValueOfCanonicalType except that enums have the
4346 /// full range of their type, not the range of their enumerators.
4347 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4348 assert(T->isCanonicalUnqualified());
4349
4350 if (const VectorType *VT = dyn_cast<VectorType>(T))
4351 T = VT->getElementType().getTypePtr();
4352 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4353 T = CT->getElementType().getTypePtr();
4354 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00004355 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00004356
4357 const BuiltinType *BT = cast<BuiltinType>(T);
4358 assert(BT->isInteger());
4359
4360 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4361 }
4362
4363 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00004364 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00004365 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00004366 L.NonNegative && R.NonNegative);
4367 }
4368
John McCall1844a6e2010-11-10 23:38:19 +00004369 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00004370 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00004371 return IntRange(std::min(L.Width, R.Width),
4372 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00004373 }
4374};
4375
Ted Kremenek0692a192012-01-31 05:37:37 +00004376static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4377 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004378 if (value.isSigned() && value.isNegative())
4379 return IntRange(value.getMinSignedBits(), false);
4380
4381 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00004382 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004383
4384 // isNonNegative() just checks the sign bit without considering
4385 // signedness.
4386 return IntRange(value.getActiveBits(), true);
4387}
4388
Ted Kremenek0692a192012-01-31 05:37:37 +00004389static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4390 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004391 if (result.isInt())
4392 return GetValueRange(C, result.getInt(), MaxWidth);
4393
4394 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00004395 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4396 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4397 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4398 R = IntRange::join(R, El);
4399 }
John McCallf2370c92010-01-06 05:24:50 +00004400 return R;
4401 }
4402
4403 if (result.isComplexInt()) {
4404 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4405 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4406 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00004407 }
4408
4409 // This can happen with lossless casts to intptr_t of "based" lvalues.
4410 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00004411 // FIXME: The only reason we need to pass the type in here is to get
4412 // the sign right on this one case. It would be nice if APValue
4413 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00004414 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004415 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00004416}
John McCallf2370c92010-01-06 05:24:50 +00004417
Eli Friedman09bddcf2013-07-08 20:20:06 +00004418static QualType GetExprType(Expr *E) {
4419 QualType Ty = E->getType();
4420 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
4421 Ty = AtomicRHS->getValueType();
4422 return Ty;
4423}
4424
John McCallf2370c92010-01-06 05:24:50 +00004425/// Pseudo-evaluate the given integer expression, estimating the
4426/// range of values it might take.
4427///
4428/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek0692a192012-01-31 05:37:37 +00004429static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004430 E = E->IgnoreParens();
4431
4432 // Try a full evaluation first.
4433 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004434 if (E->EvaluateAsRValue(result, C))
Eli Friedman09bddcf2013-07-08 20:20:06 +00004435 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004436
4437 // I think we only want to look through implicit casts here; if the
4438 // user has an explicit widening cast, we should treat the value as
4439 // being of the new, wider type.
4440 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00004441 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00004442 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4443
Eli Friedman09bddcf2013-07-08 20:20:06 +00004444 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCallf2370c92010-01-06 05:24:50 +00004445
John McCall2de56d12010-08-25 11:45:40 +00004446 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00004447
John McCallf2370c92010-01-06 05:24:50 +00004448 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00004449 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00004450 return OutputTypeRange;
4451
4452 IntRange SubRange
4453 = GetExprRange(C, CE->getSubExpr(),
4454 std::min(MaxWidth, OutputTypeRange.Width));
4455
4456 // Bail out if the subexpr's range is as wide as the cast type.
4457 if (SubRange.Width >= OutputTypeRange.Width)
4458 return OutputTypeRange;
4459
4460 // Otherwise, we take the smaller width, and we're non-negative if
4461 // either the output type or the subexpr is.
4462 return IntRange(SubRange.Width,
4463 SubRange.NonNegative || OutputTypeRange.NonNegative);
4464 }
4465
4466 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4467 // If we can fold the condition, just take that operand.
4468 bool CondResult;
4469 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
4470 return GetExprRange(C, CondResult ? CO->getTrueExpr()
4471 : CO->getFalseExpr(),
4472 MaxWidth);
4473
4474 // Otherwise, conservatively merge.
4475 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
4476 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
4477 return IntRange::join(L, R);
4478 }
4479
4480 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4481 switch (BO->getOpcode()) {
4482
4483 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00004484 case BO_LAnd:
4485 case BO_LOr:
4486 case BO_LT:
4487 case BO_GT:
4488 case BO_LE:
4489 case BO_GE:
4490 case BO_EQ:
4491 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00004492 return IntRange::forBoolType();
4493
John McCall862ff872011-07-13 06:35:24 +00004494 // The type of the assignments is the type of the LHS, so the RHS
4495 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00004496 case BO_MulAssign:
4497 case BO_DivAssign:
4498 case BO_RemAssign:
4499 case BO_AddAssign:
4500 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00004501 case BO_XorAssign:
4502 case BO_OrAssign:
4503 // TODO: bitfields?
Eli Friedman09bddcf2013-07-08 20:20:06 +00004504 return IntRange::forValueOfType(C, GetExprType(E));
John McCallc0cd21d2010-02-23 19:22:29 +00004505
John McCall862ff872011-07-13 06:35:24 +00004506 // Simple assignments just pass through the RHS, which will have
4507 // been coerced to the LHS type.
4508 case BO_Assign:
4509 // TODO: bitfields?
4510 return GetExprRange(C, BO->getRHS(), MaxWidth);
4511
John McCallf2370c92010-01-06 05:24:50 +00004512 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004513 case BO_PtrMemD:
4514 case BO_PtrMemI:
Eli Friedman09bddcf2013-07-08 20:20:06 +00004515 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004516
John McCall60fad452010-01-06 22:07:33 +00004517 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00004518 case BO_And:
4519 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00004520 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
4521 GetExprRange(C, BO->getRHS(), MaxWidth));
4522
John McCallf2370c92010-01-06 05:24:50 +00004523 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00004524 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00004525 // ...except that we want to treat '1 << (blah)' as logically
4526 // positive. It's an important idiom.
4527 if (IntegerLiteral *I
4528 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
4529 if (I->getValue() == 1) {
Eli Friedman09bddcf2013-07-08 20:20:06 +00004530 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall3aae6092010-04-07 01:14:35 +00004531 return IntRange(R.Width, /*NonNegative*/ true);
4532 }
4533 }
4534 // fallthrough
4535
John McCall2de56d12010-08-25 11:45:40 +00004536 case BO_ShlAssign:
Eli Friedman09bddcf2013-07-08 20:20:06 +00004537 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004538
John McCall60fad452010-01-06 22:07:33 +00004539 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00004540 case BO_Shr:
4541 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00004542 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4543
4544 // If the shift amount is a positive constant, drop the width by
4545 // that much.
4546 llvm::APSInt shift;
4547 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
4548 shift.isNonNegative()) {
4549 unsigned zext = shift.getZExtValue();
4550 if (zext >= L.Width)
4551 L.Width = (L.NonNegative ? 0 : 1);
4552 else
4553 L.Width -= zext;
4554 }
4555
4556 return L;
4557 }
4558
4559 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00004560 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00004561 return GetExprRange(C, BO->getRHS(), MaxWidth);
4562
John McCall60fad452010-01-06 22:07:33 +00004563 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00004564 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00004565 if (BO->getLHS()->getType()->isPointerType())
Eli Friedman09bddcf2013-07-08 20:20:06 +00004566 return IntRange::forValueOfType(C, GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00004567 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00004568
John McCall00fe7612011-07-14 22:39:48 +00004569 // The width of a division result is mostly determined by the size
4570 // of the LHS.
4571 case BO_Div: {
4572 // Don't 'pre-truncate' the operands.
Eli Friedman09bddcf2013-07-08 20:20:06 +00004573 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00004574 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4575
4576 // If the divisor is constant, use that.
4577 llvm::APSInt divisor;
4578 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
4579 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
4580 if (log2 >= L.Width)
4581 L.Width = (L.NonNegative ? 0 : 1);
4582 else
4583 L.Width = std::min(L.Width - log2, MaxWidth);
4584 return L;
4585 }
4586
4587 // Otherwise, just use the LHS's width.
4588 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4589 return IntRange(L.Width, L.NonNegative && R.NonNegative);
4590 }
4591
4592 // The result of a remainder can't be larger than the result of
4593 // either side.
4594 case BO_Rem: {
4595 // Don't 'pre-truncate' the operands.
Eli Friedman09bddcf2013-07-08 20:20:06 +00004596 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00004597 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4598 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4599
4600 IntRange meet = IntRange::meet(L, R);
4601 meet.Width = std::min(meet.Width, MaxWidth);
4602 return meet;
4603 }
4604
4605 // The default behavior is okay for these.
4606 case BO_Mul:
4607 case BO_Add:
4608 case BO_Xor:
4609 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00004610 break;
4611 }
4612
John McCall00fe7612011-07-14 22:39:48 +00004613 // The default case is to treat the operation as if it were closed
4614 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00004615 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4616 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
4617 return IntRange::join(L, R);
4618 }
4619
4620 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
4621 switch (UO->getOpcode()) {
4622 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00004623 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00004624 return IntRange::forBoolType();
4625
4626 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004627 case UO_Deref:
4628 case UO_AddrOf: // should be impossible
Eli Friedman09bddcf2013-07-08 20:20:06 +00004629 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004630
4631 default:
4632 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
4633 }
4634 }
4635
John McCall993f43f2013-05-06 21:39:12 +00004636 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004637 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004638 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00004639
Eli Friedman09bddcf2013-07-08 20:20:06 +00004640 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004641}
John McCall51313c32010-01-04 23:31:57 +00004642
Ted Kremenek0692a192012-01-31 05:37:37 +00004643static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedman09bddcf2013-07-08 20:20:06 +00004644 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCall323ed742010-05-06 08:58:33 +00004645}
4646
John McCall51313c32010-01-04 23:31:57 +00004647/// Checks whether the given value, which currently has the given
4648/// source semantics, has the same value when coerced through the
4649/// target semantics.
Ted Kremenek0692a192012-01-31 05:37:37 +00004650static bool IsSameFloatAfterCast(const llvm::APFloat &value,
4651 const llvm::fltSemantics &Src,
4652 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004653 llvm::APFloat truncated = value;
4654
4655 bool ignored;
4656 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
4657 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
4658
4659 return truncated.bitwiseIsEqual(value);
4660}
4661
4662/// Checks whether the given value, which currently has the given
4663/// source semantics, has the same value when coerced through the
4664/// target semantics.
4665///
4666/// The value might be a vector of floats (or a complex number).
Ted Kremenek0692a192012-01-31 05:37:37 +00004667static bool IsSameFloatAfterCast(const APValue &value,
4668 const llvm::fltSemantics &Src,
4669 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004670 if (value.isFloat())
4671 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
4672
4673 if (value.isVector()) {
4674 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
4675 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
4676 return false;
4677 return true;
4678 }
4679
4680 assert(value.isComplexFloat());
4681 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
4682 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
4683}
4684
Ted Kremenek0692a192012-01-31 05:37:37 +00004685static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00004686
Ted Kremeneke3b159c2010-09-23 21:43:44 +00004687static bool IsZero(Sema &S, Expr *E) {
4688 // Suppress cases where we are comparing against an enum constant.
4689 if (const DeclRefExpr *DR =
4690 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
4691 if (isa<EnumConstantDecl>(DR->getDecl()))
4692 return false;
4693
4694 // Suppress cases where the '0' value is expanded from a macro.
4695 if (E->getLocStart().isMacroID())
4696 return false;
4697
John McCall323ed742010-05-06 08:58:33 +00004698 llvm::APSInt Value;
4699 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
4700}
4701
John McCall372e1032010-10-06 00:25:24 +00004702static bool HasEnumType(Expr *E) {
4703 // Strip off implicit integral promotions.
4704 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004705 if (ICE->getCastKind() != CK_IntegralCast &&
4706 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00004707 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004708 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00004709 }
4710
4711 return E->getType()->isEnumeralType();
4712}
4713
Ted Kremenek0692a192012-01-31 05:37:37 +00004714static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00004715 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00004716 if (E->isValueDependent())
4717 return;
4718
John McCall2de56d12010-08-25 11:45:40 +00004719 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004720 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004721 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004722 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004723 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004724 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004725 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004726 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004727 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004728 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004729 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004730 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004731 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004732 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004733 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004734 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4735 }
4736}
4737
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004738static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004739 Expr *Constant, Expr *Other,
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004740 llvm::APSInt Value,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004741 bool RhsConstant) {
Richard Trieu526e6272012-11-14 22:50:24 +00004742 // 0 values are handled later by CheckTrivialUnsignedComparison().
4743 if (Value == 0)
4744 return;
4745
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004746 BinaryOperatorKind op = E->getOpcode();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004747 QualType OtherT = Other->getType();
4748 QualType ConstantT = Constant->getType();
Richard Trieu526e6272012-11-14 22:50:24 +00004749 QualType CommonT = E->getLHS()->getType();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004750 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004751 return;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004752 assert((OtherT->isIntegerType() && ConstantT->isIntegerType())
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004753 && "comparison with non-integer type");
Richard Trieu526e6272012-11-14 22:50:24 +00004754
4755 bool ConstantSigned = ConstantT->isSignedIntegerType();
Richard Trieu526e6272012-11-14 22:50:24 +00004756 bool CommonSigned = CommonT->isSignedIntegerType();
4757
4758 bool EqualityOnly = false;
4759
4760 // TODO: Investigate using GetExprRange() to get tighter bounds on
4761 // on the bit ranges.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004762 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
Richard Trieu526e6272012-11-14 22:50:24 +00004763 unsigned OtherWidth = OtherRange.Width;
4764
4765 if (CommonSigned) {
4766 // The common type is signed, therefore no signed to unsigned conversion.
Eli Friedmand87de7b2012-11-30 23:09:29 +00004767 if (!OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00004768 // Check that the constant is representable in type OtherT.
4769 if (ConstantSigned) {
4770 if (OtherWidth >= Value.getMinSignedBits())
4771 return;
4772 } else { // !ConstantSigned
4773 if (OtherWidth >= Value.getActiveBits() + 1)
4774 return;
4775 }
4776 } else { // !OtherSigned
4777 // Check that the constant is representable in type OtherT.
4778 // Negative values are out of range.
4779 if (ConstantSigned) {
4780 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
4781 return;
4782 } else { // !ConstantSigned
4783 if (OtherWidth >= Value.getActiveBits())
4784 return;
4785 }
4786 }
4787 } else { // !CommonSigned
Eli Friedmand87de7b2012-11-30 23:09:29 +00004788 if (OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00004789 if (OtherWidth >= Value.getActiveBits())
4790 return;
Eli Friedmand87de7b2012-11-30 23:09:29 +00004791 } else if (!OtherRange.NonNegative && !ConstantSigned) {
Richard Trieu526e6272012-11-14 22:50:24 +00004792 // Check to see if the constant is representable in OtherT.
4793 if (OtherWidth > Value.getActiveBits())
4794 return;
4795 // Check to see if the constant is equivalent to a negative value
4796 // cast to CommonT.
4797 if (S.Context.getIntWidth(ConstantT) == S.Context.getIntWidth(CommonT) &&
Richard Trieu5d1cf4f2012-11-15 03:43:50 +00004798 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
Richard Trieu526e6272012-11-14 22:50:24 +00004799 return;
4800 // The constant value rests between values that OtherT can represent after
4801 // conversion. Relational comparison still works, but equality
4802 // comparisons will be tautological.
4803 EqualityOnly = true;
4804 } else { // OtherSigned && ConstantSigned
4805 assert(0 && "Two signed types converted to unsigned types.");
4806 }
4807 }
4808
4809 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
4810
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004811 bool IsTrue = true;
Richard Trieu526e6272012-11-14 22:50:24 +00004812 if (op == BO_EQ || op == BO_NE) {
4813 IsTrue = op == BO_NE;
4814 } else if (EqualityOnly) {
4815 return;
4816 } else if (RhsConstant) {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004817 if (op == BO_GT || op == BO_GE)
Richard Trieu526e6272012-11-14 22:50:24 +00004818 IsTrue = !PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004819 else // op == BO_LT || op == BO_LE
Richard Trieu526e6272012-11-14 22:50:24 +00004820 IsTrue = PositiveConstant;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004821 } else {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004822 if (op == BO_LT || op == BO_LE)
Richard Trieu526e6272012-11-14 22:50:24 +00004823 IsTrue = !PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004824 else // op == BO_GT || op == BO_GE
Richard Trieu526e6272012-11-14 22:50:24 +00004825 IsTrue = PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004826 }
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004827
4828 // If this is a comparison to an enum constant, include that
4829 // constant in the diagnostic.
4830 const EnumConstantDecl *ED = 0;
4831 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
4832 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
4833
4834 SmallString<64> PrettySourceValue;
4835 llvm::raw_svector_ostream OS(PrettySourceValue);
4836 if (ED)
Ted Kremenek9de50942013-03-15 22:02:46 +00004837 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004838 else
4839 OS << Value;
4840
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004841 S.Diag(E->getOperatorLoc(), diag::warn_out_of_range_compare)
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004842 << OS.str() << OtherT << IsTrue
Richard Trieu526e6272012-11-14 22:50:24 +00004843 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004844}
4845
John McCall323ed742010-05-06 08:58:33 +00004846/// Analyze the operands of the given comparison. Implements the
4847/// fallback case from AnalyzeComparison.
Ted Kremenek0692a192012-01-31 05:37:37 +00004848static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00004849 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4850 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00004851}
John McCall51313c32010-01-04 23:31:57 +00004852
John McCallba26e582010-01-04 23:21:16 +00004853/// \brief Implements -Wsign-compare.
4854///
Richard Trieudd225092011-09-15 21:56:47 +00004855/// \param E the binary operator to check for warnings
Ted Kremenek0692a192012-01-31 05:37:37 +00004856static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCall323ed742010-05-06 08:58:33 +00004857 // The type the comparison is being performed in.
4858 QualType T = E->getLHS()->getType();
4859 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
4860 && "comparison with mismatched types");
Fariborz Jahanianab4702f2012-09-18 17:46:26 +00004861 if (E->isValueDependent())
4862 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004863
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004864 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
4865 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004866
4867 bool IsComparisonConstant = false;
4868
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004869 // Check whether an integer constant comparison results in a value
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004870 // of 'true' or 'false'.
4871 if (T->isIntegralType(S.Context)) {
4872 llvm::APSInt RHSValue;
4873 bool IsRHSIntegralLiteral =
4874 RHS->isIntegerConstantExpr(RHSValue, S.Context);
4875 llvm::APSInt LHSValue;
4876 bool IsLHSIntegralLiteral =
4877 LHS->isIntegerConstantExpr(LHSValue, S.Context);
4878 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
4879 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
4880 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
4881 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
4882 else
4883 IsComparisonConstant =
4884 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004885 } else if (!T->hasUnsignedIntegerRepresentation())
4886 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004887
John McCall323ed742010-05-06 08:58:33 +00004888 // We don't do anything special if this isn't an unsigned integral
4889 // comparison: we're only interested in integral comparisons, and
4890 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00004891 //
4892 // We also don't care about value-dependent expressions or expressions
4893 // whose result is a constant.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004894 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCall323ed742010-05-06 08:58:33 +00004895 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004896
John McCall323ed742010-05-06 08:58:33 +00004897 // Check to see if one of the (unmodified) operands is of different
4898 // signedness.
4899 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00004900 if (LHS->getType()->hasSignedIntegerRepresentation()) {
4901 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00004902 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00004903 signedOperand = LHS;
4904 unsignedOperand = RHS;
4905 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
4906 signedOperand = RHS;
4907 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00004908 } else {
John McCall323ed742010-05-06 08:58:33 +00004909 CheckTrivialUnsignedComparison(S, E);
4910 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004911 }
4912
John McCall323ed742010-05-06 08:58:33 +00004913 // Otherwise, calculate the effective range of the signed operand.
4914 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00004915
John McCall323ed742010-05-06 08:58:33 +00004916 // Go ahead and analyze implicit conversions in the operands. Note
4917 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00004918 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
4919 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00004920
John McCall323ed742010-05-06 08:58:33 +00004921 // If the signed range is non-negative, -Wsign-compare won't fire,
4922 // but we should still check for comparisons which are always true
4923 // or false.
4924 if (signedRange.NonNegative)
4925 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004926
4927 // For (in)equality comparisons, if the unsigned operand is a
4928 // constant which cannot collide with a overflowed signed operand,
4929 // then reinterpreting the signed operand as unsigned will not
4930 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00004931 if (E->isEqualityOp()) {
4932 unsigned comparisonWidth = S.Context.getIntWidth(T);
4933 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00004934
John McCall323ed742010-05-06 08:58:33 +00004935 // We should never be unable to prove that the unsigned operand is
4936 // non-negative.
4937 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
4938
4939 if (unsignedRange.Width < comparisonWidth)
4940 return;
4941 }
4942
Douglas Gregor6d3b93d2012-05-01 01:53:49 +00004943 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
4944 S.PDiag(diag::warn_mixed_sign_comparison)
4945 << LHS->getType() << RHS->getType()
4946 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallba26e582010-01-04 23:21:16 +00004947}
4948
John McCall15d7d122010-11-11 03:21:53 +00004949/// Analyzes an attempt to assign the given value to a bitfield.
4950///
4951/// Returns true if there was something fishy about the attempt.
Ted Kremenek0692a192012-01-31 05:37:37 +00004952static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
4953 SourceLocation InitLoc) {
John McCall15d7d122010-11-11 03:21:53 +00004954 assert(Bitfield->isBitField());
4955 if (Bitfield->isInvalidDecl())
4956 return false;
4957
John McCall91b60142010-11-11 05:33:51 +00004958 // White-list bool bitfields.
4959 if (Bitfield->getType()->isBooleanType())
4960 return false;
4961
Douglas Gregor46ff3032011-02-04 13:09:01 +00004962 // Ignore value- or type-dependent expressions.
4963 if (Bitfield->getBitWidth()->isValueDependent() ||
4964 Bitfield->getBitWidth()->isTypeDependent() ||
4965 Init->isValueDependent() ||
4966 Init->isTypeDependent())
4967 return false;
4968
John McCall15d7d122010-11-11 03:21:53 +00004969 Expr *OriginalInit = Init->IgnoreParenImpCasts();
4970
Richard Smith80d4b552011-12-28 19:48:30 +00004971 llvm::APSInt Value;
4972 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00004973 return false;
4974
John McCall15d7d122010-11-11 03:21:53 +00004975 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004976 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00004977
4978 if (OriginalWidth <= FieldWidth)
4979 return false;
4980
Eli Friedman3a643af2012-01-26 23:11:39 +00004981 // Compute the value which the bitfield will contain.
Jay Foad9f71a8f2010-12-07 08:25:34 +00004982 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedman3a643af2012-01-26 23:11:39 +00004983 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall15d7d122010-11-11 03:21:53 +00004984
Eli Friedman3a643af2012-01-26 23:11:39 +00004985 // Check whether the stored value is equal to the original value.
4986 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieue1ecdc12012-07-23 20:21:35 +00004987 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall15d7d122010-11-11 03:21:53 +00004988 return false;
4989
Eli Friedman3a643af2012-01-26 23:11:39 +00004990 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedman34ff0622012-02-02 00:40:20 +00004991 // therefore don't strictly fit into a signed bitfield of width 1.
4992 if (FieldWidth == 1 && Value == 1)
Eli Friedman3a643af2012-01-26 23:11:39 +00004993 return false;
4994
John McCall15d7d122010-11-11 03:21:53 +00004995 std::string PrettyValue = Value.toString(10);
4996 std::string PrettyTrunc = TruncatedValue.toString(10);
4997
4998 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
4999 << PrettyValue << PrettyTrunc << OriginalInit->getType()
5000 << Init->getSourceRange();
5001
5002 return true;
5003}
5004
John McCallbeb22aa2010-11-09 23:24:47 +00005005/// Analyze the given simple or compound assignment for warning-worthy
5006/// operations.
Ted Kremenek0692a192012-01-31 05:37:37 +00005007static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCallbeb22aa2010-11-09 23:24:47 +00005008 // Just recurse on the LHS.
5009 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5010
5011 // We want to recurse on the RHS as normal unless we're assigning to
5012 // a bitfield.
John McCall993f43f2013-05-06 21:39:12 +00005013 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005014 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall15d7d122010-11-11 03:21:53 +00005015 E->getOperatorLoc())) {
5016 // Recurse, ignoring any implicit conversions on the RHS.
5017 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
5018 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00005019 }
5020 }
5021
5022 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
5023}
5024
John McCall51313c32010-01-04 23:31:57 +00005025/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00005026static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00005027 SourceLocation CContext, unsigned diag,
5028 bool pruneControlFlow = false) {
5029 if (pruneControlFlow) {
5030 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5031 S.PDiag(diag)
5032 << SourceType << T << E->getSourceRange()
5033 << SourceRange(CContext));
5034 return;
5035 }
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005036 S.Diag(E->getExprLoc(), diag)
5037 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
5038}
5039
Chandler Carruthe1b02e02011-04-05 06:47:57 +00005040/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00005041static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00005042 SourceLocation CContext, unsigned diag,
5043 bool pruneControlFlow = false) {
5044 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruthe1b02e02011-04-05 06:47:57 +00005045}
5046
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005047/// Diagnose an implicit cast from a literal expression. Does not warn when the
5048/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00005049void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
5050 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005051 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00005052 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005053 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00005054 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
5055 T->hasUnsignedIntegerRepresentation());
5056 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00005057 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005058 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00005059 return;
5060
David Blaikiebe0ee872012-05-15 16:56:36 +00005061 SmallString<16> PrettySourceValue;
5062 Value.toString(PrettySourceValue);
David Blaikiede7e7b82012-05-15 17:18:27 +00005063 SmallString<16> PrettyTargetValue;
David Blaikiebe0ee872012-05-15 16:56:36 +00005064 if (T->isSpecificBuiltinType(BuiltinType::Bool))
5065 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
5066 else
David Blaikiede7e7b82012-05-15 17:18:27 +00005067 IntegerValue.toString(PrettyTargetValue);
David Blaikiebe0ee872012-05-15 16:56:36 +00005068
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005069 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikiebe0ee872012-05-15 16:56:36 +00005070 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
5071 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00005072}
5073
John McCall091f23f2010-11-09 22:22:12 +00005074std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
5075 if (!Range.Width) return "0";
5076
5077 llvm::APSInt ValueInRange = Value;
5078 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00005079 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00005080 return ValueInRange.toString(10);
5081}
5082
Hans Wennborg88617a22012-08-28 15:44:30 +00005083static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
5084 if (!isa<ImplicitCastExpr>(Ex))
5085 return false;
5086
5087 Expr *InnerE = Ex->IgnoreParenImpCasts();
5088 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
5089 const Type *Source =
5090 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5091 if (Target->isDependentType())
5092 return false;
5093
5094 const BuiltinType *FloatCandidateBT =
5095 dyn_cast<BuiltinType>(ToBool ? Source : Target);
5096 const Type *BoolCandidateType = ToBool ? Target : Source;
5097
5098 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
5099 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
5100}
5101
5102void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
5103 SourceLocation CC) {
5104 unsigned NumArgs = TheCall->getNumArgs();
5105 for (unsigned i = 0; i < NumArgs; ++i) {
5106 Expr *CurrA = TheCall->getArg(i);
5107 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
5108 continue;
5109
5110 bool IsSwapped = ((i > 0) &&
5111 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
5112 IsSwapped |= ((i < (NumArgs - 1)) &&
5113 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
5114 if (IsSwapped) {
5115 // Warn on this floating-point to bool conversion.
5116 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
5117 CurrA->getType(), CC,
5118 diag::warn_impcast_floating_point_to_bool);
5119 }
5120 }
5121}
5122
John McCall323ed742010-05-06 08:58:33 +00005123void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005124 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00005125 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00005126
John McCall323ed742010-05-06 08:58:33 +00005127 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
5128 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
5129 if (Source == Target) return;
5130 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00005131
Chandler Carruth108f7562011-07-26 05:40:03 +00005132 // If the conversion context location is invalid don't complain. We also
5133 // don't want to emit a warning if the issue occurs from the expansion of
5134 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
5135 // delay this check as long as possible. Once we detect we are in that
5136 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00005137 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00005138 return;
5139
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005140 // Diagnose implicit casts to bool.
5141 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
5142 if (isa<StringLiteral>(E))
5143 // Warn on string literal to bool. Checks for string literals in logical
5144 // expressions, for instances, assert(0 && "error here"), is prevented
5145 // by a check in AnalyzeImplicitConversions().
5146 return DiagnoseImpCast(S, E, T, CC,
5147 diag::warn_impcast_string_literal_to_bool);
Lang Hamese14ca9f2011-12-05 20:49:50 +00005148 if (Source->isFunctionType()) {
5149 // Warn on function to bool. Checks free functions and static member
5150 // functions. Weakly imported functions are excluded from the check,
5151 // since it's common to test their value to check whether the linker
5152 // found a definition for them.
5153 ValueDecl *D = 0;
5154 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
5155 D = R->getDecl();
5156 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
5157 D = M->getMemberDecl();
5158 }
5159
5160 if (D && !D->isWeak()) {
Richard Trieu26b45d82011-12-06 04:48:01 +00005161 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
5162 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
5163 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie2def7732011-12-09 21:42:37 +00005164 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
5165 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
5166 QualType ReturnType;
5167 UnresolvedSet<4> NonTemplateOverloads;
David Blaikiec8fa5252013-06-21 23:54:45 +00005168 S.tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
David Blaikie2def7732011-12-09 21:42:37 +00005169 if (!ReturnType.isNull()
5170 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
5171 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
5172 << FixItHint::CreateInsertion(
5173 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu26b45d82011-12-06 04:48:01 +00005174 return;
5175 }
Lang Hamese14ca9f2011-12-05 20:49:50 +00005176 }
5177 }
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005178 }
John McCall51313c32010-01-04 23:31:57 +00005179
5180 // Strip vector types.
5181 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00005182 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005183 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005184 return;
John McCallb4eb64d2010-10-08 02:01:28 +00005185 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005186 }
Chris Lattnerb792b302011-06-14 04:51:15 +00005187
5188 // If the vector cast is cast between two vectors of the same size, it is
5189 // a bitcast, not a conversion.
5190 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
5191 return;
John McCall51313c32010-01-04 23:31:57 +00005192
5193 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
5194 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
5195 }
5196
5197 // Strip complex types.
5198 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00005199 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005200 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005201 return;
5202
John McCallb4eb64d2010-10-08 02:01:28 +00005203 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005204 }
John McCall51313c32010-01-04 23:31:57 +00005205
5206 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
5207 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
5208 }
5209
5210 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
5211 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
5212
5213 // If the source is floating point...
5214 if (SourceBT && SourceBT->isFloatingPoint()) {
5215 // ...and the target is floating point...
5216 if (TargetBT && TargetBT->isFloatingPoint()) {
5217 // ...then warn if we're dropping FP rank.
5218
5219 // Builtin FP kinds are ordered by increasing FP rank.
5220 if (SourceBT->getKind() > TargetBT->getKind()) {
5221 // Don't warn about float constants that are precisely
5222 // representable in the target type.
5223 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00005224 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00005225 // Value might be a float, a float vector, or a float complex.
5226 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00005227 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
5228 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00005229 return;
5230 }
5231
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005232 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005233 return;
5234
John McCallb4eb64d2010-10-08 02:01:28 +00005235 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00005236 }
5237 return;
5238 }
5239
Ted Kremenekef9ff882011-03-10 20:03:42 +00005240 // If the target is integral, always warn.
David Blaikiebe0ee872012-05-15 16:56:36 +00005241 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005242 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005243 return;
5244
Chandler Carrutha5b93322011-02-17 11:05:49 +00005245 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00005246 // We also want to warn on, e.g., "int i = -1.234"
5247 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
5248 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
5249 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
5250
Chandler Carruthf65076e2011-04-10 08:36:24 +00005251 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
5252 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00005253 } else {
5254 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
5255 }
5256 }
John McCall51313c32010-01-04 23:31:57 +00005257
Hans Wennborg88617a22012-08-28 15:44:30 +00005258 // If the target is bool, warn if expr is a function or method call.
5259 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
5260 isa<CallExpr>(E)) {
5261 // Check last argument of function call to see if it is an
5262 // implicit cast from a type matching the type the result
5263 // is being cast to.
5264 CallExpr *CEx = cast<CallExpr>(E);
5265 unsigned NumArgs = CEx->getNumArgs();
5266 if (NumArgs > 0) {
5267 Expr *LastA = CEx->getArg(NumArgs - 1);
5268 Expr *InnerE = LastA->IgnoreParenImpCasts();
5269 const Type *InnerType =
5270 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5271 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
5272 // Warn on this floating-point to bool conversion
5273 DiagnoseImpCast(S, E, T, CC,
5274 diag::warn_impcast_floating_point_to_bool);
5275 }
5276 }
5277 }
John McCall51313c32010-01-04 23:31:57 +00005278 return;
5279 }
5280
Richard Trieu1838ca52011-05-29 19:59:02 +00005281 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikieb26331b2012-06-19 21:19:06 +00005282 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiee81b43b2012-11-08 00:41:20 +00005283 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikie896c7dd2013-02-16 00:56:22 +00005284 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieb1360492012-03-16 20:30:12 +00005285 SourceLocation Loc = E->getSourceRange().getBegin();
5286 if (Loc.isMacroID())
5287 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie9fb1ac52012-05-15 21:57:38 +00005288 if (!Loc.isMacroID() || CC.isMacroID())
5289 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
5290 << T << clang::SourceRange(CC)
5291 << FixItHint::CreateReplacement(Loc, S.getFixItZeroLiteralForType(T));
Richard Trieu1838ca52011-05-29 19:59:02 +00005292 }
5293
David Blaikieb26331b2012-06-19 21:19:06 +00005294 if (!Source->isIntegerType() || !Target->isIntegerType())
5295 return;
5296
David Blaikiebe0ee872012-05-15 16:56:36 +00005297 // TODO: remove this early return once the false positives for constant->bool
5298 // in templates, macros, etc, are reduced or removed.
5299 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
5300 return;
5301
John McCall323ed742010-05-06 08:58:33 +00005302 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00005303 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00005304
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005305 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer25ffbef2013-03-28 19:07:11 +00005306 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005307 // TODO: this should happen for bitfield stores, too.
5308 llvm::APSInt Value(32);
5309 if (E->isIntegerConstantExpr(Value, S.Context)) {
5310 if (S.SourceMgr.isInSystemMacro(CC))
5311 return;
5312
John McCall091f23f2010-11-09 22:22:12 +00005313 std::string PrettySourceValue = Value.toString(10);
5314 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005315
Ted Kremenek5e745da2011-10-22 02:37:33 +00005316 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5317 S.PDiag(diag::warn_impcast_integer_precision_constant)
5318 << PrettySourceValue << PrettyTargetValue
5319 << E->getType() << T << E->getSourceRange()
5320 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00005321 return;
5322 }
5323
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005324 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
5325 if (S.SourceMgr.isInSystemMacro(CC))
5326 return;
5327
David Blaikie37050842012-04-12 22:40:54 +00005328 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaksc36bedc2012-02-01 19:08:57 +00005329 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
5330 /* pruneControlFlow */ true);
John McCallb4eb64d2010-10-08 02:01:28 +00005331 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00005332 }
5333
5334 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
5335 (!TargetRange.NonNegative && SourceRange.NonNegative &&
5336 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00005337
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005338 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005339 return;
5340
John McCall323ed742010-05-06 08:58:33 +00005341 unsigned DiagID = diag::warn_impcast_integer_sign;
5342
5343 // Traditionally, gcc has warned about this under -Wsign-compare.
5344 // We also want to warn about it in -Wconversion.
5345 // So if -Wconversion is off, use a completely identical diagnostic
5346 // in the sign-compare group.
5347 // The conditional-checking code will
5348 if (ICContext) {
5349 DiagID = diag::warn_impcast_integer_sign_conditional;
5350 *ICContext = true;
5351 }
5352
John McCallb4eb64d2010-10-08 02:01:28 +00005353 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00005354 }
5355
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005356 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005357 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
5358 // type, to give us better diagnostics.
5359 QualType SourceType = E->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +00005360 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005361 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5362 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
5363 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
5364 SourceType = S.Context.getTypeDeclType(Enum);
5365 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
5366 }
5367 }
5368
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005369 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
5370 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall83972f12013-03-09 00:54:27 +00005371 if (SourceEnum->getDecl()->hasNameForLinkage() &&
5372 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00005373 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005374 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005375 return;
5376
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005377 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005378 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005379 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005380
John McCall51313c32010-01-04 23:31:57 +00005381 return;
5382}
5383
David Blaikie9fb1ac52012-05-15 21:57:38 +00005384void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5385 SourceLocation CC, QualType T);
John McCall323ed742010-05-06 08:58:33 +00005386
5387void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00005388 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00005389 E = E->IgnoreParenImpCasts();
5390
5391 if (isa<ConditionalOperator>(E))
David Blaikie9fb1ac52012-05-15 21:57:38 +00005392 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCall323ed742010-05-06 08:58:33 +00005393
John McCallb4eb64d2010-10-08 02:01:28 +00005394 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005395 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00005396 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00005397 return;
5398}
5399
David Blaikie9fb1ac52012-05-15 21:57:38 +00005400void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5401 SourceLocation CC, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00005402 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00005403
5404 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00005405 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
5406 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00005407
5408 // If -Wconversion would have warned about either of the candidates
5409 // for a signedness conversion to the context type...
5410 if (!Suspicious) return;
5411
5412 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005413 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
5414 CC))
John McCall323ed742010-05-06 08:58:33 +00005415 return;
5416
John McCall323ed742010-05-06 08:58:33 +00005417 // ...then check whether it would have warned about either of the
5418 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00005419 if (E->getType() == T) return;
5420
5421 Suspicious = false;
5422 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
5423 E->getType(), CC, &Suspicious);
5424 if (!Suspicious)
5425 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00005426 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00005427}
5428
5429/// AnalyzeImplicitConversions - Find and report any interesting
5430/// implicit conversions in the given expression. There are a couple
5431/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00005432void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00005433 QualType T = OrigE->getType();
5434 Expr *E = OrigE->IgnoreParenImpCasts();
5435
Douglas Gregorf8b6e152011-10-10 17:38:18 +00005436 if (E->isTypeDependent() || E->isValueDependent())
5437 return;
5438
John McCall323ed742010-05-06 08:58:33 +00005439 // For conditional operators, we analyze the arguments as if they
5440 // were being fed directly into the output.
5441 if (isa<ConditionalOperator>(E)) {
5442 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie9fb1ac52012-05-15 21:57:38 +00005443 CheckConditionalOperator(S, CO, CC, T);
John McCall323ed742010-05-06 08:58:33 +00005444 return;
5445 }
5446
Hans Wennborg88617a22012-08-28 15:44:30 +00005447 // Check implicit argument conversions for function calls.
5448 if (CallExpr *Call = dyn_cast<CallExpr>(E))
5449 CheckImplicitArgumentConversions(S, Call, CC);
5450
John McCall323ed742010-05-06 08:58:33 +00005451 // Go ahead and check any implicit conversions we might have skipped.
5452 // The non-canonical typecheck is just an optimization;
5453 // CheckImplicitConversion will filter out dead implicit conversions.
5454 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00005455 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00005456
5457 // Now continue drilling into this expression.
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00005458
5459 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00005460 if (POE->getResultExpr())
5461 E = POE->getResultExpr();
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00005462 }
5463
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00005464 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5465 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
5466
John McCall323ed742010-05-06 08:58:33 +00005467 // Skip past explicit casts.
5468 if (isa<ExplicitCastExpr>(E)) {
5469 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00005470 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005471 }
5472
John McCallbeb22aa2010-11-09 23:24:47 +00005473 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5474 // Do a somewhat different check with comparison operators.
5475 if (BO->isComparisonOp())
5476 return AnalyzeComparison(S, BO);
5477
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005478 // And with simple assignments.
5479 if (BO->getOpcode() == BO_Assign)
John McCallbeb22aa2010-11-09 23:24:47 +00005480 return AnalyzeAssignment(S, BO);
5481 }
John McCall323ed742010-05-06 08:58:33 +00005482
5483 // These break the otherwise-useful invariant below. Fortunately,
5484 // we don't really need to recurse into them, because any internal
5485 // expressions should have been analyzed already when they were
5486 // built into statements.
5487 if (isa<StmtExpr>(E)) return;
5488
5489 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005490 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00005491
5492 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00005493 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005494 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
5495 bool IsLogicalOperator = BO && BO->isLogicalOp();
5496 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor54042f12012-02-09 10:18:50 +00005497 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor503384f2012-02-09 00:47:04 +00005498 if (!ChildExpr)
5499 continue;
5500
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005501 if (IsLogicalOperator &&
5502 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
5503 // Ignore checking string literals that are in logical operators.
5504 continue;
5505 AnalyzeImplicitConversions(S, ChildExpr, CC);
5506 }
John McCall323ed742010-05-06 08:58:33 +00005507}
5508
5509} // end anonymous namespace
5510
5511/// Diagnoses "dangerous" implicit conversions within the given
5512/// expression (which is a full expression). Implements -Wconversion
5513/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00005514///
5515/// \param CC the "context" location of the implicit conversion, i.e.
5516/// the most location of the syntactic entity requiring the implicit
5517/// conversion
5518void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00005519 // Don't diagnose in unevaluated contexts.
David Blaikie71f55f72012-08-06 22:47:24 +00005520 if (isUnevaluatedContext())
John McCall323ed742010-05-06 08:58:33 +00005521 return;
5522
5523 // Don't diagnose for value- or type-dependent expressions.
5524 if (E->isTypeDependent() || E->isValueDependent())
5525 return;
5526
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005527 // Check for array bounds violations in cases where the check isn't triggered
5528 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
5529 // ArraySubscriptExpr is on the RHS of a variable initialization.
5530 CheckArrayAccess(E);
5531
John McCallb4eb64d2010-10-08 02:01:28 +00005532 // This is not the right CC for (e.g.) a variable initialization.
5533 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005534}
5535
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005536/// Diagnose when expression is an integer constant expression and its evaluation
5537/// results in integer overflow
5538void Sema::CheckForIntOverflow (Expr *E) {
Fariborz Jahanian1fd8d462013-03-15 20:47:07 +00005539 if (isa<BinaryOperator>(E->IgnoreParens())) {
Robert Wilhelme7205c02013-08-10 12:33:24 +00005540 SmallVector<PartialDiagnosticAt, 4> Diags;
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005541 E->EvaluateForOverflow(Context, &Diags);
5542 }
5543}
5544
Richard Smith6c3af3d2013-01-17 01:17:56 +00005545namespace {
5546/// \brief Visitor for expressions which looks for unsequenced operations on the
5547/// same object.
5548class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smith0c0b3902013-06-30 10:40:20 +00005549 typedef EvaluatedExprVisitor<SequenceChecker> Base;
5550
Richard Smith6c3af3d2013-01-17 01:17:56 +00005551 /// \brief A tree of sequenced regions within an expression. Two regions are
5552 /// unsequenced if one is an ancestor or a descendent of the other. When we
5553 /// finish processing an expression with sequencing, such as a comma
5554 /// expression, we fold its tree nodes into its parent, since they are
5555 /// unsequenced with respect to nodes we will visit later.
5556 class SequenceTree {
5557 struct Value {
5558 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
5559 unsigned Parent : 31;
5560 bool Merged : 1;
5561 };
Robert Wilhelme7205c02013-08-10 12:33:24 +00005562 SmallVector<Value, 8> Values;
Richard Smith6c3af3d2013-01-17 01:17:56 +00005563
5564 public:
5565 /// \brief A region within an expression which may be sequenced with respect
5566 /// to some other region.
5567 class Seq {
5568 explicit Seq(unsigned N) : Index(N) {}
5569 unsigned Index;
5570 friend class SequenceTree;
5571 public:
5572 Seq() : Index(0) {}
5573 };
5574
5575 SequenceTree() { Values.push_back(Value(0)); }
5576 Seq root() const { return Seq(0); }
5577
5578 /// \brief Create a new sequence of operations, which is an unsequenced
5579 /// subset of \p Parent. This sequence of operations is sequenced with
5580 /// respect to other children of \p Parent.
5581 Seq allocate(Seq Parent) {
5582 Values.push_back(Value(Parent.Index));
5583 return Seq(Values.size() - 1);
5584 }
5585
5586 /// \brief Merge a sequence of operations into its parent.
5587 void merge(Seq S) {
5588 Values[S.Index].Merged = true;
5589 }
5590
5591 /// \brief Determine whether two operations are unsequenced. This operation
5592 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
5593 /// should have been merged into its parent as appropriate.
5594 bool isUnsequenced(Seq Cur, Seq Old) {
5595 unsigned C = representative(Cur.Index);
5596 unsigned Target = representative(Old.Index);
5597 while (C >= Target) {
5598 if (C == Target)
5599 return true;
5600 C = Values[C].Parent;
5601 }
5602 return false;
5603 }
5604
5605 private:
5606 /// \brief Pick a representative for a sequence.
5607 unsigned representative(unsigned K) {
5608 if (Values[K].Merged)
5609 // Perform path compression as we go.
5610 return Values[K].Parent = representative(Values[K].Parent);
5611 return K;
5612 }
5613 };
5614
5615 /// An object for which we can track unsequenced uses.
5616 typedef NamedDecl *Object;
5617
5618 /// Different flavors of object usage which we track. We only track the
5619 /// least-sequenced usage of each kind.
5620 enum UsageKind {
5621 /// A read of an object. Multiple unsequenced reads are OK.
5622 UK_Use,
5623 /// A modification of an object which is sequenced before the value
Richard Smith418dd3e2013-06-26 23:16:51 +00005624 /// computation of the expression, such as ++n in C++.
Richard Smith6c3af3d2013-01-17 01:17:56 +00005625 UK_ModAsValue,
5626 /// A modification of an object which is not sequenced before the value
5627 /// computation of the expression, such as n++.
5628 UK_ModAsSideEffect,
5629
5630 UK_Count = UK_ModAsSideEffect + 1
5631 };
5632
5633 struct Usage {
5634 Usage() : Use(0), Seq() {}
5635 Expr *Use;
5636 SequenceTree::Seq Seq;
5637 };
5638
5639 struct UsageInfo {
5640 UsageInfo() : Diagnosed(false) {}
5641 Usage Uses[UK_Count];
5642 /// Have we issued a diagnostic for this variable already?
5643 bool Diagnosed;
5644 };
5645 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
5646
5647 Sema &SemaRef;
5648 /// Sequenced regions within the expression.
5649 SequenceTree Tree;
5650 /// Declaration modifications and references which we have seen.
5651 UsageInfoMap UsageMap;
5652 /// The region we are currently within.
5653 SequenceTree::Seq Region;
5654 /// Filled in with declarations which were modified as a side-effect
5655 /// (that is, post-increment operations).
Robert Wilhelme7205c02013-08-10 12:33:24 +00005656 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smith1a2dcd52013-01-17 23:18:09 +00005657 /// Expressions to check later. We defer checking these to reduce
5658 /// stack usage.
Robert Wilhelme7205c02013-08-10 12:33:24 +00005659 SmallVectorImpl<Expr *> &WorkList;
Richard Smith6c3af3d2013-01-17 01:17:56 +00005660
5661 /// RAII object wrapping the visitation of a sequenced subexpression of an
5662 /// expression. At the end of this process, the side-effects of the evaluation
5663 /// become sequenced with respect to the value computation of the result, so
5664 /// we downgrade any UK_ModAsSideEffect within the evaluation to
5665 /// UK_ModAsValue.
5666 struct SequencedSubexpression {
5667 SequencedSubexpression(SequenceChecker &Self)
5668 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
5669 Self.ModAsSideEffect = &ModAsSideEffect;
5670 }
5671 ~SequencedSubexpression() {
5672 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
5673 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
5674 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
5675 Self.addUsage(U, ModAsSideEffect[I].first,
5676 ModAsSideEffect[I].second.Use, UK_ModAsValue);
5677 }
5678 Self.ModAsSideEffect = OldModAsSideEffect;
5679 }
5680
5681 SequenceChecker &Self;
Robert Wilhelme7205c02013-08-10 12:33:24 +00005682 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
5683 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smith6c3af3d2013-01-17 01:17:56 +00005684 };
5685
Richard Smith67470052013-06-20 22:21:56 +00005686 /// RAII object wrapping the visitation of a subexpression which we might
5687 /// choose to evaluate as a constant. If any subexpression is evaluated and
5688 /// found to be non-constant, this allows us to suppress the evaluation of
5689 /// the outer expression.
5690 class EvaluationTracker {
5691 public:
5692 EvaluationTracker(SequenceChecker &Self)
5693 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
5694 Self.EvalTracker = this;
5695 }
5696 ~EvaluationTracker() {
5697 Self.EvalTracker = Prev;
5698 if (Prev)
5699 Prev->EvalOK &= EvalOK;
5700 }
5701
5702 bool evaluate(const Expr *E, bool &Result) {
5703 if (!EvalOK || E->isValueDependent())
5704 return false;
5705 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
5706 return EvalOK;
5707 }
5708
5709 private:
5710 SequenceChecker &Self;
5711 EvaluationTracker *Prev;
5712 bool EvalOK;
5713 } *EvalTracker;
5714
Richard Smith6c3af3d2013-01-17 01:17:56 +00005715 /// \brief Find the object which is produced by the specified expression,
5716 /// if any.
5717 Object getObject(Expr *E, bool Mod) const {
5718 E = E->IgnoreParenCasts();
5719 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5720 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
5721 return getObject(UO->getSubExpr(), Mod);
5722 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5723 if (BO->getOpcode() == BO_Comma)
5724 return getObject(BO->getRHS(), Mod);
5725 if (Mod && BO->isAssignmentOp())
5726 return getObject(BO->getLHS(), Mod);
5727 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
5728 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
5729 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
5730 return ME->getMemberDecl();
5731 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5732 // FIXME: If this is a reference, map through to its value.
5733 return DRE->getDecl();
5734 return 0;
5735 }
5736
5737 /// \brief Note that an object was modified or used by an expression.
5738 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
5739 Usage &U = UI.Uses[UK];
5740 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
5741 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
5742 ModAsSideEffect->push_back(std::make_pair(O, U));
5743 U.Use = Ref;
5744 U.Seq = Region;
5745 }
5746 }
5747 /// \brief Check whether a modification or use conflicts with a prior usage.
5748 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
5749 bool IsModMod) {
5750 if (UI.Diagnosed)
5751 return;
5752
5753 const Usage &U = UI.Uses[OtherKind];
5754 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
5755 return;
5756
5757 Expr *Mod = U.Use;
5758 Expr *ModOrUse = Ref;
5759 if (OtherKind == UK_Use)
5760 std::swap(Mod, ModOrUse);
5761
5762 SemaRef.Diag(Mod->getExprLoc(),
5763 IsModMod ? diag::warn_unsequenced_mod_mod
5764 : diag::warn_unsequenced_mod_use)
5765 << O << SourceRange(ModOrUse->getExprLoc());
5766 UI.Diagnosed = true;
5767 }
5768
5769 void notePreUse(Object O, Expr *Use) {
5770 UsageInfo &U = UsageMap[O];
5771 // Uses conflict with other modifications.
5772 checkUsage(O, U, Use, UK_ModAsValue, false);
5773 }
5774 void notePostUse(Object O, Expr *Use) {
5775 UsageInfo &U = UsageMap[O];
5776 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
5777 addUsage(U, O, Use, UK_Use);
5778 }
5779
5780 void notePreMod(Object O, Expr *Mod) {
5781 UsageInfo &U = UsageMap[O];
5782 // Modifications conflict with other modifications and with uses.
5783 checkUsage(O, U, Mod, UK_ModAsValue, true);
5784 checkUsage(O, U, Mod, UK_Use, false);
5785 }
5786 void notePostMod(Object O, Expr *Use, UsageKind UK) {
5787 UsageInfo &U = UsageMap[O];
5788 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
5789 addUsage(U, O, Use, UK);
5790 }
5791
5792public:
Robert Wilhelme7205c02013-08-10 12:33:24 +00005793 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
5794 : Base(S.Context), SemaRef(S), Region(Tree.root()), ModAsSideEffect(0),
5795 WorkList(WorkList), EvalTracker(0) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00005796 Visit(E);
5797 }
5798
5799 void VisitStmt(Stmt *S) {
5800 // Skip all statements which aren't expressions for now.
5801 }
5802
5803 void VisitExpr(Expr *E) {
5804 // By default, just recurse to evaluated subexpressions.
Richard Smith0c0b3902013-06-30 10:40:20 +00005805 Base::VisitStmt(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005806 }
5807
5808 void VisitCastExpr(CastExpr *E) {
5809 Object O = Object();
5810 if (E->getCastKind() == CK_LValueToRValue)
5811 O = getObject(E->getSubExpr(), false);
5812
5813 if (O)
5814 notePreUse(O, E);
5815 VisitExpr(E);
5816 if (O)
5817 notePostUse(O, E);
5818 }
5819
5820 void VisitBinComma(BinaryOperator *BO) {
5821 // C++11 [expr.comma]p1:
5822 // Every value computation and side effect associated with the left
5823 // expression is sequenced before every value computation and side
5824 // effect associated with the right expression.
5825 SequenceTree::Seq LHS = Tree.allocate(Region);
5826 SequenceTree::Seq RHS = Tree.allocate(Region);
5827 SequenceTree::Seq OldRegion = Region;
5828
5829 {
5830 SequencedSubexpression SeqLHS(*this);
5831 Region = LHS;
5832 Visit(BO->getLHS());
5833 }
5834
5835 Region = RHS;
5836 Visit(BO->getRHS());
5837
5838 Region = OldRegion;
5839
5840 // Forget that LHS and RHS are sequenced. They are both unsequenced
5841 // with respect to other stuff.
5842 Tree.merge(LHS);
5843 Tree.merge(RHS);
5844 }
5845
5846 void VisitBinAssign(BinaryOperator *BO) {
5847 // The modification is sequenced after the value computation of the LHS
5848 // and RHS, so check it before inspecting the operands and update the
5849 // map afterwards.
5850 Object O = getObject(BO->getLHS(), true);
5851 if (!O)
5852 return VisitExpr(BO);
5853
5854 notePreMod(O, BO);
5855
5856 // C++11 [expr.ass]p7:
5857 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
5858 // only once.
5859 //
5860 // Therefore, for a compound assignment operator, O is considered used
5861 // everywhere except within the evaluation of E1 itself.
5862 if (isa<CompoundAssignOperator>(BO))
5863 notePreUse(O, BO);
5864
5865 Visit(BO->getLHS());
5866
5867 if (isa<CompoundAssignOperator>(BO))
5868 notePostUse(O, BO);
5869
5870 Visit(BO->getRHS());
5871
Richard Smith418dd3e2013-06-26 23:16:51 +00005872 // C++11 [expr.ass]p1:
5873 // the assignment is sequenced [...] before the value computation of the
5874 // assignment expression.
5875 // C11 6.5.16/3 has no such rule.
5876 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
5877 : UK_ModAsSideEffect);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005878 }
5879 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
5880 VisitBinAssign(CAO);
5881 }
5882
5883 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
5884 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
5885 void VisitUnaryPreIncDec(UnaryOperator *UO) {
5886 Object O = getObject(UO->getSubExpr(), true);
5887 if (!O)
5888 return VisitExpr(UO);
5889
5890 notePreMod(O, UO);
5891 Visit(UO->getSubExpr());
Richard Smith418dd3e2013-06-26 23:16:51 +00005892 // C++11 [expr.pre.incr]p1:
5893 // the expression ++x is equivalent to x+=1
5894 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
5895 : UK_ModAsSideEffect);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005896 }
5897
5898 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
5899 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
5900 void VisitUnaryPostIncDec(UnaryOperator *UO) {
5901 Object O = getObject(UO->getSubExpr(), true);
5902 if (!O)
5903 return VisitExpr(UO);
5904
5905 notePreMod(O, UO);
5906 Visit(UO->getSubExpr());
5907 notePostMod(O, UO, UK_ModAsSideEffect);
5908 }
5909
5910 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
5911 void VisitBinLOr(BinaryOperator *BO) {
5912 // The side-effects of the LHS of an '&&' are sequenced before the
5913 // value computation of the RHS, and hence before the value computation
5914 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
5915 // as if they were unconditionally sequenced.
Richard Smith67470052013-06-20 22:21:56 +00005916 EvaluationTracker Eval(*this);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005917 {
5918 SequencedSubexpression Sequenced(*this);
5919 Visit(BO->getLHS());
5920 }
5921
5922 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00005923 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith995e4a72013-01-17 22:06:26 +00005924 if (!Result)
5925 Visit(BO->getRHS());
5926 } else {
5927 // Check for unsequenced operations in the RHS, treating it as an
5928 // entirely separate evaluation.
5929 //
5930 // FIXME: If there are operations in the RHS which are unsequenced
5931 // with respect to operations outside the RHS, and those operations
5932 // are unconditionally evaluated, diagnose them.
Richard Smith1a2dcd52013-01-17 23:18:09 +00005933 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00005934 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005935 }
5936 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith67470052013-06-20 22:21:56 +00005937 EvaluationTracker Eval(*this);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005938 {
5939 SequencedSubexpression Sequenced(*this);
5940 Visit(BO->getLHS());
5941 }
5942
5943 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00005944 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith995e4a72013-01-17 22:06:26 +00005945 if (Result)
5946 Visit(BO->getRHS());
5947 } else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00005948 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00005949 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005950 }
5951
5952 // Only visit the condition, unless we can be sure which subexpression will
5953 // be chosen.
5954 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith67470052013-06-20 22:21:56 +00005955 EvaluationTracker Eval(*this);
Richard Smith418dd3e2013-06-26 23:16:51 +00005956 {
5957 SequencedSubexpression Sequenced(*this);
5958 Visit(CO->getCond());
5959 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005960
5961 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00005962 if (Eval.evaluate(CO->getCond(), Result))
Richard Smith6c3af3d2013-01-17 01:17:56 +00005963 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00005964 else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00005965 WorkList.push_back(CO->getTrueExpr());
5966 WorkList.push_back(CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00005967 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005968 }
5969
Richard Smith0c0b3902013-06-30 10:40:20 +00005970 void VisitCallExpr(CallExpr *CE) {
5971 // C++11 [intro.execution]p15:
5972 // When calling a function [...], every value computation and side effect
5973 // associated with any argument expression, or with the postfix expression
5974 // designating the called function, is sequenced before execution of every
5975 // expression or statement in the body of the function [and thus before
5976 // the value computation of its result].
5977 SequencedSubexpression Sequenced(*this);
5978 Base::VisitCallExpr(CE);
5979
5980 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
5981 }
5982
Richard Smith6c3af3d2013-01-17 01:17:56 +00005983 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smith0c0b3902013-06-30 10:40:20 +00005984 // This is a call, so all subexpressions are sequenced before the result.
5985 SequencedSubexpression Sequenced(*this);
5986
Richard Smith6c3af3d2013-01-17 01:17:56 +00005987 if (!CCE->isListInitialization())
5988 return VisitExpr(CCE);
5989
5990 // In C++11, list initializations are sequenced.
Robert Wilhelme7205c02013-08-10 12:33:24 +00005991 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smith6c3af3d2013-01-17 01:17:56 +00005992 SequenceTree::Seq Parent = Region;
5993 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
5994 E = CCE->arg_end();
5995 I != E; ++I) {
5996 Region = Tree.allocate(Parent);
5997 Elts.push_back(Region);
5998 Visit(*I);
5999 }
6000
6001 // Forget that the initializers are sequenced.
6002 Region = Parent;
6003 for (unsigned I = 0; I < Elts.size(); ++I)
6004 Tree.merge(Elts[I]);
6005 }
6006
6007 void VisitInitListExpr(InitListExpr *ILE) {
6008 if (!SemaRef.getLangOpts().CPlusPlus11)
6009 return VisitExpr(ILE);
6010
6011 // In C++11, list initializations are sequenced.
Robert Wilhelme7205c02013-08-10 12:33:24 +00006012 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smith6c3af3d2013-01-17 01:17:56 +00006013 SequenceTree::Seq Parent = Region;
6014 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
6015 Expr *E = ILE->getInit(I);
6016 if (!E) continue;
6017 Region = Tree.allocate(Parent);
6018 Elts.push_back(Region);
6019 Visit(E);
6020 }
6021
6022 // Forget that the initializers are sequenced.
6023 Region = Parent;
6024 for (unsigned I = 0; I < Elts.size(); ++I)
6025 Tree.merge(Elts[I]);
6026 }
6027};
6028}
6029
6030void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelme7205c02013-08-10 12:33:24 +00006031 SmallVector<Expr *, 8> WorkList;
Richard Smith1a2dcd52013-01-17 23:18:09 +00006032 WorkList.push_back(E);
6033 while (!WorkList.empty()) {
Robert Wilhelm344472e2013-08-23 16:11:15 +00006034 Expr *Item = WorkList.pop_back_val();
Richard Smith1a2dcd52013-01-17 23:18:09 +00006035 SequenceChecker(*this, Item, WorkList);
6036 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00006037}
6038
Fariborz Jahanianad48a502013-01-24 22:11:45 +00006039void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
6040 bool IsConstexpr) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00006041 CheckImplicitConversions(E, CheckLoc);
6042 CheckUnsequencedOperations(E);
Fariborz Jahanianad48a502013-01-24 22:11:45 +00006043 if (!IsConstexpr && !E->isValueDependent())
6044 CheckForIntOverflow(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00006045}
6046
John McCall15d7d122010-11-11 03:21:53 +00006047void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
6048 FieldDecl *BitField,
6049 Expr *Init) {
6050 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
6051}
6052
Mike Stumpf8c49212010-01-21 03:59:47 +00006053/// CheckParmsForFunctionDef - Check that the parameters of the given
6054/// function are appropriate for the definition of a function. This
6055/// takes care of any checks that cannot be performed on the
6056/// declaration itself, e.g., that the types of each of the function
6057/// parameters are complete.
Reid Kleckner8c0501c2013-06-24 14:38:26 +00006058bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
6059 ParmVarDecl *const *PEnd,
Douglas Gregor82aa7132010-11-01 18:37:59 +00006060 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00006061 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00006062 for (; P != PEnd; ++P) {
6063 ParmVarDecl *Param = *P;
6064
Mike Stumpf8c49212010-01-21 03:59:47 +00006065 // C99 6.7.5.3p4: the parameters in a parameter type list in a
6066 // function declarator that is part of a function definition of
6067 // that function shall not have incomplete type.
6068 //
6069 // This is also C++ [dcl.fct]p6.
6070 if (!Param->isInvalidDecl() &&
6071 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00006072 diag::err_typecheck_decl_incomplete_type)) {
Mike Stumpf8c49212010-01-21 03:59:47 +00006073 Param->setInvalidDecl();
6074 HasInvalidParm = true;
6075 }
6076
6077 // C99 6.9.1p5: If the declarator includes a parameter type list, the
6078 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00006079 if (CheckParameterNames &&
6080 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00006081 !Param->isImplicit() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006082 !getLangOpts().CPlusPlus)
Mike Stumpf8c49212010-01-21 03:59:47 +00006083 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00006084
6085 // C99 6.7.5.3p12:
6086 // If the function declarator is not part of a definition of that
6087 // function, parameters may have incomplete type and may use the [*]
6088 // notation in their sequences of declarator specifiers to specify
6089 // variable length array types.
6090 QualType PType = Param->getOriginalType();
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00006091 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigd17e3402010-02-01 05:02:49 +00006092 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitfc093362013-03-01 21:41:22 +00006093 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigd17e3402010-02-01 05:02:49 +00006094 // information is added for it.
6095 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00006096 break;
Sam Weinigd17e3402010-02-01 05:02:49 +00006097 }
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00006098 PType= AT->getElementType();
Sam Weinigd17e3402010-02-01 05:02:49 +00006099 }
Reid Kleckner9b601952013-06-21 12:45:15 +00006100
6101 // MSVC destroys objects passed by value in the callee. Therefore a
6102 // function definition which takes such a parameter must be able to call the
6103 // object's destructor.
6104 if (getLangOpts().CPlusPlus &&
6105 Context.getTargetInfo().getCXXABI().isArgumentDestroyedByCallee()) {
6106 if (const RecordType *RT = Param->getType()->getAs<RecordType>())
6107 FinalizeVarWithDestructor(Param, RT);
6108 }
Mike Stumpf8c49212010-01-21 03:59:47 +00006109 }
6110
6111 return HasInvalidParm;
6112}
John McCallb7f4ffe2010-08-12 21:44:57 +00006113
6114/// CheckCastAlign - Implements -Wcast-align, which warns when a
6115/// pointer cast increases the alignment requirements.
6116void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
6117 // This is actually a lot of work to potentially be doing on every
6118 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00006119 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
6120 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00006121 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00006122 return;
6123
6124 // Ignore dependent types.
6125 if (T->isDependentType() || Op->getType()->isDependentType())
6126 return;
6127
6128 // Require that the destination be a pointer type.
6129 const PointerType *DestPtr = T->getAs<PointerType>();
6130 if (!DestPtr) return;
6131
6132 // If the destination has alignment 1, we're done.
6133 QualType DestPointee = DestPtr->getPointeeType();
6134 if (DestPointee->isIncompleteType()) return;
6135 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
6136 if (DestAlign.isOne()) return;
6137
6138 // Require that the source be a pointer type.
6139 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
6140 if (!SrcPtr) return;
6141 QualType SrcPointee = SrcPtr->getPointeeType();
6142
6143 // Whitelist casts from cv void*. We already implicitly
6144 // whitelisted casts to cv void*, since they have alignment 1.
6145 // Also whitelist casts involving incomplete types, which implicitly
6146 // includes 'void'.
6147 if (SrcPointee->isIncompleteType()) return;
6148
6149 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
6150 if (SrcAlign >= DestAlign) return;
6151
6152 Diag(TRange.getBegin(), diag::warn_cast_align)
6153 << Op->getType() << T
6154 << static_cast<unsigned>(SrcAlign.getQuantity())
6155 << static_cast<unsigned>(DestAlign.getQuantity())
6156 << TRange << Op->getSourceRange();
6157}
6158
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006159static const Type* getElementType(const Expr *BaseExpr) {
6160 const Type* EltType = BaseExpr->getType().getTypePtr();
6161 if (EltType->isAnyPointerType())
6162 return EltType->getPointeeType().getTypePtr();
6163 else if (EltType->isArrayType())
6164 return EltType->getBaseElementTypeUnsafe();
6165 return EltType;
6166}
6167
Chandler Carruthc2684342011-08-05 09:10:50 +00006168/// \brief Check whether this array fits the idiom of a size-one tail padded
6169/// array member of a struct.
6170///
6171/// We avoid emitting out-of-bounds access warnings for such arrays as they are
6172/// commonly used to emulate flexible arrays in C89 code.
6173static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
6174 const NamedDecl *ND) {
6175 if (Size != 1 || !ND) return false;
6176
6177 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
6178 if (!FD) return false;
6179
6180 // Don't consider sizes resulting from macro expansions or template argument
6181 // substitution to form C89 tail-padded arrays.
Sean Callanand2cf3482012-05-04 18:22:53 +00006182
6183 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00006184 while (TInfo) {
6185 TypeLoc TL = TInfo->getTypeLoc();
6186 // Look through typedefs.
David Blaikie39e6ab42013-02-18 22:06:02 +00006187 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
6188 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00006189 TInfo = TDL->getTypeSourceInfo();
6190 continue;
6191 }
David Blaikie39e6ab42013-02-18 22:06:02 +00006192 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
6193 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier5e253012013-02-06 00:58:34 +00006194 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
6195 return false;
6196 }
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00006197 break;
Sean Callanand2cf3482012-05-04 18:22:53 +00006198 }
Chandler Carruthc2684342011-08-05 09:10:50 +00006199
6200 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00006201 if (!RD) return false;
6202 if (RD->isUnion()) return false;
6203 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
6204 if (!CRD->isStandardLayout()) return false;
6205 }
Chandler Carruthc2684342011-08-05 09:10:50 +00006206
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00006207 // See if this is the last field decl in the record.
6208 const Decl *D = FD;
6209 while ((D = D->getNextDeclInContext()))
6210 if (isa<FieldDecl>(D))
6211 return false;
6212 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00006213}
6214
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006215void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006216 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00006217 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman92b670e2012-02-27 21:21:40 +00006218 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006219 if (IndexExpr->isValueDependent())
6220 return;
6221
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00006222 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006223 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00006224 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006225 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00006226 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00006227 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00006228
Chandler Carruth34064582011-02-17 20:55:08 +00006229 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006230 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00006231 return;
Richard Smith25b009a2011-12-16 19:31:14 +00006232 if (IndexNegated)
6233 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00006234
Chandler Carruthba447122011-08-05 08:07:29 +00006235 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00006236 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6237 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00006238 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00006239 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00006240
Ted Kremenek9e060ca2011-02-23 23:06:04 +00006241 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00006242 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00006243 if (!size.isStrictlyPositive())
6244 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006245
6246 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00006247 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006248 // Make sure we're comparing apples to apples when comparing index to size
6249 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
6250 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00006251 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00006252 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006253 if (ptrarith_typesize != array_typesize) {
6254 // There's a cast to a different size type involved
6255 uint64_t ratio = array_typesize / ptrarith_typesize;
6256 // TODO: Be smarter about handling cases where array_typesize is not a
6257 // multiple of ptrarith_typesize
6258 if (ptrarith_typesize * ratio == array_typesize)
6259 size *= llvm::APInt(size.getBitWidth(), ratio);
6260 }
6261 }
6262
Chandler Carruth34064582011-02-17 20:55:08 +00006263 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00006264 index = index.zext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00006265 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00006266 size = size.zext(index.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00006267
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006268 // For array subscripting the index must be less than size, but for pointer
6269 // arithmetic also allow the index (offset) to be equal to size since
6270 // computing the next address after the end of the array is legal and
6271 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman92b670e2012-02-27 21:21:40 +00006272 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruthba447122011-08-05 08:07:29 +00006273 return;
6274
6275 // Also don't warn for arrays of size 1 which are members of some
6276 // structure. These are often used to approximate flexible arrays in C89
6277 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006278 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00006279 return;
Chandler Carruth34064582011-02-17 20:55:08 +00006280
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006281 // Suppress the warning if the subscript expression (as identified by the
6282 // ']' location) and the index expression are both from macro expansions
6283 // within a system header.
6284 if (ASE) {
6285 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
6286 ASE->getRBracketLoc());
6287 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
6288 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
6289 IndexExpr->getLocStart());
Eli Friedman24146972013-08-22 00:27:10 +00006290 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006291 return;
6292 }
6293 }
6294
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006295 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006296 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006297 DiagID = diag::warn_array_index_exceeds_bounds;
6298
6299 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6300 PDiag(DiagID) << index.toString(10, true)
6301 << size.toString(10, true)
6302 << (unsigned)size.getLimitedValue(~0U)
6303 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00006304 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006305 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006306 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006307 DiagID = diag::warn_ptr_arith_precedes_bounds;
6308 if (index.isNegative()) index = -index;
6309 }
6310
6311 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6312 PDiag(DiagID) << index.toString(10, true)
6313 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00006314 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00006315
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00006316 if (!ND) {
6317 // Try harder to find a NamedDecl to point at in the note.
6318 while (const ArraySubscriptExpr *ASE =
6319 dyn_cast<ArraySubscriptExpr>(BaseExpr))
6320 BaseExpr = ASE->getBase()->IgnoreParenCasts();
6321 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6322 ND = dyn_cast<NamedDecl>(DRE->getDecl());
6323 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
6324 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
6325 }
6326
Chandler Carruth35001ca2011-02-17 21:10:52 +00006327 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006328 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
6329 PDiag(diag::note_array_index_out_of_bounds)
6330 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00006331}
6332
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006333void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006334 int AllowOnePastEnd = 0;
6335 while (expr) {
6336 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006337 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006338 case Stmt::ArraySubscriptExprClass: {
6339 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006340 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006341 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006342 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006343 }
6344 case Stmt::UnaryOperatorClass: {
6345 // Only unwrap the * and & unary operators
6346 const UnaryOperator *UO = cast<UnaryOperator>(expr);
6347 expr = UO->getSubExpr();
6348 switch (UO->getOpcode()) {
6349 case UO_AddrOf:
6350 AllowOnePastEnd++;
6351 break;
6352 case UO_Deref:
6353 AllowOnePastEnd--;
6354 break;
6355 default:
6356 return;
6357 }
6358 break;
6359 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006360 case Stmt::ConditionalOperatorClass: {
6361 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
6362 if (const Expr *lhs = cond->getLHS())
6363 CheckArrayAccess(lhs);
6364 if (const Expr *rhs = cond->getRHS())
6365 CheckArrayAccess(rhs);
6366 return;
6367 }
6368 default:
6369 return;
6370 }
Peter Collingbournef111d932011-04-15 00:35:48 +00006371 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006372}
John McCallf85e1932011-06-15 23:02:42 +00006373
6374//===--- CHECK: Objective-C retain cycles ----------------------------------//
6375
6376namespace {
6377 struct RetainCycleOwner {
6378 RetainCycleOwner() : Variable(0), Indirect(false) {}
6379 VarDecl *Variable;
6380 SourceRange Range;
6381 SourceLocation Loc;
6382 bool Indirect;
6383
6384 void setLocsFrom(Expr *e) {
6385 Loc = e->getExprLoc();
6386 Range = e->getSourceRange();
6387 }
6388 };
6389}
6390
6391/// Consider whether capturing the given variable can possibly lead to
6392/// a retain cycle.
6393static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00006394 // In ARC, it's captured strongly iff the variable has __strong
John McCallf85e1932011-06-15 23:02:42 +00006395 // lifetime. In MRR, it's captured strongly if the variable is
6396 // __block and has an appropriate type.
6397 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6398 return false;
6399
6400 owner.Variable = var;
Jordan Rosee10f4d32012-09-15 02:48:31 +00006401 if (ref)
6402 owner.setLocsFrom(ref);
John McCallf85e1932011-06-15 23:02:42 +00006403 return true;
6404}
6405
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006406static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00006407 while (true) {
6408 e = e->IgnoreParens();
6409 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
6410 switch (cast->getCastKind()) {
6411 case CK_BitCast:
6412 case CK_LValueBitCast:
6413 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00006414 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00006415 e = cast->getSubExpr();
6416 continue;
6417
John McCallf85e1932011-06-15 23:02:42 +00006418 default:
6419 return false;
6420 }
6421 }
6422
6423 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
6424 ObjCIvarDecl *ivar = ref->getDecl();
6425 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6426 return false;
6427
6428 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006429 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00006430 return false;
6431
6432 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
6433 owner.Indirect = true;
6434 return true;
6435 }
6436
6437 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
6438 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
6439 if (!var) return false;
6440 return considerVariable(var, ref, owner);
6441 }
6442
John McCallf85e1932011-06-15 23:02:42 +00006443 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
6444 if (member->isArrow()) return false;
6445
6446 // Don't count this as an indirect ownership.
6447 e = member->getBase();
6448 continue;
6449 }
6450
John McCall4b9c2d22011-11-06 09:01:30 +00006451 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
6452 // Only pay attention to pseudo-objects on property references.
6453 ObjCPropertyRefExpr *pre
6454 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
6455 ->IgnoreParens());
6456 if (!pre) return false;
6457 if (pre->isImplicitProperty()) return false;
6458 ObjCPropertyDecl *property = pre->getExplicitProperty();
6459 if (!property->isRetaining() &&
6460 !(property->getPropertyIvarDecl() &&
6461 property->getPropertyIvarDecl()->getType()
6462 .getObjCLifetime() == Qualifiers::OCL_Strong))
6463 return false;
6464
6465 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006466 if (pre->isSuperReceiver()) {
6467 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
6468 if (!owner.Variable)
6469 return false;
6470 owner.Loc = pre->getLocation();
6471 owner.Range = pre->getSourceRange();
6472 return true;
6473 }
John McCall4b9c2d22011-11-06 09:01:30 +00006474 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
6475 ->getSourceExpr());
6476 continue;
6477 }
6478
John McCallf85e1932011-06-15 23:02:42 +00006479 // Array ivars?
6480
6481 return false;
6482 }
6483}
6484
6485namespace {
6486 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
6487 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
6488 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
6489 Variable(variable), Capturer(0) {}
6490
6491 VarDecl *Variable;
6492 Expr *Capturer;
6493
6494 void VisitDeclRefExpr(DeclRefExpr *ref) {
6495 if (ref->getDecl() == Variable && !Capturer)
6496 Capturer = ref;
6497 }
6498
John McCallf85e1932011-06-15 23:02:42 +00006499 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
6500 if (Capturer) return;
6501 Visit(ref->getBase());
6502 if (Capturer && ref->isFreeIvar())
6503 Capturer = ref;
6504 }
6505
6506 void VisitBlockExpr(BlockExpr *block) {
6507 // Look inside nested blocks
6508 if (block->getBlockDecl()->capturesVariable(Variable))
6509 Visit(block->getBlockDecl()->getBody());
6510 }
Fariborz Jahanian7e2e4c32012-08-31 20:04:47 +00006511
6512 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
6513 if (Capturer) return;
6514 if (OVE->getSourceExpr())
6515 Visit(OVE->getSourceExpr());
6516 }
John McCallf85e1932011-06-15 23:02:42 +00006517 };
6518}
6519
6520/// Check whether the given argument is a block which captures a
6521/// variable.
6522static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
6523 assert(owner.Variable && owner.Loc.isValid());
6524
6525 e = e->IgnoreParenCasts();
Jordan Rose1fac58a2012-09-17 17:54:30 +00006526
6527 // Look through [^{...} copy] and Block_copy(^{...}).
6528 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
6529 Selector Cmd = ME->getSelector();
6530 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
6531 e = ME->getInstanceReceiver();
6532 if (!e)
6533 return 0;
6534 e = e->IgnoreParenCasts();
6535 }
6536 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
6537 if (CE->getNumArgs() == 1) {
6538 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekd13eff62012-10-02 04:36:54 +00006539 if (Fn) {
6540 const IdentifierInfo *FnI = Fn->getIdentifier();
6541 if (FnI && FnI->isStr("_Block_copy")) {
6542 e = CE->getArg(0)->IgnoreParenCasts();
6543 }
6544 }
Jordan Rose1fac58a2012-09-17 17:54:30 +00006545 }
6546 }
6547
John McCallf85e1932011-06-15 23:02:42 +00006548 BlockExpr *block = dyn_cast<BlockExpr>(e);
6549 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
6550 return 0;
6551
6552 FindCaptureVisitor visitor(S.Context, owner.Variable);
6553 visitor.Visit(block->getBlockDecl()->getBody());
6554 return visitor.Capturer;
6555}
6556
6557static void diagnoseRetainCycle(Sema &S, Expr *capturer,
6558 RetainCycleOwner &owner) {
6559 assert(capturer);
6560 assert(owner.Variable && owner.Loc.isValid());
6561
6562 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
6563 << owner.Variable << capturer->getSourceRange();
6564 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
6565 << owner.Indirect << owner.Range;
6566}
6567
6568/// Check for a keyword selector that starts with the word 'add' or
6569/// 'set'.
6570static bool isSetterLikeSelector(Selector sel) {
6571 if (sel.isUnarySelector()) return false;
6572
Chris Lattner5f9e2722011-07-23 10:55:15 +00006573 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00006574 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00006575 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00006576 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00006577 else if (str.startswith("add")) {
6578 // Specially whitelist 'addOperationWithBlock:'.
6579 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
6580 return false;
6581 str = str.substr(3);
6582 }
John McCallf85e1932011-06-15 23:02:42 +00006583 else
6584 return false;
6585
6586 if (str.empty()) return true;
Jordan Rose3f6f51e2013-02-08 22:30:41 +00006587 return !isLowercase(str.front());
John McCallf85e1932011-06-15 23:02:42 +00006588}
6589
6590/// Check a message send to see if it's likely to cause a retain cycle.
6591void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
6592 // Only check instance methods whose selector looks like a setter.
6593 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
6594 return;
6595
6596 // Try to find a variable that the receiver is strongly owned by.
6597 RetainCycleOwner owner;
6598 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006599 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00006600 return;
6601 } else {
6602 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
6603 owner.Variable = getCurMethodDecl()->getSelfDecl();
6604 owner.Loc = msg->getSuperLoc();
6605 owner.Range = msg->getSuperLoc();
6606 }
6607
6608 // Check whether the receiver is captured by any of the arguments.
6609 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
6610 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
6611 return diagnoseRetainCycle(*this, capturer, owner);
6612}
6613
6614/// Check a property assign to see if it's likely to cause a retain cycle.
6615void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
6616 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006617 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00006618 return;
6619
6620 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
6621 diagnoseRetainCycle(*this, capturer, owner);
6622}
6623
Jordan Rosee10f4d32012-09-15 02:48:31 +00006624void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
6625 RetainCycleOwner Owner;
6626 if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
6627 return;
6628
6629 // Because we don't have an expression for the variable, we have to set the
6630 // location explicitly here.
6631 Owner.Loc = Var->getLocation();
6632 Owner.Range = Var->getSourceRange();
6633
6634 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
6635 diagnoseRetainCycle(*this, Capturer, Owner);
6636}
6637
Ted Kremenek9d084012012-12-21 08:04:28 +00006638static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
6639 Expr *RHS, bool isProperty) {
6640 // Check if RHS is an Objective-C object literal, which also can get
6641 // immediately zapped in a weak reference. Note that we explicitly
6642 // allow ObjCStringLiterals, since those are designed to never really die.
6643 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenekf530ff72012-12-21 21:59:39 +00006644
Ted Kremenekd3292c82012-12-21 22:46:35 +00006645 // This enum needs to match with the 'select' in
6646 // warn_objc_arc_literal_assign (off-by-1).
6647 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
6648 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
6649 return false;
Ted Kremenekf530ff72012-12-21 21:59:39 +00006650
6651 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenekd3292c82012-12-21 22:46:35 +00006652 << (unsigned) Kind
Ted Kremenek9d084012012-12-21 08:04:28 +00006653 << (isProperty ? 0 : 1)
6654 << RHS->getSourceRange();
Ted Kremenekf530ff72012-12-21 21:59:39 +00006655
6656 return true;
Ted Kremenek9d084012012-12-21 08:04:28 +00006657}
6658
Ted Kremenekb29b30f2012-12-21 19:45:30 +00006659static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
6660 Qualifiers::ObjCLifetime LT,
6661 Expr *RHS, bool isProperty) {
6662 // Strip off any implicit cast added to get to the one ARC-specific.
6663 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
6664 if (cast->getCastKind() == CK_ARCConsumeObject) {
6665 S.Diag(Loc, diag::warn_arc_retained_assign)
6666 << (LT == Qualifiers::OCL_ExplicitNone)
6667 << (isProperty ? 0 : 1)
6668 << RHS->getSourceRange();
6669 return true;
6670 }
6671 RHS = cast->getSubExpr();
6672 }
6673
6674 if (LT == Qualifiers::OCL_Weak &&
6675 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
6676 return true;
6677
6678 return false;
6679}
6680
Ted Kremenekb1ea5102012-12-21 08:04:20 +00006681bool Sema::checkUnsafeAssigns(SourceLocation Loc,
6682 QualType LHS, Expr *RHS) {
6683 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
6684
6685 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
6686 return false;
6687
6688 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
6689 return true;
6690
6691 return false;
6692}
6693
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006694void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
6695 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006696 QualType LHSType;
6697 // PropertyRef on LHS type need be directly obtained from
6698 // its declaration as it has a PsuedoType.
6699 ObjCPropertyRefExpr *PRE
6700 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
6701 if (PRE && !PRE->isImplicitProperty()) {
6702 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6703 if (PD)
6704 LHSType = PD->getType();
6705 }
6706
6707 if (LHSType.isNull())
6708 LHSType = LHS->getType();
Jordan Rose7a270482012-09-28 22:21:35 +00006709
6710 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
6711
6712 if (LT == Qualifiers::OCL_Weak) {
6713 DiagnosticsEngine::Level Level =
6714 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
6715 if (Level != DiagnosticsEngine::Ignored)
6716 getCurFunction()->markSafeWeakUse(LHS);
6717 }
6718
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006719 if (checkUnsafeAssigns(Loc, LHSType, RHS))
6720 return;
Jordan Rose7a270482012-09-28 22:21:35 +00006721
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006722 // FIXME. Check for other life times.
6723 if (LT != Qualifiers::OCL_None)
6724 return;
6725
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006726 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006727 if (PRE->isImplicitProperty())
6728 return;
6729 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6730 if (!PD)
6731 return;
6732
Bill Wendlingad017fa2012-12-20 19:22:21 +00006733 unsigned Attributes = PD->getPropertyAttributes();
6734 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006735 // when 'assign' attribute was not explicitly specified
6736 // by user, ignore it and rely on property type itself
6737 // for lifetime info.
6738 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
6739 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
6740 LHSType->isObjCRetainableType())
6741 return;
6742
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006743 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00006744 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006745 Diag(Loc, diag::warn_arc_retained_property_assign)
6746 << RHS->getSourceRange();
6747 return;
6748 }
6749 RHS = cast->getSubExpr();
6750 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006751 }
Bill Wendlingad017fa2012-12-20 19:22:21 +00006752 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb1ea5102012-12-21 08:04:20 +00006753 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
6754 return;
Fariborz Jahanianbd2e27e2012-07-06 21:09:27 +00006755 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006756 }
6757}
Dmitri Gribenko625bb562012-02-14 22:14:32 +00006758
6759//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
6760
6761namespace {
6762bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
6763 SourceLocation StmtLoc,
6764 const NullStmt *Body) {
6765 // Do not warn if the body is a macro that expands to nothing, e.g:
6766 //
6767 // #define CALL(x)
6768 // if (condition)
6769 // CALL(0);
6770 //
6771 if (Body->hasLeadingEmptyMacro())
6772 return false;
6773
6774 // Get line numbers of statement and body.
6775 bool StmtLineInvalid;
6776 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
6777 &StmtLineInvalid);
6778 if (StmtLineInvalid)
6779 return false;
6780
6781 bool BodyLineInvalid;
6782 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
6783 &BodyLineInvalid);
6784 if (BodyLineInvalid)
6785 return false;
6786
6787 // Warn if null statement and body are on the same line.
6788 if (StmtLine != BodyLine)
6789 return false;
6790
6791 return true;
6792}
6793} // Unnamed namespace
6794
6795void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
6796 const Stmt *Body,
6797 unsigned DiagID) {
6798 // Since this is a syntactic check, don't emit diagnostic for template
6799 // instantiations, this just adds noise.
6800 if (CurrentInstantiationScope)
6801 return;
6802
6803 // The body should be a null statement.
6804 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6805 if (!NBody)
6806 return;
6807
6808 // Do the usual checks.
6809 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6810 return;
6811
6812 Diag(NBody->getSemiLoc(), DiagID);
6813 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6814}
6815
6816void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
6817 const Stmt *PossibleBody) {
6818 assert(!CurrentInstantiationScope); // Ensured by caller
6819
6820 SourceLocation StmtLoc;
6821 const Stmt *Body;
6822 unsigned DiagID;
6823 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
6824 StmtLoc = FS->getRParenLoc();
6825 Body = FS->getBody();
6826 DiagID = diag::warn_empty_for_body;
6827 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
6828 StmtLoc = WS->getCond()->getSourceRange().getEnd();
6829 Body = WS->getBody();
6830 DiagID = diag::warn_empty_while_body;
6831 } else
6832 return; // Neither `for' nor `while'.
6833
6834 // The body should be a null statement.
6835 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6836 if (!NBody)
6837 return;
6838
6839 // Skip expensive checks if diagnostic is disabled.
6840 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
6841 DiagnosticsEngine::Ignored)
6842 return;
6843
6844 // Do the usual checks.
6845 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6846 return;
6847
6848 // `for(...);' and `while(...);' are popular idioms, so in order to keep
6849 // noise level low, emit diagnostics only if for/while is followed by a
6850 // CompoundStmt, e.g.:
6851 // for (int i = 0; i < n; i++);
6852 // {
6853 // a(i);
6854 // }
6855 // or if for/while is followed by a statement with more indentation
6856 // than for/while itself:
6857 // for (int i = 0; i < n; i++);
6858 // a(i);
6859 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
6860 if (!ProbableTypo) {
6861 bool BodyColInvalid;
6862 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
6863 PossibleBody->getLocStart(),
6864 &BodyColInvalid);
6865 if (BodyColInvalid)
6866 return;
6867
6868 bool StmtColInvalid;
6869 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
6870 S->getLocStart(),
6871 &StmtColInvalid);
6872 if (StmtColInvalid)
6873 return;
6874
6875 if (BodyCol > StmtCol)
6876 ProbableTypo = true;
6877 }
6878
6879 if (ProbableTypo) {
6880 Diag(NBody->getSemiLoc(), DiagID);
6881 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6882 }
6883}
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00006884
6885//===--- Layout compatibility ----------------------------------------------//
6886
6887namespace {
6888
6889bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
6890
6891/// \brief Check if two enumeration types are layout-compatible.
6892bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
6893 // C++11 [dcl.enum] p8:
6894 // Two enumeration types are layout-compatible if they have the same
6895 // underlying type.
6896 return ED1->isComplete() && ED2->isComplete() &&
6897 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
6898}
6899
6900/// \brief Check if two fields are layout-compatible.
6901bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
6902 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
6903 return false;
6904
6905 if (Field1->isBitField() != Field2->isBitField())
6906 return false;
6907
6908 if (Field1->isBitField()) {
6909 // Make sure that the bit-fields are the same length.
6910 unsigned Bits1 = Field1->getBitWidthValue(C);
6911 unsigned Bits2 = Field2->getBitWidthValue(C);
6912
6913 if (Bits1 != Bits2)
6914 return false;
6915 }
6916
6917 return true;
6918}
6919
6920/// \brief Check if two standard-layout structs are layout-compatible.
6921/// (C++11 [class.mem] p17)
6922bool isLayoutCompatibleStruct(ASTContext &C,
6923 RecordDecl *RD1,
6924 RecordDecl *RD2) {
6925 // If both records are C++ classes, check that base classes match.
6926 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
6927 // If one of records is a CXXRecordDecl we are in C++ mode,
6928 // thus the other one is a CXXRecordDecl, too.
6929 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
6930 // Check number of base classes.
6931 if (D1CXX->getNumBases() != D2CXX->getNumBases())
6932 return false;
6933
6934 // Check the base classes.
6935 for (CXXRecordDecl::base_class_const_iterator
6936 Base1 = D1CXX->bases_begin(),
6937 BaseEnd1 = D1CXX->bases_end(),
6938 Base2 = D2CXX->bases_begin();
6939 Base1 != BaseEnd1;
6940 ++Base1, ++Base2) {
6941 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
6942 return false;
6943 }
6944 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
6945 // If only RD2 is a C++ class, it should have zero base classes.
6946 if (D2CXX->getNumBases() > 0)
6947 return false;
6948 }
6949
6950 // Check the fields.
6951 RecordDecl::field_iterator Field2 = RD2->field_begin(),
6952 Field2End = RD2->field_end(),
6953 Field1 = RD1->field_begin(),
6954 Field1End = RD1->field_end();
6955 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
6956 if (!isLayoutCompatible(C, *Field1, *Field2))
6957 return false;
6958 }
6959 if (Field1 != Field1End || Field2 != Field2End)
6960 return false;
6961
6962 return true;
6963}
6964
6965/// \brief Check if two standard-layout unions are layout-compatible.
6966/// (C++11 [class.mem] p18)
6967bool isLayoutCompatibleUnion(ASTContext &C,
6968 RecordDecl *RD1,
6969 RecordDecl *RD2) {
6970 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
6971 for (RecordDecl::field_iterator Field2 = RD2->field_begin(),
6972 Field2End = RD2->field_end();
6973 Field2 != Field2End; ++Field2) {
6974 UnmatchedFields.insert(*Field2);
6975 }
6976
6977 for (RecordDecl::field_iterator Field1 = RD1->field_begin(),
6978 Field1End = RD1->field_end();
6979 Field1 != Field1End; ++Field1) {
6980 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
6981 I = UnmatchedFields.begin(),
6982 E = UnmatchedFields.end();
6983
6984 for ( ; I != E; ++I) {
6985 if (isLayoutCompatible(C, *Field1, *I)) {
6986 bool Result = UnmatchedFields.erase(*I);
6987 (void) Result;
6988 assert(Result);
6989 break;
6990 }
6991 }
6992 if (I == E)
6993 return false;
6994 }
6995
6996 return UnmatchedFields.empty();
6997}
6998
6999bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
7000 if (RD1->isUnion() != RD2->isUnion())
7001 return false;
7002
7003 if (RD1->isUnion())
7004 return isLayoutCompatibleUnion(C, RD1, RD2);
7005 else
7006 return isLayoutCompatibleStruct(C, RD1, RD2);
7007}
7008
7009/// \brief Check if two types are layout-compatible in C++11 sense.
7010bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
7011 if (T1.isNull() || T2.isNull())
7012 return false;
7013
7014 // C++11 [basic.types] p11:
7015 // If two types T1 and T2 are the same type, then T1 and T2 are
7016 // layout-compatible types.
7017 if (C.hasSameType(T1, T2))
7018 return true;
7019
7020 T1 = T1.getCanonicalType().getUnqualifiedType();
7021 T2 = T2.getCanonicalType().getUnqualifiedType();
7022
7023 const Type::TypeClass TC1 = T1->getTypeClass();
7024 const Type::TypeClass TC2 = T2->getTypeClass();
7025
7026 if (TC1 != TC2)
7027 return false;
7028
7029 if (TC1 == Type::Enum) {
7030 return isLayoutCompatible(C,
7031 cast<EnumType>(T1)->getDecl(),
7032 cast<EnumType>(T2)->getDecl());
7033 } else if (TC1 == Type::Record) {
7034 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
7035 return false;
7036
7037 return isLayoutCompatible(C,
7038 cast<RecordType>(T1)->getDecl(),
7039 cast<RecordType>(T2)->getDecl());
7040 }
7041
7042 return false;
7043}
7044}
7045
7046//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
7047
7048namespace {
7049/// \brief Given a type tag expression find the type tag itself.
7050///
7051/// \param TypeExpr Type tag expression, as it appears in user's code.
7052///
7053/// \param VD Declaration of an identifier that appears in a type tag.
7054///
7055/// \param MagicValue Type tag magic value.
7056bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
7057 const ValueDecl **VD, uint64_t *MagicValue) {
7058 while(true) {
7059 if (!TypeExpr)
7060 return false;
7061
7062 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
7063
7064 switch (TypeExpr->getStmtClass()) {
7065 case Stmt::UnaryOperatorClass: {
7066 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
7067 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
7068 TypeExpr = UO->getSubExpr();
7069 continue;
7070 }
7071 return false;
7072 }
7073
7074 case Stmt::DeclRefExprClass: {
7075 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
7076 *VD = DRE->getDecl();
7077 return true;
7078 }
7079
7080 case Stmt::IntegerLiteralClass: {
7081 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
7082 llvm::APInt MagicValueAPInt = IL->getValue();
7083 if (MagicValueAPInt.getActiveBits() <= 64) {
7084 *MagicValue = MagicValueAPInt.getZExtValue();
7085 return true;
7086 } else
7087 return false;
7088 }
7089
7090 case Stmt::BinaryConditionalOperatorClass:
7091 case Stmt::ConditionalOperatorClass: {
7092 const AbstractConditionalOperator *ACO =
7093 cast<AbstractConditionalOperator>(TypeExpr);
7094 bool Result;
7095 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
7096 if (Result)
7097 TypeExpr = ACO->getTrueExpr();
7098 else
7099 TypeExpr = ACO->getFalseExpr();
7100 continue;
7101 }
7102 return false;
7103 }
7104
7105 case Stmt::BinaryOperatorClass: {
7106 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
7107 if (BO->getOpcode() == BO_Comma) {
7108 TypeExpr = BO->getRHS();
7109 continue;
7110 }
7111 return false;
7112 }
7113
7114 default:
7115 return false;
7116 }
7117 }
7118}
7119
7120/// \brief Retrieve the C type corresponding to type tag TypeExpr.
7121///
7122/// \param TypeExpr Expression that specifies a type tag.
7123///
7124/// \param MagicValues Registered magic values.
7125///
7126/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
7127/// kind.
7128///
7129/// \param TypeInfo Information about the corresponding C type.
7130///
7131/// \returns true if the corresponding C type was found.
7132bool GetMatchingCType(
7133 const IdentifierInfo *ArgumentKind,
7134 const Expr *TypeExpr, const ASTContext &Ctx,
7135 const llvm::DenseMap<Sema::TypeTagMagicValue,
7136 Sema::TypeTagData> *MagicValues,
7137 bool &FoundWrongKind,
7138 Sema::TypeTagData &TypeInfo) {
7139 FoundWrongKind = false;
7140
7141 // Variable declaration that has type_tag_for_datatype attribute.
7142 const ValueDecl *VD = NULL;
7143
7144 uint64_t MagicValue;
7145
7146 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
7147 return false;
7148
7149 if (VD) {
7150 for (specific_attr_iterator<TypeTagForDatatypeAttr>
7151 I = VD->specific_attr_begin<TypeTagForDatatypeAttr>(),
7152 E = VD->specific_attr_end<TypeTagForDatatypeAttr>();
7153 I != E; ++I) {
7154 if (I->getArgumentKind() != ArgumentKind) {
7155 FoundWrongKind = true;
7156 return false;
7157 }
7158 TypeInfo.Type = I->getMatchingCType();
7159 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
7160 TypeInfo.MustBeNull = I->getMustBeNull();
7161 return true;
7162 }
7163 return false;
7164 }
7165
7166 if (!MagicValues)
7167 return false;
7168
7169 llvm::DenseMap<Sema::TypeTagMagicValue,
7170 Sema::TypeTagData>::const_iterator I =
7171 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
7172 if (I == MagicValues->end())
7173 return false;
7174
7175 TypeInfo = I->second;
7176 return true;
7177}
7178} // unnamed namespace
7179
7180void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
7181 uint64_t MagicValue, QualType Type,
7182 bool LayoutCompatible,
7183 bool MustBeNull) {
7184 if (!TypeTagForDatatypeMagicValues)
7185 TypeTagForDatatypeMagicValues.reset(
7186 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
7187
7188 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
7189 (*TypeTagForDatatypeMagicValues)[Magic] =
7190 TypeTagData(Type, LayoutCompatible, MustBeNull);
7191}
7192
7193namespace {
7194bool IsSameCharType(QualType T1, QualType T2) {
7195 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
7196 if (!BT1)
7197 return false;
7198
7199 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
7200 if (!BT2)
7201 return false;
7202
7203 BuiltinType::Kind T1Kind = BT1->getKind();
7204 BuiltinType::Kind T2Kind = BT2->getKind();
7205
7206 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
7207 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
7208 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
7209 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
7210}
7211} // unnamed namespace
7212
7213void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
7214 const Expr * const *ExprArgs) {
7215 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
7216 bool IsPointerAttr = Attr->getIsPointer();
7217
7218 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
7219 bool FoundWrongKind;
7220 TypeTagData TypeInfo;
7221 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
7222 TypeTagForDatatypeMagicValues.get(),
7223 FoundWrongKind, TypeInfo)) {
7224 if (FoundWrongKind)
7225 Diag(TypeTagExpr->getExprLoc(),
7226 diag::warn_type_tag_for_datatype_wrong_kind)
7227 << TypeTagExpr->getSourceRange();
7228 return;
7229 }
7230
7231 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
7232 if (IsPointerAttr) {
7233 // Skip implicit cast of pointer to `void *' (as a function argument).
7234 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5a249802012-11-03 16:07:49 +00007235 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkob57ce4e2012-11-03 22:10:18 +00007236 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00007237 ArgumentExpr = ICE->getSubExpr();
7238 }
7239 QualType ArgumentType = ArgumentExpr->getType();
7240
7241 // Passing a `void*' pointer shouldn't trigger a warning.
7242 if (IsPointerAttr && ArgumentType->isVoidPointerType())
7243 return;
7244
7245 if (TypeInfo.MustBeNull) {
7246 // Type tag with matching void type requires a null pointer.
7247 if (!ArgumentExpr->isNullPointerConstant(Context,
7248 Expr::NPC_ValueDependentIsNotNull)) {
7249 Diag(ArgumentExpr->getExprLoc(),
7250 diag::warn_type_safety_null_pointer_required)
7251 << ArgumentKind->getName()
7252 << ArgumentExpr->getSourceRange()
7253 << TypeTagExpr->getSourceRange();
7254 }
7255 return;
7256 }
7257
7258 QualType RequiredType = TypeInfo.Type;
7259 if (IsPointerAttr)
7260 RequiredType = Context.getPointerType(RequiredType);
7261
7262 bool mismatch = false;
7263 if (!TypeInfo.LayoutCompatible) {
7264 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
7265
7266 // C++11 [basic.fundamental] p1:
7267 // Plain char, signed char, and unsigned char are three distinct types.
7268 //
7269 // But we treat plain `char' as equivalent to `signed char' or `unsigned
7270 // char' depending on the current char signedness mode.
7271 if (mismatch)
7272 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
7273 RequiredType->getPointeeType())) ||
7274 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
7275 mismatch = false;
7276 } else
7277 if (IsPointerAttr)
7278 mismatch = !isLayoutCompatible(Context,
7279 ArgumentType->getPointeeType(),
7280 RequiredType->getPointeeType());
7281 else
7282 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
7283
7284 if (mismatch)
7285 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
7286 << ArgumentType << ArgumentKind->getName()
7287 << TypeInfo.LayoutCompatible << RequiredType
7288 << ArgumentExpr->getSourceRange()
7289 << TypeTagExpr->getSourceRange();
7290}